When trying to add a link to the label of a form field an __init __ () got an unexpected keyword argument 'initial' error occurs

Question:

When I try to add a link to the label of a django UserCreationForm field, I get the error:

 __init__() got an unexpected keyword argument 'initial'.

My code looks like this:

#forms.py
class RegisterUserForm(UserCreationForm):
    email = forms.EmailField(required=True, label='Адрес электронной почты')
    check = forms.BooleanField()

    def __init__(self):
        super(RegisterUserForm, self).__init__()
        self.fields['check'].label = 'Принимаю политику конфиденциальности' % reverse('user:privacy')

    class Meta:
        model = AdvUser
        fields = ('username', 'email', 'password1', 'password2', 'check')

views.py look like this:

#views.py 
class RegisterUserView(SuccessMessageMixin, CreateView):
    model = AdvUser
    template_name = 'users/register_user.html'
    form_class = RegisterUserForm
    success_url = reverse_lazy('articles:list_view')
    success_message = 'Вы успешно зарегистрировались!'

    def form_valid(self, form):
        valid = super(RegisterUserView, self).form_valid(form)
        username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1')
        new_user = authenticate(username=username, password=password)
        login(self.request, new_user)
        return valid

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # 5 тегов с наибольшим количеством публикаций
        context['tags_list'] = Tag.objects.annotate(articles_quantiy=Count('taggit_taggeditem_items')).order_by(
            '-articles_quantiy')[:10]
        context['securities_types_list'] = StocksETFsBonds.objects.all()
        return context

After adding *args and **kwargs to def __init__ I got the traceback which looks like this:

Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/register/

Traceback (most recent call last):
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangourlsbase.py", line 71, in reverse
    extra, resolver = resolver.namespace_dict[ns]

During handling of the above exception ('user'), another exception occurred:
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangocorehandlersexception.py", line 47, in inner
    response = get_response(request)
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangoviewsgenericbase.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangoviewsgenericbase.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangoviewsgenericedit.py", line 168, in get
    return super().get(request, *args, **kwargs)
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangoviewsgenericedit.py", line 133, in get
    return self.render_to_response(self.get_context_data())
  File "C:UsersuserDesktopdjangosandboxsecuritieswebsiteusersviews.py", line 139, in get_context_data
    context = super().get_context_data(**kwargs)
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangoviewsgenericedit.py", line 66, in get_context_data
    kwargs['form'] = self.get_form()
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangoviewsgenericedit.py", line 33, in get_form
    return form_class(**self.get_form_kwargs())
  File "C:UsersuserDesktopdjangosandboxsecuritieswebsiteusersforms.py", line 71, in __init__
    self.fields['check'].label = 'Принимаю политику конфиденциальности' % reverse('user:privacy')
  File "C:UsersuserDesktopdjangosandboxsecuritiesvenvlibsite-packagesdjangourlsbase.py", line 82, in reverse
    raise NoReverseMatch("%s is not a registered namespace" % key)

Exception Type: NoReverseMatch at /accounts/register/
Exception Value: 'user' is not a registered namespace

  • How can I solve this problem?
  • Are there other ways to add a link to the label or help_text of
    a django form field?
Asked By: ilsurealism

||

Answers:

This error is because __init__ now does not accept any args or kwargs:

    def __init__(self): # Not expecting anything

The args and kwargs need to be retained so just change it to:

class RegisterUserForm(UserCreationForm):
    ...
    def __init__(self, *args, **kwargs): # Add back args and kwargs
        super(RegisterUserForm, self).__init__(*args, **kwargs) # And pass to parent
Answered By: Brian Destura

When I changed the def __init__ to the code below, the correct link appeared in my registration page:

def __init__(self, *args, **kwargs):
    super(RegisterUserForm, self).__init__(*args, **kwargs)
    self.fields['check'].label = mark_safe('Принимаю <a href=%s> политику конфиденциальности</a>' % reverse_lazy('users:privacy'))
Answered By: ilsurealism