问题
I'm using Django 1.11.
I'm using Class based view for update profile page, to updated auth user profile info.
myapp/accounts/views.py
class UpdateProfile(UpdateView):
model = User
fields = ['first_name', 'last_name']
template_name = 'accounts/update.html'
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.request = None
def get_object(self, queryset=None):
return self.request.user
This works fine for updating profile. But after update, it gives error
No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
I followed some YouTube tutorials here which is using method based view and form.py
to generate form, There I can check for request method and call form.save()
and then redirect user to profile page (probably index).
1. How can I do I check if data updated and then redirect user to index
class in my class?
2. Is this method suitable for editing data using pk
?
I also want to generate flash message after updation for which I can use
messages.success(request, "Profile updated")
3. Since class is not have request object, how to use messages
in class based view?
回答1:
You can use the get_success_url
method.
def get_success_url(self):
messages.success(self.request, 'Profile updated')
return '/' # or whatever url you want to redirect to
The object request is in the self
. Note that i don't understand why in your init you're doing self.request = None
.
来源:https://stackoverflow.com/questions/46193057/redirect-user-after-update-in-class-based-view-in-django