2015-05-01 52 views
5

就像標題中所述,表單窗口小部件中的佔位符屬性無法正確顯示。它是隨機的,有時它可以正常工作,有時我需要刷新瀏覽器才能顯示。 我需要它們,因爲我沒有在模板中顯示字段標籤。 反正這裏是代碼:django中的表單佔位符顯示不正確

#FORMS.PY 
class RegistrationForm(UserCreationForm): 
    first_name = forms.CharField(label=_('First name'), max_length=30) 
    last_name = forms.CharField(label=_('Last name'), max_length=30) 
    email = forms.EmailField(label=_("Email"), required=True) 

    class Meta: 
     model = User 
     fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') 

    def __init__(self, *args, **kwargs): 
     super(RegistrationForm, self).__init__(*args, **kwargs) 
     # Set field Label as Placeholder for every field 
     for field in self.base_fields.values(): 
      field.widget.attrs["placeholder"] = field.label 
     # Set HTML and CSS attributes to the fields 
     self.fields['username'].widget.attrs.update({'class':TEXTINPUT_CSS}) 
     self.fields['email'].widget.attrs.update({'class':EMAILINPUT_CSS}) 
     self.fields['password1'].widget.attrs.update({'class':PASSWORDINPUT_CSS}) 
     ... 

通過我使用Django開發服務器的方式,可能來自一個事實,即服務器速度慢的問題。 任何幫助,將不勝感激

編輯:Views.py和模板的要求

#views.py 
def register(request): 
    if request.method == 'POST': 
     form = RegistrationForm(request.POST) 
     if form.is_valid(): 
      form.save() 
      if REGISTER_EMAIL_CONFIRMATION == True: 
       # Add email confirmation 
       username = form.cleaned_data['username'] 
       email = form.cleaned_data['email'] 
       salt = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]    
       activation_key = hashlib.sha1((salt+email).encode('utf-8')).hexdigest()    
       key_expires = datetime.datetime.today() + datetime.timedelta(CONFIRMATION_KEY_EXPIRE_DAYS) 
       # Create and save User Profile 
       user=User.objects.get(username=username)    
       new_profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires) 
      new_profile.save() 
       # Send email with activation key 
       subject_file = 'app_authentication/email_signup_confirm_subject.txt' 
       body_file = 'app_authentication/email_signup_confirm_body.html' 
       context = {'username':username, 'activation_key':activation_key} 
       send_email_from_files([email], subject_file, body_file, context) 
       return redirect('confirm_email_sent') 
      else: 
       return redirect('register_success') 
    else: 
     form = RegistrationForm() 
    return render(request, 'registration/register.html', {'form': form, 'title': _('Register')}) 


#register.html 
{% block content2 %} 
<form id="register_form" autocomplete="off" method="post" action="{% url 'register' %}"> 
{% csrf_token %} 
    <div class="clearfix"> 
    {% for field in form %} 
     <div class="form-group"> 
      {{ field }} 
      {% if form.errors %} 
      {% for error in field.errors %} 
       <div class="alert alert-error"> 
        <strong>{{ error|escape }}</strong> 
       </div> 
      {% endfor %} 
      {% endif %} 
     </div> 
    {% endfor %} 
     {% if form.errors %} 
     {% for error in form.non_field_errors %} 
      <div class="alert alert-error"> 
       <strong>{{ error|escape }}</strong> 
      </div> 
     {% endfor %} 
     {% endif %} 
    </div> 
    <!-- Send Button --> 
    <div class="pt-10"> 
     <button class="submit_btn btn btn-mod btn-medium btn-round btn-full" id="reg-btn" name="submit">{{ title }}</button> 
    </div> 
</form> 
{% endblock content2 %} 

截圖:

當我啓動開發服務器,並嘗試登錄: placeholders not working

我刷新瀏覽器後的相同登錄頁面: placeholders working after refresh

@akarilimano:

class LoginForm(AuthenticationForm): 
    # username doesn't have label in AuthenticationForm 
    username = forms.CharField(label=_("Username"), max_length=254) 

    def __init__(self, *args, **kwargs): 
     super(LoginForm, self).__init__(*args, **kwargs) 
     # Set field Label as Placeholder for every field 
     for field in self.base_fields.values(): 
      print(field.label) 
      field.widget.attrs['placeholder'] = field.label 
+0

你在佔位符得到什麼輸出?這看起來應該到目前爲止。 – Mikeec3

+0

我得到了預期的結果(標籤用作佔位符),但我只得到它的7倍,10出來。當它不起作用,我得到空白表單字段(沒有佔位符)。 我在登錄表單中也有相同的問題,使用相同的代碼。 –

+0

@ khalilan這些是登錄頁面的屏幕,註冊頁面是否有同樣的問題?你能否提供登錄的代碼(表單,視圖)? – akarilimano

回答

3

嘗試改變這裏base_fields

for field in self.base_fields.values(): 

fields

for field in self.fields.values(): 

base_fields字典是一組基本的類定義的字段。你可以改變它,但不建議,在你的情況下不需要。

我想如果你改變base_fields後打電話super您的版本將工作:

def __init__(self, *args, **kwargs): 
    for field in self.base_fields.values(): 
     field.widget.attrs["placeholder"] = field.label 
    super(RegistrationForm, self).__init__(*args, **kwargs) 
+1

完美的作品。非常感謝你 ! –

1

爲什麼你需要這個代碼,如果你已經在Meta定義model = User

first_name = forms.CharField(label=_('First name'), max_length=30) 
last_name = forms.CharField(label=_('Last name'), max_length=30) 
email = forms.EmailField(label=_("Email"), required=True) 

也許他們與模型字段發生衝突?你可以嘗試刪除非模型表單域?

+0

我以前使用過它們添加佔位符,忘了把它們註釋掉 'FIRST_NAME = forms.CharField(標籤= _( '名'),MAX_LENGTH = 30,小部件= forms.TextInput(ATTRS = { '佔位': '名字'}))' 我會將其刪除,並檢查馬上 –

+0

當我RUNSERVER和去該網站並嘗試登錄或註冊的佔位符不顯示的第一次,他們只顯示後,我刷新。 但是一旦他們在那裏,他們總是表現出來,所以這是一個改進。 –

+0

@KhalilAn可以嘗試用'field.widget.attrs.update({ '佔位符':field.label})替換'field.widget.attrs [ 「佔位符」] = field.label''?或者嘗試將'for'循環移動到'__init()__'的末尾。 – akarilimano

3

嘗試定義你的佔位符直接作爲控件屬性,如:

class RegistrationForm(UserCreationForm): 
     first_name = forms.CharField(label=_('First name'), max_length=30, widget=forms.TextInput(attrs={"placeholder": "First name"})) 
     last_name = forms.CharField(label=_('Last name'),max_length=30, widget=forms.TextInput(attrs={"placeholder": "Last Name"})) 
     email = forms.EmailField(label=_("Email"), required=True, widget=forms.TextInput(attrs={"placeholder": "Email"})) 
+0

我確定你的建議正在工作,但我正在尋找更乾的答案。 (+1) –

+0

@KhalilAn我想我們只是使用HTML佔位符屬性。 – ofnowhere