2

在過去的幾天裏,我一直試圖解決一個奇怪的問題,在我創建的用於處理用戶註冊的窗體上使用默認的help_text。我首先注意到這個問題,當我看到html django正在插入,因爲默認help_text正在逃脫。編輯Django窗體的默認字段'help_text(1.11)

Screenshot of Issue

不是顯示<ul>,我提醒你的是,Django包含密碼字段的默認help_text,它顯示純文本。

所以這是我第一次注意到,必須做錯的地方。如果默認表單help_text正在越獄並且看起來很糟糕,那我顯然是犯了一個錯誤。接下來,我將解釋我所做的嘗試解決此問題的方法,然後將對model,form,viewtemplate進行概述,以便您們有所收穫。

我在網上找到的第一個解決方案是使用Meta類,所以我在forms.py下,我修改class SignUpForm:一樣。

from django import forms 
from django.contrib.auth.forms import UserCreationForm 
from django.contrib.auth.models import User  

class SignUpForm(UserCreationForm): 
     company = forms.CharField() 
     city = forms.CharField() 
     state = forms.CharField() 
     zip = forms.IntegerField() 
     address = forms.CharField() 
     phone = forms.IntegerField() 

     class Meta: 
      model = User 
      # help_text = mark_safe 
      fields = ('company', 'city', 'state', 'zip', 'address', 'phone', 'username', 'email', 'password1', 'password2') 
      labels = { 
       'state': 'US States', 
       'password1': 'passcode1', 
       'password2': 'passcode2', 
       'username': 'human person', 
       'email': 'telegraph', 
       'city': 'locality', 
       'phone': "tele", 
      } 
      help_texts = { 
       'password1': 'Something that doesnt look awful', 
       'password2': 'Something else', 
       'username': 'Please enter an appropriate human name.', 
       'email': 'Which office?', 
       'city': 'What county?', 
       'phone': 'Please Include Country Code', 
      } 

這是我開始意識到問題比我想象的要大的地方。不僅是造成help_text轉義的原因,其中一些字段接受我的更改,而另一些字段不接受我的更改。我已經擴展默認UserCreationForm與(在這個例子中cityphone自定義字段不顯示自己的新labelhelp_text,而默認域usernameemail都顯示其空洞新labelhelp_text。而且,最重要全部關閉在password1password2領域保持不變。

Screenshot of class Meta result

好了,所以沒有工作。關於硬編碼到正確的形式?那麼事實是什麼的是主要工作,但它引入了複雜性的另一個層面在這個例子中對我來說,以及感覺像不好的做法。我會解釋。

由於我的形式延長了默認的Django UserCreationForm我真的不安裝在我的SignUpForm領域,它們被自動添加,我用自己的class Meta:字段,以便以硬編碼解決這個問題,我有我的方式添加它們。

from django import forms 
from django.contrib.auth.forms import UserCreationForm 
from django.contrib.auth.models import User 
from django.utils.safestring import mark_safe 

class SignUpForm(UserCreationForm): 
    username = forms.CharField(help_text=mark_safe("Please enter an appropriate human name."), label='human name') 
    email = forms.CharField(widget=forms.EmailInput, help_text=mark_safe('Which office?'), label='telegraph') 
    password1 = forms.CharField(widget=forms.PasswordInput, help_text=mark_safe('Something that doesnt look awful'), 
           label='Passcode') 
    password2 = forms.CharField(widget=forms.PasswordInput, help_text=mark_safe('Something else'), label='Passcode 2') 
    company = forms.CharField(help_text=mark_safe("Please enter a company name")) 
    city = forms.CharField(help_text=mark_safe('What county?'), label='locality') 
    state = forms.CharField(help_text=mark_safe('Please enter the state')) 
    zip = forms.IntegerField(help_text=mark_safe('Please enter a zip code.')) 
    address = forms.CharField(help_text=mark_safe('Please enter an address.')) 
    phone = forms.IntegerField(help_text=mark_safe('Please include country code.'), label='tele') 

    class Meta: 
     model = User 
     fields = ('company', 'city', 'state', 'zip', 'address', 'phone', 'username', 'email', 'password1', 'password2') 

所以這一個工程,但它確實是不切實際的,並且關於我還沒有解決根本問題。硬編碼結果的

截圖(不能發表,因爲我沒有足夠的代表,但是請相信我一切正常)

所以這給我們帶來了現在,我已經嘗試了一些其他的東西,但沒有任何東西讓我儘可能接近我想要的硬編碼,所以我需要弄清楚我所犯的潛在錯誤。

所以這是我與合作:

模型。PY

from django.db import models 
from django.contrib.auth.models import User 
from django.db.models.signals import post_save 
from django.dispatch import receiver 

class Profile(models.Model): 
    username = models.OneToOneField(User, on_delete=models.CASCADE) 
    company = models.TextField(max_length=500, blank=True) 
    city = models.CharField(max_length=100, blank=True) 
    state = models.CharField(max_length=100, blank=True) 
    zip = models.CharField(max_length=5, blank=True) 
    address = models.CharField(max_length=200, blank=True) 
    phone = models.CharField(max_length=12, blank=True) 

@receiver(post_save, sender=User) 
def update_user_profile(sender, instance, created, **kwargs): 
    if created: 
     Profile.objects.create(user=instance) 
    instance.profile.save() 

forms.py(當前硬編碼版本):

from django import forms 
from django.contrib.auth.forms import UserCreationForm 
from django.contrib.auth.models import User 
from django.utils.safestring import mark_safe 

class SignUpForm(UserCreationForm): 
    username = forms.CharField(help_text=mark_safe("Please enter an appropriate human name."), label='human name') 
    email = forms.CharField(widget=forms.EmailInput, help_text=mark_safe('Which office?'), label='telegraph') 
    password1 = forms.CharField(widget=forms.PasswordInput, help_text=mark_safe('Something that doesnt look awful'), 
           label='Passcode') 
    password2 = forms.CharField(widget=forms.PasswordInput, help_text=mark_safe('Something else'), label='Passcode 2') 
    company = forms.CharField(help_text=mark_safe("Please enter a company name")) 
    city = forms.CharField(help_text=mark_safe('What county?'), label='locality') 
    state = forms.CharField(help_text=mark_safe('Please enter the state')) 
    zip = forms.IntegerField(help_text=mark_safe('Please enter a zip code.')) 
    address = forms.CharField(help_text=mark_safe('Please enter an address.')) 
    phone = forms.IntegerField(help_text=mark_safe('Please include country code.'), label='tele') 

    class Meta: 
     model = User 
     fields = ('company', 'city', 'state', 'zip', 'address', 'phone', 'username', 'email', 'password1', 'password2') 

views.py

from django.shortcuts import render, redirect 
from django.contrib.auth import login, authenticate 
from apps.dashboard.forms import SignUpForm 

def signup(request): 
    if request.method == 'POST': 
     form = SignUpForm(request.POST) 
     if form.is_valid(): 
      user = form.save() 
      user.refresh_from_db() # load the profile instance created by the signal 
      user.profile.company = form.cleaned_data.get('company') 
      user.profile.city = form.cleaned_data.get('city') 
      user.profile.state = form.cleaned_data.get('state') 
      user.profile.zip = form.cleaned_data.get('zip') 
      user.profile.address = form.cleaned_data.get('address') 
      user.profile.phone = form.cleaned_data.get('phone') 
      user.save() 
      raw_password = form.cleaned_data.get('password1') 
      user = authenticate(username=user.username, password=raw_password) 
      login(request, user) 
      return redirect(main) 
    else: 
     form = SignUpForm() 
    return render(request, 'signup.html', {'form': form}) 

模板(HTML):

<h2>Sign up</h2> 
        <form method="post"> 
         {% csrf_token %} 
         {% for field in form %} 
          <p> 
           {{ field.label_tag }}<br> 
           {{ field }} 
           {% if field.help_text %} 
            <small style="color: grey">{{ field.help_text }}</small> 
           {% endif %} 
           {% for error in field.errors %} 
            <p style="color: red">{{ error }}</p> 
           {% endfor %} 
          </p> 
         {% endfor %} 
         <button type="submit">Sign up</button> 
        </form> 
+0

羅布辛普森的答案看起來像對我來說是正確的。無論如何,它是爲我解決它的人。 – nilo

回答

2

要回答的有機磷農藥對help_text最初的擔憂被轉義:

的「安全」的過濾器可以使用,例如......

{% if field.help_text %} 
     <small style="color: grey">{{ field.help_text|safe }}</small> 
    {% endif %} 

給您正在尋找名單被回報的模板。

您可能想看到標題爲Django template escaping的SO帖子,以獲取此行爲的更多示例以及如何控制它。

+0

看起來像是對我的正確答案。非常感謝,這也幫助了我。 – nilo

+0

謝謝!如果你這麼認爲,那麼你可以評論OP嗎?我的代表太低... –

+0

我已經做到了! – nilo

0

看起來像help_texts只適用於型號字段,如usernameemail。對於其他字段,您可以在__init__方法中設置help_text

class SignUpForm(UserCreationForm): 
    class Meta: 
     model = User 
     ... 
     help_texts = { 
      'username': 'Please enter an appropriate human name.', 
      'email': 'Which office?', 
     } 

    def __init__(self, *args, **kwargs): 
     super(SignUpForm, self).__init__(*args, **kwargs) 
     self.fields['password1'].help_text = 'Something that doesnt look awful' 
     self.fields['password2'].help_text = 'Something else' 

,而不是添加配置文件字段的SignUpForm的,我將創造麴線

​​

一個單獨的模型形式然後在您的視圖和模板兩種形式。

+0

看到我最近的編輯(在底部),試圖在這裏迴應,但字符限制是一個痛苦。 – Jon

+0

有幾個錯別字。查看更新後的答案。 – Alasdair

+0

爲什麼你不包括字段?這是更大的一部分嗎?我得到這個錯誤'django.core.exceptions.ImproperlyConfigured:創建沒有'fields'屬性或'exclude'屬性的ModelForm是禁止的;表格SignUpForm需要更新.' – Jon

相關問題