简体   繁体   English

如何使用 model forms 更新 django 中的博客文章?

[英]How do I update blog article in django using model forms?

I am creating a blog using django.我正在使用 django 创建一个博客。 I am using model Forms for input.I want to edit an existing blog post, but I can't get this to work.我正在使用 model Forms 进行输入。我想编辑现有的博客文章,但我无法让它工作。

models.py模型.py

class tags(models.Model):
name = models.CharField(max_length = 30)
def __str__(self):
    return self.name

class Article(models.Model):
    title = models.CharField(max_length=60)
    post = HTMLField()
    editor = models.ForeignKey(User,on_delete=models.CASCADE)
    tag = models.ManyToManyField(tags,blank=True)
    pub_date = models.DateTimeField(auto_now_add=True)
    article_image = models.ImageField(upload_to='articles/', blank=True)
    photo_credits = models.CharField(max_length=60,default='unsplash.com')

Forms.py Forms.py

class UpdateArticleForm(forms.ModelForm):
class Meta:
    model = Article
    fields = ['title','article_image','post','tags','photo_credits']

Views.py视图.py

@login_required(login_url='/accounts/login/')
    def update_article(request,id):
    instance = Article.objects.get(id = id)
    if request.method == 'POST':
        form = UpdateArticleForm(request.POST, request.FILES,instance=instance)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = UpdateArticleForm(instance=instance)
    return render(request,'article/update.html',{'form':form})

urls.py网址.py

url(r'^article/update/$',views.update_article,name='update_article'),

I get a 404 error.and if I replace the url with the below I get a Reverse for 'update_article' with no arguments not found. 1 pattern(s) tried: ['article/update/(?P<id>[0-9]+)/$']我收到 404 错误。如果我将 url 替换为下面的内容,我会得到一个Reverse for 'update_article' with no arguments not found. 1 pattern(s) tried: ['article/update/(?P<id>[0-9]+)/$'] Reverse for 'update_article' with no arguments not found. 1 pattern(s) tried: ['article/update/(?P<id>[0-9]+)/$']

    url(r'^article/update/(?P<id>[0-9]+)/$',views.update_article,name='update_article'),

How can I get this to work?我怎样才能让它工作?

Your views and url configurations are correct, errors probably reside in your templates.您的视图和 url 配置是正确的,错误可能存在于您的模板中。 Try to find {% url "update_article" %} in your template and replace with {% url "update_article" <article_id> %}尝试在您的模板中找到{% url "update_article" %}并替换为{% url "update_article" <article_id> %}

Note that you have 'tags' field in the form, but in model you name it 'tag'.请注意,表单中有“标签”字段,但在 model 中,您将其命名为“标签”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM