"后"方法条件不能在django表单中编辑和保存

时间:2017-01-12 13:20:09

标签: django python-3.x django-forms

单击表单中的编辑方法后,模型的数据将加载到表单视图中,但是当我单击“保存”按钮时,不会保存该值,而是再次使用相同的值重新加载页面。通过表单将新表单保存在数据库中可以正常工作

views.py

def sessioncreate(request):
if request.method=="GET":
    form=SessionForm();
    return  render(request,'app/sessions_form.html',{'form':form});
elif request.method=="POST":
    form=SessionForm(request.POST);
    form.save();
    return HttpResponseRedirect('/sessions');


def SessionUpdate(request,pk):
    post = get_object_or_404(Sessions, pk=pk)
    if request.method == "post":
        form = SessionForm(request.POST)
        form.save()
        return RedirectView('/sessions',pk=form.pk);
    else:
        form = SessionForm(instance=post)


return  render(request,'app/sessions_form.html',{'form':form});

models.py

class Sessions(models.Model):
    title=models.CharField(max_length=50)
    abstract=models.CharField(max_length=2000)
    track=models.ForeignKey(Track)
    speaker=models.ForeignKey(Speaker)
    status=models.CharField(max_length =1, choices=SESSION_STATUSES)
 # returning name in site 
def __str__(self):
    return self.title
def get_absolute_url(self):
    return reverse('sessions_detail', kwargs={'pk':self.pk})

class SessionForm(forms.ModelForm):
   class Meta:
       model=Sessions;
       fields=['title','abstract','track','speaker'];

url.py

    url(r'^sessions/$',views.SessionList.as_view(),name='sessions_list'),
url(r'^sessions/(?P<pk>[0-9]+)/$',views.SessionDetail.as_view() ,   name='sessions_details'),

url(r'^sessions/create/$',views.sessioncreate, name='sessions_create'),
url(r'^sessions/update/(?P<pk>[0-9]+)/$',views.SessionUpdate , name='sessions_update'),
url(r'^sessions/delete/(?P<pk>[0-9]+)/$',views.SessionDelete.as_view() , name='sessions_delete'),

session_form.html

{% extends 'layout.html' %}



{% block content %}
<form method="post">
    {% csrf_token%}
    {{form.as_table}}
      <button type="submit">Save</button>

</form>

{% endblock %}

2 个答案:

答案 0 :(得分:1)

方法都是上限。您应该检查if request.method == 'POST'

另请注意,您永远不会检查您的表格是否有效;你应该在保存之前调用if form.is_valid()

答案 1 :(得分:0)

这是我的最终views.py更新文件,它有效...我可以从中删除多余的内容?

def SessionUpdate(request,pk):
form_class=SessionForm
post = get_object_or_404(Sessions, pk=pk)
form = SessionForm(request.POST)
if request.method == "POST":
    if form.is_valid():
        form = SessionForm(request.POST, instance=post)
        form.save()
        return HttpResponseRedirect('/sessions')
else:
    form = SessionForm(instance=post)


return  render(request,'app/sessions_form.html',{'form':form});