本文介绍了未提交Django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个在模板中正确呈现的 Django 模型/视图/表单,但它没有提交输入到数据库的数据.对此的任何帮助将不胜感激!
I have a Django model/view/form that is rendering correctly in the template, but it is not submitting the data that is input to the database. Any help with this would be greatly appreciated!
#models.py
from django.db import models
from django.forms import ModelForm
class UserRegistration(models.Model):
user_first = models.CharField(max_length=50)
user_last = models.CharField(max_length=50)
user_email = models.EmailField()
#user_fantasyhost = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s %s' % (self.user_first, self.user_last, self.user_email)
class RegForm(ModelForm):
class Meta:
model = UserRegistration
#views.py
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from acme.dc_django.models import UserRegistration
from acme.dc_django.models import RegForm
def regPage(request, id=None):
form = RegForm(request.POST or None,
instance=id and UserRegistration.objects.get(id=id))
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/league_setup/')
user_info = UserRegistration.objects.all()
context = {
'form':form,
'user_info' :user_info,
}
return render(request, 'regpage.html', context)
#repage.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="/league/">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account"
</form><br /><br />
</body>
</HTML>
感谢您的帮助,
dp
推荐答案
我试过你的代码.您的问题是您的 html 表单标签 的 action 属性设置为/league/".
I tried your code. Your problem is that the action attribute of your html form tag is set to "/league/".
除非 reqPage url 实际上是/league/",否则它不会工作.当我将 action="/league/"
更改为 action=""
时:
Unless reqPage url is actually "/league/", it won't work. When i changed action="/league/"
to action=""
as such:
<HTML lang="en">
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Create Account" />
</form><br /><br />
</body>
</HTML>
表单确实起作用了:
In [3]: UserRegistration.objects.all()
Out[3]: [<UserRegistration: aoeu oeu oeu@aeou.com>]
这篇关于未提交Django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!