一个视图中的不同模型

时间:2016-07-25 13:19:41

标签: python django

嗨,我是django的新手。我想知道我是否可以在一个视图中使用不同的模型。 所以我看了这页https://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ 它非常有用,但我无法在浏览器页面上看到输出。我在哪里弄错了?

我的观点

from .models import Contact, MyUser
from .forms import ContactForm, UserRegisterForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def total_register(request):
uform = UserRegisterForm()
cform = ContactForm()
if request.method == "POST":
    uform = UserRegisterForm(request.POST or None, instance=MyUser())
    cform = [ContactForm(request.POST or None, prefix=str(x), instance=Contact()) for x in range(0,19)]
    if uform.is_valid() and all([cf.is_valid() for cf in cform]):
        new_MyUser = uform.save()
        for cf in cform:
            new_contact = cf.save(commit=False)
            new_contact.MyUser = new_MyUser
            new_contact.save()
        return HttpResponseRedirect('/')
else:
                pform = UserRegisterForm(instance=MyUser())
                cform = [ContactForm(prefix=str(x), instance=Contact()) for x in range(0,19)]
return render_to_response('total_register.html', {'UserRegisterForm': uform, 'ContactForm': cform})

我的表格

class UserRegisterForm(forms.ModelForm):
username = forms.CharField(label = 'isminizi giriniz')
lastname = forms.CharField(label = 'soyisminizi giriniz')    
password = forms.CharField(widget=forms.PasswordInput)


class Meta:
    model = User
    fields = [
        'username',
        'lastname',
    ]
def signup(self, request, user):
    user.username = self.cleaned_data['username']
    user.lastname = self.cleaned_data['lastname']


    user.save()




class ContactForm(forms.ModelForm):
class Meta:
    model = Contact
    fields = ['username','soyad','cinsiyet','unvan','kurum',"bolum","gorev", "uzmanlik","adres","posta_kodu","sehir","ulke","is_tel","ev_tel","fax_no","cep_tel","email"]

我的网址

    url(r'^kayit/', bildirge.views.total_register, name = 'kayit'),

我的HTML

{% extends "base.html" %}
{% load crispy_forms_tags %}


{% block content %}
<div class='col-sm-6 col-sm-offset-3'>
<h1>{{ title }}</h1>
<hr/>

<form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{ form|crispy }}
<button type='submit'>gonder</button>
</form>
</div>
{% endblock content %}

提前致谢

2 个答案:

答案 0 :(得分:1)

您在模板中使用变量form,但是您将UserRegisterFormContactForm作为模板上下文传递。

尝试类似:

<form...>

{{ UserRegisterForm }}
{% for form in ContactForm %}
{{ form }}
{% endfor %}
</form>

两个提示:

  • 查看formsets以处理多种相同类型的表单
  • 请确保您的代码正确缩进,尤其是使用Python

答案 1 :(得分:0)

您已使用密钥UserRegisterFormContactForm向模板发送了两个变量。您必须在模板中使用这些名称,而不仅仅是form