blockhead
blockhead

Reputation: 431

how do i redirect to user profiles upon signup with django

I am trying to redirect users to their profiles once they sign up. i can't figure out how the url should be, should be written the same way it is in the urls.py or modified? i read some articles and they talked of using a reverse lazy argument, i am not sure that would work. my current profile url uses a slug field that contains the last name and surname.

views.py

   def addpatient(request):
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.profile.first_name = form.cleaned_data.get('first_name')
            user.profile.last_name = form.cleaned_data.get('last_name')
            user.is_active = True
    
            user.save()
            user.profile.id=pk
    
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            messages.success(request, 'Account was created for ' + username)
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('profile/<str:slug>/<int:pk>')
        else:
            form = SignUpForm()
        return render(request, 'core/signup.html', {'form': form})

models.py

class Profile(models.Model):
    username = models.CharField(max_length=50, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    last_name = models.CharField(max_length=100, blank=True)
    first_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    slug = models.SlugField(max_length=200,null=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(f"{self.last_name}-{self.first_name}")
        super(Profile, self).save(*args, **kwargs)

urls.py

urlpatterns = [
    path('profile/', profile, name='profile'),
    path('profile/<str:slug>/<int:pk>', profile, name='profilepk')

Upvotes: 1

Views: 415

Answers (1)

Lord Elrond
Lord Elrond

Reputation: 16032

Pass the actual values for slug and pk in your redirect, and it should work:

return redirect(f'/profile/{user.profile.slug}/{user.pk}')

Upvotes: 1

Related Questions