我无法将我的django应用程序发布到数据库。我正在尝试传递我的外键,以便我可以正确发布。
对不起,如果这是基本的我不知道我刚刚开始。我认为它永远不会形成= ResultForm(request.POST)。然后给我一个form = ResultForm。
这是我的代码:
型号:
class Result(models.Model):
category = models.ForeignKey(Category)
category_result = models.CharField(max_length=200)
rating = models.DecimalField('', '', 8, 3)
votes = models.IntegerField(default=0)
created_by = models.IntegerField(default=0, null=True, blank=True)
created_on = models.DateTimeField('created on')
def __unicode__(self):
return self.category_result
形式:
class ResultForm(forms.ModelForm):
category_result = forms.CharField(max_length=200,help_text="Your best line")
rating = forms.DecimalField(widget=forms.HiddenInput(), initial=0)
votes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
created_by = forms.IntegerField(widget=forms.HiddenInput(), initial=1)
category = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = Result
fields = ('category_result', 'rating', 'votes')
视图:
def help_out(request, category_id):
if request.method == 'POST':
form = ResultForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.category = category_id
form.save()
return index(request)
else:
print form.errors
else:
form = ResultForm
context = {'form': form, 'category_id': category_id}
return render(request,'pocketwingman/help_out.html', context)
模板:
<!DOCTYPE html>
<html>
<head>
<title>Pocketwingman</title>
</head>
<body>
<h1>Add a Result</h1>
<form id="result_form" method="post" action="/pocketwingman/help_out/{{category_id}}/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text}}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Line" />
</form>
</body>
</html>
url config:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<category_id>\d+)/$', views.help_me, name='help_me'),
url(r'^help_out/(?P<category_id>\d+)/$', views.help_out, name='help_out'),
)
答案 0 :(得分:1)
如果表格不是POST,您应该发表表格:
else:
form = ResultForm()
将()
附加到表格。