简体   繁体   中英

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

I am creating a blog using django. I am using model Forms for input.I want to edit an existing blog post, but I can't get this to work.

models.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

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

Views.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

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]+)/$'] 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. Try to find {% url "update_article" %} in your template and replace with {% url "update_article" <article_id> %}

Note that you have 'tags' field in the form, but in model you name it 'tag'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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