【问题标题】:django how to do something if value of form submitted is a certain word如果提交的表单的值是某个单词,django 如何做某事
【发布时间】:2013-10-04 21:45:32
【问题描述】:

好的,所以我有 django 模型并创建了该模型的一种形式。这是我的模板:

<form method="post" action="">{% csrf_token %}
    {{ form.first_name }} {{form.last_name }} <br>
    {{ form.username }} {{ form.password }} <br>
    {{ form.date_of_birth_month }} {{ form.date_of_birth_day }} {{ form.date_of_birth_year }}
    <input type="submit" value="Register"/>
</form>


{% for field, error in form.errors.items %}
    {% if forloop.counter == 1 %}
        {{ error | striptags }}
    {% endif %}
{% endfor %}

现在,这是我的那种形式的模型。

class Users(models.Model): 
    months = (
        ('Month','Month'), ('January', 'January'), ('February','February'), ('March','March'), ('April','April'), ('May','May'), ('June','June'), ('July','July'), ('August','August'), ('September','September'), ('October','October'), ('November','November'), ('December','December'),
)
    days = (
        ('Day', 'Day'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'),)
    years = (
        ('Year','Year'), ('2013','2013'), ('2012','2012'), ('2011','2011'), ('2010','2010'), ('2009','2009'), ('2008','2008'),)

    user_id = models.AutoField(unique=True, primary_key=True)
    username = models.SlugField(max_length=50, unique=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    password = models.SlugField(max_length=50)

    date_of_birth_month = models.CharField(verbose_name='', max_length=9, choices=months, default='Month')
    date_of_birth_day = models.CharField(verbose_name='', max_length=3, choices=days, default='Day')
    date_of_birth_year = models.CharField(verbose_name='', max_length=4, choices=years, default='Year')

现在,月份选择框的默认值为“月份”,用户名单击下拉菜单并选择他出生的月份。日和年也是如此。然而,这使得月、日和年成为用户可以选择的选项。我怎样才能做到这一点,如果用户选择“月”作为月份,“日”作为日或“年”作为年,然后引发错误消息说“请选择有效的月/日/年”?

我的观点在这里:

def home_page(request):
    form = UsersForm()
    if request.method == "POST":
        form = UsersForm(request.POST)

        if form.is_valid():
            form.save()
    c = {}
    c.update(csrf(request))
    c.update({'form':form})
    return render_to_response('home_page.html', c)

【问题讨论】:

    标签: django django-models django-forms django-views django-errors


    【解决方案1】:

    为表单中的字段编写 clean 方法:

    class UsersForm(form.Form):
        # form fields here
    
        def clean_month(self):
            month = self.cleaned_data.get('month')
            if month:
                try:
                    month = int(month)
                except:
                    raise forms.ValidationError('Invalid month')
                if month < 1 or month > 12:
                    raise forms.ValidationError('Invalid month')
    
            return month
    

    对您要验证的其余字段执行此操作。更多帮助在Documentation

    【讨论】:

    • 是的,我假设月份必须是整数,那么您可以跳过该检查。顺便说一句,您为什么不只提供一个日期字段并存储在数据库中。并且在前端使用 datepicker 可以轻松为您节省大量工作。
    • 啊,完美。另外,您说“如果月份:尝试:月份= int(月份)”..月份的值不会总是一个字符串,因为我只给他们1-12月的选项吗?我在想的是, def clean_date_of_brith_month(self): data = self.cleaned_data.get('date_of_birth_month') if month == 'Month': raise forms.ValidationError('Invalid month').. 但它没有用..任何想法为什么?
    • 在做任何事情之前尝试打印 self.cleaned_data.get('date_of_birth_month') 的值并检查值是否真的是 Month 或其他东西即将出现而 if month == 'Month': 条件失败
    • 嗯,因为我希望月份字段是它自己的某些选项的按钮,日期字段是它自己的具有某些选项的按钮,而年份字段是它自己的某些选项的按钮。有没有办法做到这一点并将其存储为数据库中的单个日期字段?另外,有没有关于如何使用 datepicker 的好文档?
    • 表格有DateField。您需要在这里查看更多内容。
    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 2021-04-16
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多