在过去的几天里,我一直在尝试使用我创建的用于处理用户注册的表单上的默认help_text解决一个奇怪的问题。当我看到html django正在插入而默认help_text被转义时,我首先注意到了这个问题。

Screenshot of Issue

我没有显示<ul>(我提醒您这是django用于密码字段的默认help_text),而是显示纯文本。

因此,这是我首先注意到必须做错事情的地方。如果默认格式的help_text被转义并看起来像那样可怕,那么我显然是在犯错误。接下来,我将解释我为解决此问题所做的工作,然后概述了modelformviewtemplate,以便您有所作为。

我在网上找到的第一个解决方案是使用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_textpassword1password2字段保持不变。

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

因此,这是可行的,但由于我尚未解决根本问题,所以这确实不切实际且令人担忧。

硬编码结果的屏幕快照(无法发布,因为我没有足够的代表,但是请相信我一切正常)

到现在为止,我已经尝试了其他一些东西,但是没有什么比我想要的像硬编码更接近我了,所以我需要弄清楚我犯的潜在错误。

所以这是我正在使用的东西:

models.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>

最佳答案

要回答OP最初对转义help_text的担心,请执行以下操作:

可以使用“安全”过滤器,例如...

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

给出您要在呈现的模板中查找的列表。

您可能需要查看标题为Django template escaping的SO帖子,以获取有关此行为以及如何控制它的更多示例。

关于django - 在Django(1.11)中为表单编辑默认字段的help_text,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45088397/

10-12 17:43
查看更多