Search code examples
pythondjangodjango-modelsdjango-viewsdjango-forms

NoReverseMatch for submitting my form on my profile page


I have a blog project for a assignment and i have all functionality except for my user profiles editing and deleting.

I have created the profile page and ability to edit the page. When i then submit my update request, i can see that it submits the change as after i get the error the profile page is updated.

I am getting this error and i know it is due to the redirect but i cannot figure out for the life of me how to just redirect back to the user profile. I have tried to just use a httpredirect or reverse and now using reverse_lazy as that has worked fine for blog posts and comments and edits.

This is my error and code bellow. I belive it is down to the get_success_url and am hoping that someone has had this error or knows the best fix for this. Thank you

NoReverseMatch at /1/edit_profile_page/ Reverse for 'show_profile_page' with no arguments not found. 1 pattern(s) tried: ['(?P[0-9]+)/profile/\Z']

Views.py

class EditProfile(LoginRequiredMixin,
                  SuccessMessageMixin,
                  UserPassesTestMixin,
                  generic.UpdateView):
    model = Profile
    template_name = 'edit_profile_page.html'
    form_class = ProfileForm
    success_message = 'Updated Profile'

    def get_success_url(self):
        return reverse_lazy('show_profile_page')

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

    def test_func(self):
        profile = self.get_object()
        if self.request.user == profile.user:
            return True
        return False

URLS.PY

urlpatterns = [
    path('<int:pk>/profile/', ShowProfilePageView.as_view(),
         name="show_profile_page"),
    path('<int:pk>/edit_profile_page/', EditProfile.as_view(),
         name='edit_profile_page'),
]

FORMS.PY

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = [
            'bio',
            'country',
        ]
        widgets = {
            'bio': SummernoteWidget(),
            'country': CountrySelectWidget(),
        }

I am expecting after submitting the form to redirect to home page. The profile page uses websiteurl/id/profile as path to view profile. i thought that redirecting to the ShowProfilePageView after submitting the form using reverse_lazy but i cant seem to find anyway of it working and have hit a block.


Solution

  • The url pattern for show_profile_page needs an id as argument which you are not passing:

    path('<int:pk>/profile/', ShowProfilePageView.as_view(),
                 name="show_profile_page")
    

    pass it like this:

    def get_success_url(self):
        return reverse_lazy('show_profile_page', kwargs={'pk': self.object.pk})