2015-01-17 3 views
2

Я использую Django Userena в первый раз. Так что вы не можете настроить внешний вид формы пароля для изменения, так как мы знаем, что userena использовал пароль изменения по умолчанию форма из django.contrib.auth.forms (если я не ошибаюсь) .Теперь это становится тяжело для меня, чтобы настроить внешний вид форму для смены пароля шаблон причины в change password шаблоне, каждое поле отображается как {{ form.as_p }} как тотКак настроить внешний вид формы смены пароля Django-Userena

<form action = "" method="post" role = "form"> 
<fieldset> 
    <legend>{% trans "Change Password" %}</legend> 
    {% csrf_token %} 
    {{ form.as_p }} 
</fieldset> 
<input type="submit" value="{% trans "Change password" %}" class="btn btn-success" /> 
</form> 

В упоминании, я уже смог отформатировать внешний вид других форм, предоставляемых userena.for Пример я изменил внешний вид Edit Profile form путем добавления css классов в forms.py как то

class EditProfileForm(forms.ModelForm): 
""" Base form used for fields that are always required """ 
first_name = forms.CharField(label=_(u'First name'), 
          max_length=30, 
          widget=forms.TextInput(attrs={'class' : 'form-control'}), 
          required=False) 
last_name = forms.CharField(label=_(u'Last name'), 
          max_length=30, 
          widget=forms.TextInput(attrs={'class' : 'form-control'}), 
          required=False) 
background = forms.CharField(label=(u'Background'), 
          max_length=500, 
          widget=forms.Textarea(attrs={'class' : 'form-control'}), 
          required=True) 

и работал, change password form было вынесено из django.contrib.auth.forms, поэтому я не знаю как добавлять классы CSS в каждом поле этого файла, поскольку он является основным файлом Django. Может быть, есть альтернативный способ сделать это, но я неопытный в django, а также django userena, я не знаю, как это сделать.

+1

Вы можете увидеть идентификатор или класс по проверке элемента или просмотра исходного кода страницы. А затем добавьте стиль в css. – Kakar

ответ

1

Вы на самом деле нужно переопределить вид userena в целом, так как она проходит свою собственную форму в представлении

urls.py:

# Change password 
url(r'^(?P<username>[\@\.\w-]+)/password/$', 
    accounts.views.my_own_password_change_view, 
    name='userena_password_change'), 

В вашем views.py:

@secure_required 
@permission_required_or_403('change_user', (get_user_model(), 'username', 'username')) 
def my_own_password_change_view(request, username, template_name='userena/password_form.html', 
        pass_form=YourPasswordChangeForm, success_url=None, extra_context=None): 
    """ Change password of user. 

    This view is almost a mirror of the view supplied in 
    :func:`contrib.auth.views.password_change`, with the minor change that in 
    this view we also use the username to change the password. This was needed 
    to keep our URLs logical (and REST) across the entire application. And 
    that in a later stadium administrators can also change the users password 
    through the web application itself. 

    :param username: 
     String supplying the username of the user who's password is about to be 
     changed. 

    :param template_name: 
     String of the name of the template that is used to display the password 
     change form. Defaults to ``userena/password_form.html``. 

    :param pass_form: 
     Form used to change password. Default is the form supplied by Django 
     itself named ``PasswordChangeForm``. 

    :param success_url: 
     Named URL that is passed onto a :func:`reverse` function with 
     ``username`` of the active user. Defaults to the 
     ``userena_password_complete`` URL. 

    :param extra_context: 
     Dictionary of extra variables that are passed on to the template. The 
     ``form`` key is always used by the form supplied by ``pass_form``. 

    **Context** 

    ``form`` 
     Form used to change the password. 

    """ 
    user = get_object_or_404(get_user_model(), 
          username__iexact=username) 

    form = pass_form(user=user) 

    if request.method == "POST": 
     form = pass_form(user=user, data=request.POST) 
     if form.is_valid(): 
      form.save() 

      # Send a signal that the password has changed 
      userena_signals.password_complete.send(sender=None, 
                user=user) 

      if success_url: redirect_to = success_url 
      else: redirect_to = reverse('userena_password_change_complete', 
             kwargs={'username': user.username}) 
      return redirect(redirect_to) 

    if not extra_context: extra_context = dict() 
    extra_context['form'] = form 
    extra_context['profile'] = get_user_profile(user=user) 
    return ExtraContextTemplateView.as_view(template_name=template_name, 
              extra_context=extra_context)(request) 

И наконец

class YourPasswordChangeForm(forms.ModelForm): 
""" Base form used for fields that are always required """ 
first_name = forms.CharField(label=_(u'First name'), 
          max_length=30, 
          widget=forms.TextInput(attrs={'class' : 'form-control'}), 
          required=False) 
last_name = forms.CharField(label=_(u'Last name'), 
          max_length=30, 
          widget=forms.TextInput(attrs={'class' : 'form-control'}), 
          required=False) 
background = forms.CharField(label=(u'Background'), 
          max_length=500, 
          widget=forms.Textarea(attrs={'class' : 'form-control'}), 
          required=True) 

сделать еще больше настроек на шаблоне HTML

\t <form action="" method="post" id="password_change_form"> 
 
\t \t {% csrf_token %} 
 
     {% for field in form %} 
 
      <div class="profile-input w33"> 
 
       <div class="profile-label" for="{{ field.name }}">{{ field.label }}</div> 
 
       {{ field }} 
 
       {{ field.errors }} 
 
      </div> 
 
     {% endfor %} 
 
     <div class="profile-input w33"> 
 
      <input type="submit" class="input updatebtn" value="{% trans "UPDATE" %}"/> 
 
     </div> 
 
\t </form>

0

Если вы собираетесь использовать Bootstrap и JQuery вы можете также настроить все шаблоны в вашей базе файла userena с JQuery.

В моем случае это спасло мне много грязного кода в нескольких файлах по всему проекту.

Просто измените нужные части с JQuery или чистый JS и CSS, например:

$("input").addClass("form-control"); 
Смежные вопросы