1

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:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\urls\base.py", line 71, in reverse
    extra, resolver = resolver.namespace_dict[ns]

During handling of the above exception ('user'), another exception occurred:
  File "C:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\views\generic\edit.py", line 168, in get
    return super().get(request, *args, **kwargs)
  File "C:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\views\generic\edit.py", line 133, in get
    return self.render_to_response(self.get_context_data())
  File "C:\Users\user\Desktop\django\sandbox\securities\website\users\views.py", line 139, in get_context_data
    context = super().get_context_data(**kwargs)
  File "C:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
    kwargs['form'] = self.get_form()
  File "C:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
    return form_class(**self.get_form_kwargs())
  File "C:\Users\user\Desktop\django\sandbox\securities\website\users\forms.py", line 71, in __init__
    self.fields['check'].label = 'Принимаю политику конфиденциальности' % reverse('user:privacy')
  File "C:\Users\user\Desktop\django\sandbox\securities\venv\lib\site-packages\django\urls\base.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?

2 Answers 2

2

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
6
  • Now I got the error: 'user' is not a registered namespace Sep 9, 2021 at 9:13
  • 1
    That seems to be a totally different problem. Can you share the full traceback? I guess it's caused by reverse('user:privacy'), where you can't use user Sep 9, 2021 at 12:19
  • I have added the full traceback to the question. Sep 9, 2021 at 13:54
  • Sorry, I had a typo. I wrote reverse('user:privacy') instead of reverse('users:privacy'). But after fixing it I still have an error. Now it's not all arguments converted during string formatting. Sep 9, 2021 at 14:43
  • Now I have changed this to the __init__: self.fields['check'].label = 'Принимаю <a href="{%s}"> политику конфиденциальности</a>' % reverse_lazy('users:privacy'). The privacy page has loaded, but instead of a link, I see this: Принимаю <a href="{/privacy}"> политику конфиденциальности</a> Sep 9, 2021 at 14:51
0

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'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.