Search code examples
djangodjango-formsdjango-viewsdjango-generic-views

Generic UpdateView isn't working with slug


I'm pretty new to django.I am trying to update a post with generic UpdateView. But the post isn't updating after filling up the form.Im accessing the update view through slug url.

My model:

class Post(models.Model):
title = models.CharField(max_length=60)
post_body = models.TextField()
time_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE)
slug = models.SlugField(null=False,unique=True)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('postdetail', kwargs={'slug': self.slug})

def save(self,*args,**kwargs):
    if not self.slug:
        author_id = str(self.author.id)
        self.slug = slugify(self.title +'-'+author_id)
        return super().save(*args, **kwargs)

My view:

class postupdate(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
model = Post
fields = ['title','post_body']

def form_valid(self, form):
    form.instance.author = self.request.user
    return super().form_valid(form)

def test_func(self):
    post = self.get_object()
    if self.request.user == post.author:
        return True
    else:
        return False

My url:

path('post/<slug:slug>/updatepost/', postupdate.as_view(),name = 'updatepost'),

Solution

  • It seems the save() method is not getting called every time.

    class Post(models.Model):
        # rest of your code
    
        def save(self, *args, **kwargs):
            if not self.slug:
                author_id = str(self.author.id)
                self.slug = slugify(self.title + '-' + author_id)
    
            return super().save(*args, **kwargs) # outside the `if...` clause