当我在我的front_end中编写或编辑某些内容时,它不会保存那些编辑内容。它重定向到详细视图并显示早期数据。我在哪里做错了?
我的代码
Models.py
from django.db import models
from django.template.defaultfilters import slugify
# Create your moels here.
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(blank=True,default='')
body = models.TextField()
created_date = models.DateTimeField(auto_now_add=True,blank=True,null=True)
def __str__(self):
return self.title
def save(self, *args,**kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post,self).save(*args,**kwargs)
Forms.py
from .models import Post
from django import forms
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','body']
应用程序/ urls.py
urlpatterns = [ path('post/<int:pk>/edit/',views.edit_view, name = "edit_view")]
Views.py
def edit_view(request,pk):
try:
post = Post.objects.get(pk=pk)
except:
raise Http404('Page Not Found')
form = PostForm(request.POST or None,instance= post)
print(request.method)
if request.method == 'POST':
if form.is_valid:
form.save()
return redirect('detail_view', pk=pk)
else:
return render(request, 'edit.html',{'form_edit': form})
模板 edit.html
<form method="post" >
{% csrf_token %}
{{form_edit.as_p}}
<input type="submit" value="ok">
</form>
答案 0 :(得分:1)
在模型中,仅当未设置实例的slug值时,才调用save()
方法。您需要像这样重写模型的save()
:
def save(self, *args,**kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post,self).save(*args,**kwargs)
如果super().save()
已填满且状态为空,则会在两种情况下调用self.slug
。