我希望在 ModelForm 中自动设置 PestReport 国家,但使用以下代码不断收到以下错误:
TypeError at /countries/italy/pestreports/create/
pest_report_create() got an unexpected keyword argument 'country'
我最终还需要确保用户只能添加与其个人资料所在国家/地区相同的国家/地区的害虫报告。我正在使用django-countries。
如何在下面的代码中自动将 URL 的关键字参数设置为表单(用户不应选择国家)?
网址.py
from django.conf.urls import patterns, include, url
from .ippc.views import pest_report_create
urlpatterns = patterns("",
# pest report add
url(r'^countries/(?P<country>[\w-]+)/pestreports/create/$',
view=pest_report_create,
name='pest-report-create'),
)
模型.py:
from django.db import models
from django import forms
from django_countries.fields import CountryField
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
class IppcUserProfile(models.Model):
user = models.OneToOneField("auth.User")
country = CountryField(_("Country"))
class PestReport(models.Model):
country = CountryField(_("Country"))
author = models.ForeignKey(User, related_name="pest_report_author")
class PestReportForm(forms.ModelForm):
class Meta:
model = PestReport
视图.py:
from .models import UserProfile, PestReport, PestReportForm
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404, redirect
def pest_report_create(request):
if request.method == "POST":
form = form(request.POST, instance=PestReport())
user = request.user
author_id = user.id
profile_user = request.profile_user
country = profile_user.country
if form.is_valid():
new_pest_report = form.save(commit=False)
new_pest_report.author_id = author_id
new_pest_report.country = country
form.save()
return HttpResponseRedirect('/thank-you/')
else:
form = form(instance=PestReport())
return render_to_response('countries/pest_report_create.html', {'form': form},
context_instance=RequestContext(request))
感谢Peter Tinkler的回答,更新了 views.py 函数(现在可以使用):
def pest_report_create(request, country):
user = request.user
author = user
country=user.get_profile().country
form = PestReportForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
new_pest_report = form.save(commit=False)
new_pest_report.author = request.user
new_pest_report.author_id = author.id
form.save()
return redirect("pest-report-detail", country=country, year=new_pest_report.publish_date.strftime("%Y"), month=new_pest_report.publish_date.strftime("%m"), slug=new_pest_report.slug)
else:
form = PestReportForm(initial={'country': country}, instance=PestReport())
return render_to_response('countries/pest_report_create.html', {'form': form},
context_instance=RequestContext(request))
国家/模板/pest_report_create.html:
{% extends "base.html" %}
{% block main %}
<form class="customform" method="POST" action="">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.as_p }}
<input type="submit" value="Submit />
</form>
{% endblock %}