尝试按照this教程进行非常小的修改,将表单和模板应用到我的对象的模型中,但是遇到错误我无法解决。这应该很简单,模型创建表单,表单保存并重定向到详细页面。
据我所知,调用HttpResponseRedirect是导致错误的原因,但我不知道为什么或问题是什么。代码似乎与我在教程中看到的内容匹配(尽可能接近),以及我在django表单文档页面和其他教程中看到的内容。也许这是愚蠢的我只是没有看到它,但我现在已经尝试了几个小时,我需要另外一套眼睛。请帮忙。我搞砸了什么?提前谢谢。
我得到的错误是:
private List<Person> visiblePersons;
public List<Person> VisiblePersons
{
get { return visiblePersons; }
set
{
visiblePersons = value;
OnPropertyChanged();
}
}
这是我的urls.py:
__init__() got an unexpected keyword argument 'pk'
相关views.py视图:
app_name = 'jobs'
urlpatterns = [
# /jobs/
url(r'^$', views.IndexView.as_view(), name='list'),
url(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'),
url(r'^edit/(?P<pk>[0-9]+)/$', views.edit, name='edit'),
url(r'^edit/$', views.new, name='new'),
]
forms.py文件:
def new(request):
if request.method == "POST":
form = JobForm(request.POST)
if form.is_valid():
job = form.save(commit=False)
user = request.user
member = Member.objects.get(user=user)
buyer = Buyer.objects.get(member=member)
job.buyer = buyer
job.buyer_paid = False
job.freelancers_paid = False
#job.created = timezone.now()
job.save()
return HttpResponseRedirect('detail', pk=job.pk)
else:
form = JobForm()
return render(request, 'jobs/edit.html', {'form': form})
回溯:
class JobForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(JobForm, self).__init__(*args, **kwargs)
class Meta:
model = Job
fields = (
'handle',
'name',
'venue',
'room',
'start_on',
'end_on',
'contact',
'description',
'instructions',
'dress_code',
)
编辑添加:发生此错误时,数据会保存在数据库中。
答案 0 :(得分:3)
您将pk
传递给HttpResponseRedirect
:
HttpResponseRedirect('detail', pk=job.pk)
HttpResponseRedirect
应该将用户重定向到另一个URL。要从您的urlconf构建网址,您可以使用此处描述的多个方法:https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls
我会选择像这样使用reverse
:
HttpResponseRedirect(reverse('detail', kwargs={"pk": job.pk}))
最终的代码如下:
from django.core.urlresolvers import reverse
# [ other codes ]
def new(request):
if request.method == "POST":
form = JobForm(request.POST)
if form.is_valid():
job = form.save(commit=False)
user = request.user
member = Member.objects.get(user=user)
buyer = Buyer.objects.get(member=member)
job.buyer = buyer
job.buyer_paid = False
job.freelancers_paid = False
#job.created = timezone.now()
job.save()
return HttpResponseRedirect(reverse('detail', kwargs={"pk": job.pk}))
注意: redirect
函数使用reverse
来解析网址。