嗨,我是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'),
{% 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 %}
提前致谢
答案 0 :(得分:1)
您在模板中使用变量form
,但是您将UserRegisterForm
和ContactForm
作为模板上下文传递。
尝试类似:
<form...>
{{ UserRegisterForm }}
{% for form in ContactForm %}
{{ form }}
{% endfor %}
</form>
两个提示:
答案 1 :(得分:0)
您已使用密钥UserRegisterForm
和ContactForm
向模板发送了两个变量。您必须在模板中使用这些名称,而不仅仅是form
。