简体   繁体   English

Django UpdateView 不填充表单

[英]Django UpdateView not populating form

I've been stuck on this problem for hours, looking through Django documentation and adjusting my code hasn't helped.我已经被这个问题困扰了几个小时,查看 Django 文档并调整我的代码并没有帮助。

I have manually coded a HTML form (for styling reasons).我已经手动编码了一个 HTML 表单(出于样式原因)。 Everything works fine until I try to edit an object via this form.一切正常,直到我尝试通过此表单编辑对象。

I'm using a standard UpdateView with no additions but for some reason the form is not populating the data in the object.我正在使用没有添加的标准 UpdateView,但由于某种原因,表单没有填充对象中的数据。

class RPLogbookEditEntry(LoginRequiredMixin, UpdateView):
    login_url = 'ihq-login'
    template_name = 'internethq/ihq-rplogbookform.html'
    model = RPLogbookEntry
    fields = ['entry_date', 'rpa_code', 'rpa_icao_code','rpa_registration', 'user_role', 'crew', 'crew_role', 'launch_location', 'recovery_location',
    'remarks', 'vlos', 'evlos1', 'evlos2', 'bvlos', 'ft_day', 'ft_night', 'remarks', 'no_of_landings_day', 'no_of_landings_night']

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.rpa = RPA.objects.get(rpa_code=form.cleaned_data['rpa_code'])
        return super().form_valid(form)

    def form_invalid(self, form):
        return super().form_invalid(form)
    
    def get_success_url(self):
        return reverse('ihq-rplogbook-list') + '?month=' + str(self.object.entry_date.month) + '&year=' + str(self.object.entry_date.year)

models.py模型.py

class RPLogbookEntry(models.Model):
    ## Date
    entry_date  = models.DateField()

    ## RPA Details
    rpa_obj = RPA.objects.only('rpa_code')
    RPA_CODE_CHOICES = []
    for vars in rpa_obj:
        RPA_CODE_CHOICES.append((vars.rpa_code, vars.rpa_code)) 
    rpa_code         = models.CharField(choices=RPA_CODE_CHOICES, max_length=20)

    rpa_icao_code    = models.CharField(max_length=15)
    rpa_registration = models.CharField(max_length=30)
    rpa           = models.ForeignKey(RPA, on_delete=models.CASCADE)
    ## Crew Details
    user        = models.ForeignKey(User, on_delete=models.CASCADE)
    USER_ROLE_CHOICES = [
        ('RPIC', 'Remote Pilot-In-Command'),
        ('RP', 'Remote Pilot'),
        ('SPOT', 'Spotter'),
        ('CAMOP', 'Camera operator'),
    ]
    user_role   = models.CharField(
        max_length=5,
        choices=USER_ROLE_CHOICES,
    )
    crew        = models.CharField(max_length=128, blank=True)
    crew_role   = models.CharField(
        max_length=5,
        choices=USER_ROLE_CHOICES,
        blank = True
    )

    ## Flight Details
    launch_location     = models.CharField(max_length=128)
    recovery_location   = models.CharField(max_length=128)
    remarks             = models.CharField(max_length=256, blank=True)
    vlos                = models.BooleanField(default=True)
    evlos1              = models.BooleanField(default=False)
    evlos2              = models.BooleanField(default=False)
    bvlos               = models.BooleanField(default=False)

    ## Flight Time
    ft_day              = FlightTimeFieldInt("Day flight time", blank=True, null=True,)
    ft_night            = FlightTimeFieldInt("Night flight time", blank=True, null=True,)

    def _ft_total(self):
        return int(self.ft_day + self.ft_night)

    ft_total            = property(_ft_total)

    ## Category of mission or flight

    MISSION_CATEGORY_CHOICES = [

        ('INS', 'Inspection'),
        ('MAP', 'Mapping'),
        ('PHO', 'Photography'),
        ('VID', 'Videography'),
        ('PRI', 'Private flying'),
        ('TRA', 'Training'),
    ]

    mission_category = models.CharField(
        max_length=3,
        choices=MISSION_CATEGORY_CHOICES,
        blank=True,
    )

    ## Landings & Autolands

    no_of_landings_day = models.IntegerField("Number of landings", blank=True, default=0,)
    no_of_landings_night = models.IntegerField("Number of auto landings", blank=True, default=0,)


    def get_absolute_url(self):
        return reverse('ihq-rplogbook-list')

    def clean(self):
        if self.no_of_landings_day is None and self.no_of_landings_night is None:
            raise ValidationError({'no_of_landings_day':_('You must have landed at least once!')})
        if self.no_of_landings_night is None:
            if self.no_of_landings_day >= 1:
                self.no_of_landings_night = 0
                return self.no_of_landings_night
        if self.no_of_landings_day is None:
            if self.no_of_landings_night >= 1:
                self.no_of_landings_day = 0
                return self.no_of_landings_day
 
    def clean_fields(self, exclude=None):
        validation_error_dict = {}
        p = re.compile('^[0-9]+:([0-5][0-9])')
        if self.ft_day !='' and p.match(self.ft_day) is None:
            validation_error_dict['ft_day'] = ValidationError(_('Flight duration must be in HH:MM format.'))
        if self.ft_night !='' and p.match(self.ft_night) is None:
            validation_error_dict['ft_night'] = ValidationError(_('regex night wrong'))
        if self.ft_day =='' and self.ft_night =='':
            validation_error_dict['ft_day'] = ValidationError(_('Fill in at least one flying time duration.'))

        if (self.vlos or self.evlos1 or self.evlos2 or self.bvlos) is False:
            validation_error_dict['vlos'] = ValidationError(_('Select one LOS category.'))
        
        if (self.vlos or self.evlos1 or self.evlos2 or self.bvlos) is True:
            counter = 0
            for x in [self.vlos, self.evlos1, self.evlos2, self.bvlos]:
                if x == True:
                    counter += 1
            if counter > 1:
                validation_error_dict['vlos'] = ValidationError(_('Selecting more than one LOS category is not allowed.'))
        # if self.no_of_landings is None and self.no_of_auto_landings is None:
        #      validation_error_dict['no_of_landings'] = ValidationError(_('You must have landed at least once!'))

        if validation_error_dict:
            raise ValidationError(validation_error_dict)

Basically my question is - shouldn't this UpdateView populate my form automatically?基本上我的问题是 - 这个 UpdateView 不应该自动填充我的表单吗?

Very silly mistake on my part.对我来说非常愚蠢的错误。

I was using the same HTML template to add and edit these records, which had the {{form.cleaned_data.field_name}} in the <input value="..> tag. This works for retaining data when adding a new record, such as an invalid form, but won't show up when editing an object.我使用相同的 HTML 模板来添加和编辑这些记录,它在<input value="..>标签中有{{form.cleaned_data.field_name}} 。这适用于在添加新记录时保留数据,例如作为无效表单,但在编辑对象时不会显示。

The fix was to create a new template (identical page), but fill the <input value="... with the necessary object value template tag ie {{object.field_name}} .修复方法是创建一个新模板(相同的页面),但用必要的对象值模板标记(即{{object.field_name}} )填充<input value="...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM