简体   繁体   中英

Facing problems redirecting user using django post_save signal

When ever a user creates a new chat thread, i want to automatically redirect them to the thread. But facing problems

example my models

class Thread(models.Model):
    name=models.CharField()
    creator=models.ForeignKey(User)
class Chat(models.Model):
    thread=models.ForeignKey(Thread)
    message=models.TextField()

User creates a thread , and has to be redirected to the created thread('app:chat',pk) displaying the Chatform and thread name.

I tried using django post_save signal to redirect the user after creating a thread

def redirect_user(sender,instance,**kwargs)
    pk=instance.id
    url=('app:chat',pk)
    post_save.connect(redirect_user,sender=Thread)

Well this is not working. Please help with a good approach to solve this problem.

You should be doing that in your view where your form is rendered afaic. If the form is valid then model instance's id should be accessible by the form instance and you may call return redirect("chat", args=(new_id,)) where "chat" is reversed name.

If you use Django's generic class based views you can quite easily get this functionality

You should use a CreateView for this and then override the get_success_url method to redirect the user. Classy class based views is a great website for exploring all options for the generic views

class ThreadCreateView(CreateView):

    model = Thread

    def get_success_url(self):
        return reverse('app:chat', args=[self.object.pk])

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