我是Django的新手。我只是学习使用表单和模型。在这里,我使用了modelforms来获取两个字段(用户名和密码)并保存它。我想要做的是获取该用户名的模型ID。下面是代码。但我无法得到身份证。
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from reg.models import registration, registrationform
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
p = registration.objects.all()
for loop in p:
if loop.username == username:
id = loop.id
return HttpResponseRedirect(reverse('reg.views.thanks', args=(id)))
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
def thanks(request, id):
p = get_object_or_404(registration, pk=id)
return render_to_response('thanks.html', {'reg': p)
还有一个问题。密码的型号字段是什么?
感谢。
答案 0 :(得分:2)
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
data =form.save()
#...
id = data.id
#...
return HttpResponseRedirect(reverse('reg.views.thanks', args=(id)))
答案 1 :(得分:0)
user = form.save(commit=False)
user.first_name = u'First name'
user.last_name = u'Last name'
user.save()
密码使用密码1字段
答案 2 :(得分:0)
如何将注册功能更改为:
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
userdetails = form.save()
user = userdetails.username
val = registration.objects.get(username = user)
return HttpResponseRedirect(reverse('reg.views.thanks', args=(val.id)))
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
我建议你阅读:https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
答案 3 :(得分:0)
请问你可以粘贴urls.py
吗?
我最近遇到的问题几乎与此完全相同 - 这只是一个错字,我在url函数的第二个字段中输入了错误的值:
url(r'^people/thanks/(?P<person_id>\d+)$', 'people.views.thanks'),
应该是:
url(r'^people/thanks/(?P<person_id>\d+)$', 'people.views.new'),