Django:从字段中获取数据并插入与用户相关的2个表中

时间:2019-06-10 18:33:56

标签: django forms django-orm

我有2个字段(电子邮件和电话)的基本html表单。我有3种型号:

models.py

class Person(models.Model):
    name = models.CharField()
    surname = models.Charfield()

class Email(models.Model):
    person = models.ForeignKey(Person,editable=False,on_delete=models.CASCADE)
    email = model.EmailField()

class Phone(models.Model):
    person = models.ForeignKey(Person,editable=False,on_delete=models.CASCADE)
    phone = models.CharField()

在我的 views.py

/imports/

def home(request):
    context = {'users': Person.object.all()}
    return render(request,'app/home.html',context)

和我的 home.html

{% block content %}
{% for user in users %}
Displaying user's attributes

{% for email in user.email_set.all %}
{{ email }}

{% endfor %}
<form method="POST">
<input type="email">
<input type="label">
<button type="submit">Add data</button>
</form>
{% endfor %}
{% endblock content %}

因此,单击按钮后,我想从字段中获取数据并将其添加到数据库的2个表中,并且此数据必须与单击的用户相关。我知道我应该使用 forms.py ,但是我尝试不使用它。有解决这个问题的简便方法吗?

1 个答案:

答案 0 :(得分:0)

使用ModelForm创建表单。然后,如果要添加,更新或删除phoneemail,则可以使用 formset_factory 从其他视图进行操作。我建议像这样。

forms.py

from yourapp.models import Person, Email, Phone
from django.forms impot ModelForm


class EmailForm(ModelForm):
    class Meta:
        model = Person
        fields = '__all__'

views.py

from django.forms import formset_factory


def view_to_update_person_data(request, pk):
    person = get_object_or_404(Person, pk)
    email_formset = model_factory(EmailForm, extra=2)
    for email in person.email_set.all():
        email_formset = email_formset(initial=[{'person': email}]

    if request.method == 'POST':
        # you can proceed one formset by one
        if email_formset.is_valid():
            instances = email_formset.save(commit=false)
            for i in instances:
                i.person = person
                i.save()

    ctx = {'email_formset': email_formset,
           'phone_form': phone_form,
    }
    return TemplateResponse(request, 'your/template/html', ctx)


了解如何在working with forms page中使用表单集