【问题标题】:Django form sporadic validationDjango 表单零星验证
【发布时间】:2013-09-30 00:28:07
【问题描述】:

我有一个从基于类的通用 UpdateView 访问的表单。除其他事项外,它还验证正在更新的事件与另一个事件不在同一日期。

问题在于,在更新某些字段时,例如位置,处理更改时不会引发错误,但会更新其他错误,例如名称,引发有关事件日期与另一个事件冲突的验证错误,在编辑位置时也会发生错误。

为什么编辑某些字段会引发验证错误而不编辑其他字段?确实,验证应该检查所有内容。

我的看法:

class EventEditView(UpdateView):
    template_name = "edit_event.html"
    pk_url_kwarg='event_id'
    model = Event
    form_class = EventEditForm

使用这种形式:

class EventEditForm(forms.ModelForm):

    class Meta:
        model = Event

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(EventEditForm, self).__init__(*args, **kwargs)


    name = forms.CharField(max_length=1024,
        initial="Give short, descriptive name")
    location = forms.CharField(max_length=1024,
        initial="Be specific, give online map link")
    dateTimeOptions = {
        'format': 'dd/mm/yyyy HH:ii P',
        'autoclose': 'true',
        'showMeridian': 'true',
        }
    date = forms.DateTimeField(label="Date and time",
        widget=DateTimeWidget(options=dateTimeOptions,
        attrs={'id':"date-time"}))
    host_act = forms.CharField(max_length=1024,
        initial="What act will you bring, if any?", required=False)
    description = forms.CharField(required=False, max_length=10240)

    def clean_location(self):
        cd = self.cleaned_data
        location = cd.get('location')
        if location == "Be specific, give online map link" or '':
            raise forms.ValidationError("Please enter a location")
        return location

    def clean_name(self):
        cd = self.cleaned_data
        name = cd.get('name')
        other_names = Event.objects.proposed(datetime.now)
        if name == "Give short, descriptive name" or '':
            raise forms.ValidationError("Please enter a name")
        return name

    def clean(self):
        """
        Check that there is not another event on at
        the same time and place. Then check that user has not committed
        to another event on the same date, even somewhere else.
        """
        cleaned_data = super(EventEditForm, self).clean()
        event_start_estimate = cleaned_data.get("date") - timedelta(hours=3)
        event_end_estimate = event_start_estimate + timedelta(hours=7)
        location = cleaned_data.get("location")
        events_on_date = Event.objects.\
            filter(date__range=[event_start_estimate,event_end_estimate])
        events_at_location_on_date = events_on_date.filter(location=location)
        # Check event clash is not this event clashing with itself
        #        events_with_same_date_and_location_id = events_at_location_on_date.values()[0]['id']
        #        this_event_id = self.instance.id
        try:
            if events_with_same_date_and_location_id == this_event_id:
                events_at_location_on_date = False
        except:
            pass
        if events_at_location_on_date:
            raise forms.ValidationError("There is already an event on \
                this date.")
        user = self.request
        print user
        events_on_date_user_has_commit = events_on_date.filter(host__exact=user)
        if events_on_date_user_has_commit:
            raise forms.ValidationError("You are already committed to an event\
                on this date.")
        return cleaned_data    

【问题讨论】:

    标签: python django forms validation


    【解决方案1】:

    您的代码中有一些错误可能与您的问题有关,也可能无关。

    clean_location 中的 if 语句将始终为 false,因为 '' 为 false。我想你想要的是这样的:

    if name in ["Give short, descriptive name", '']:
    

    其次,clean_name 中的相同内容。应该是:

    if name in ["Give short, descriptive name", '']:
    

    第三,在clean 中,您使用self.request 作为用户对象:

    user = self.request
    

    应该是:

    user = self.request.user
    

    也许这些更改会解决您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-10
      • 2011-01-19
      • 2021-06-05
      • 2014-12-06
      • 2017-08-24
      • 2019-02-02
      • 2020-06-10
      • 2011-01-20
      相关资源
      最近更新 更多