Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

Django post single form to 1 model and another model twice

I have a customer form containing name, email, email2 and email3 inputs. I would like to save the form using a class based view and post name and email to Customer model and iterate thru email2 and email3 and post to AdditionalEmail model, which has a foreign key to the customer model. I got it to work using a function based view, but the code seems a bit...hacky to me and I wanted to see if someone had a better way to do this, preferably using a CBV instead of FBV. Here is what I have:

models.py

class Customer(models.Model):
    name = models.CharField(max_length=100, unique=True)
    email = models.EmailField(max_length=64, null=True, blank=True)

    def __str__(self):
        return f"{self.name}"

    def get_absolute_url(self):
        return reverse('customer_list')

    class Meta(object):
        ordering = ['name']


class AdditionalEmail(models.Model):
    name = models.ForeignKey(Customer, on_delete=models.CASCADE)
    email = models.EmailField(max_length=64, null=True, blank=True)

    def __str__(self):
        return f"{self.email}"

    class Meta(object):
        ordering = ['name']

forms.py

class CustomerForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = '__all__'
        widgets = {
            'name': forms.TextInput(attrs={'autofocus': 'true', 'class': 'form-control'}),
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
        }


class AdditionalEmailForm(forms.ModelForm):
    class Meta:
        model = AdditionalEmail
        fields = ['email']
        widgets = {
            'email': forms.EmailInput(attrs={'class': 'form-control'}),
        }

views.py

def CustomerCreateView(request):
    if request.method == 'POST':
        customer_form = CustomerForm(request.POST)
        email_form2 = AdditionalEmailForm(request.POST, prefix='email2')
        email_form3 = AdditionalEmailForm(request.POST, prefix='email3')

        if customer_form.is_valid() and email_form2.is_valid() and email_form3.is_valid():
            customer = customer_form.save()
            additionalEmail = email_form2.save(commit=False)
            additionalEmail.name = customer
            additionalEmail.save()
            additionalEmail = email_form3.save(commit=False)
            additionalEmail.name = customer
            additionalEmail.save()
            return redirect('customer_list')
    else:
        customer_form = CustomerForm()
        email_form2 = AdditionalEmailForm(prefix='email2')
        email_form3 = AdditionalEmailForm(prefix='email3')

    context = {
        'customer_form': customer_form,
        'email_form2': email_form2,
        'email_form3': email_form3,
    }

    return render(request, 'customers/customer_create.html', context)

customer_create.html

<form action="." method="POST" id="customerForm" enctype="multipart/form-data">
    {% csrf_token %}
    <div>
        <label for="{{ customer_form.name.id_for_label }}">Name</label>
        {{ customer_form.name }}
    </div>
    <div>
        <label for="{{ customer_form.email.id_for_label }}">Email Address</label>
        {{  customer_form.email }}
    </div>
    <div>
        <label for="{{ email_form2.email.id_for_label }}">2nd Email Address</label>
        {{ email_form2.email }}
    </div>
    <div>
        <label for="{{ email_form3.email.id_for_label }}">3rd Email Address</label>
        {{ email_form3.email }}
    </div>

This process gets me what I need to the db, but it seems very inefficient and redundant. I've looked into formsets, inlineformset_factory, modelformset_factory but I'm new to Django and can't seem to assemble all the moving parts to accomplish this task, especially trying to save email2 and email3 to the same model which is separate from saving name and email to a different model. Any help or suggestions will be greatly appreciated!

question from:https://stackoverflow.com/questions/65897177/django-post-single-form-to-1-model-and-another-model-twice

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...