username on URL with Class Based Views

162 views
Skip to first unread message

Ricardo Cataldi

unread,
Sep 12, 2018, 4:06:15 PM9/12/18
to Django users

nice to be here again :D


This question is on stackoverflow, in here: https://stackoverflow.com/questions/52302052/django-url-custom-parameters-on-base-class-view. I have writen a class based views based on generic.base.view to get information about users profiles, that are comming from different models and db tables, that will be applied both in viewing some user information on a social network and by the own user on edditing his own profile. Here is the view:


class ProfileView(PageTitleMixin, generic.View):
template = "common/profile.html"
template_name = "Perfil"
page_title = _('Profile')
active_tab = 'profile'
success_url = reverse_lazy('usrxtnsion:profile')

def get_queryset(self):
    return User.objects.filter(username=self.kwargs['username'])

def get_context_data(self, **kwargs):
    ctx = super().get_context_data(**kwargs)
    account_info = Profile.objects.get(pk=self.request.user.profile.pk)
    user_info = User.objects.get(pk=self.request.user.pk)
    ctx['user_fields'] = self.get_profile_fields(self.request.user)
    ctx['profile_fields'] = user_info.profile_set.all()
    ctx['address_fields'] = user_info.useraddress_set.all()
    ctx['account_fields'] = account_info.account_set.all()
    ctx['username'] = self.request.user.username
    return ctx

def get_profile_fields(self, user):
    field_data = []

    # Check for custom user model
    for field_name in User._meta.additional_fields:
        field_data.append(
            self.get_model_field_data(user, field_name))

    # Check for profile class
    profile_class = get_profile_class()
    if profile_class:
        try:
            profile = profile_class.objects.get(user=user)
        except ObjectDoesNotExist:
            profile = profile_class(user=user)

        field_names = [f.name for f in profile._meta.local_fields]
        for field_name in field_names:
            if field_name in ('user', 'id'):
                continue
            field_data.append(
                self.get_model_field_data(profile, field_name))

    return field_data

def get_model_field_data(self, model_class, field_name):
    """
    Extract the verbose name and value for a model's field value
    """
    field = model_class._meta.get_field(field_name)
    if field.choices:
        value = getattr(model_class, 'get_%s_display' % field_name)()
    else:
        value = getattr(model_class, field_name)
    return {
        'name': getattr(field, 'verbose_name'),
        'value': value,
    }

def get(self, request, *args, **kwargs):
    user_form = SignupForm(instance=self.request.user)
    profile_form = ProfileForm(instance=self.request.user.profile)
    account_form = AccountForm(instance=self.request.user)
    address_form = UserAddressForm(instance=self.request.user)
    username = request.user.username

    return render(request, 'common/profile.html', {
        'user_form': user_form,
        'profile_form': profile_form,
        'account_form': account_form,
        'address_form': address_form,
        'username': username
    })

def post(self, request, *args, **kwargs):
    user_form = SignupForm(instance=self.request.user)
    profile_form = ProfileForm(instance=self.request.user.profile)
    account_form = AccountForm(instance=self.request.user)
    address_form = UserAddressForm(instance=self.request.user)

    if user_form.is_valid() and profile_form.is_valid() and account_form.is_valid() and address_form.is_valid():
        user_form.save()
        profile_form.save()
        account_form.save()
        address_form.save()
        messages.success(request, _('Seu perfil foi atualizado!'))
        return redirect('settings:profile')
    else:
        messages.error(request, _('Por favor, corriga os erros abaixo.'))

def form_valid(self, form):
    try:
        old_user = User.objects.get(id=self.request.user.id)
    except User.DoesNotExist:
        old_user = None

    form.save()

    new_email = form.cleaned_data.get('email')
    if new_email and old_user and new_email != old_user.email:
        ctx = {
            'user': self.request.user,
            'site': get_current_site(self.request),
            'reset_url': get_password_reset_url(old_user),
            'new_email': new_email,
        }
        msgs = CommunicationEventType.objects.get_and_render(
            code=self.communication_type_code, context=ctx)
        Dispatcher().dispatch_user_messages(old_user, msgs)

    messages.success(self.request, _("Profile updated"))
    return redirect(self.get_success_url())


The problem is that i'm trying to insert the user name on the url and i'm not getting into it. The URL is the following:


path('profile/<username>/', login_required(views.ProfileView.as_view()), name="profile"),


But i am having some problem to pass the argument to the URL. I've already tried to insert the get_queryset to get all the details of username, but Django still gives me the error msg


Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile/(?P<username>[^/]+)/$']


I have read the docs in here, here and here, with no success in finding a solution. I've also searched around in stackoverflow for some solution and i didn't find anything. Any hints on how to make this work?

Gear Crew

unread,
Sep 12, 2018, 4:16:30 PM9/12/18
to django...@googlegroups.com
Do you know what's the specific problem in my code?

Jason

unread,
Sep 13, 2018, 7:45:24 AM9/13/18
to Django users
return redirect('settings:profile')

The issue is this.  you're telling Django to hit up that URL, but you don't specify the username for that.

Something like this would be required:  return redirect('settings:profile', args=(username,))

Ricardo Cataldi

unread,
Sep 13, 2018, 9:27:51 AM9/13/18
to django...@googlegroups.com
Nice! Thanks a lot!

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/805978e9-ff92-4acb-b536-f1d1efa29f30%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tosin Ayoola

unread,
Sep 14, 2018, 4:36:42 AM9/14/18
to django...@googlegroups.com
good morning guyz
i'm trying to use django-form-wizard in my project, but when i include it in the install apps in my settings, attached below is the error message i'm getting.
anyone with suggestion on how i can fix this ?
thanks










thanks
Screenshot from 2018-09-14 09-32-48.png
Reply all
Reply to author
Forward
0 new messages