[英]Django UpdateView not populating form
我已經被這個問題困擾了幾個小時,查看 Django 文檔並調整我的代碼並沒有幫助。
我已經手動編碼了一個 HTML 表單(出於樣式原因)。 一切正常,直到我嘗試通過此表單編輯對象。
我正在使用沒有添加的標准 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)
模型.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)
基本上我的問題是 - 這個 UpdateView 不應該自動填充我的表單嗎?
對我來說非常愚蠢的錯誤。
我使用相同的 HTML 模板來添加和編輯這些記錄,它在<input value="..>
標簽中有{{form.cleaned_data.field_name}}
。這適用於在添加新記錄時保留數據,例如作為無效表單,但在編輯對象時不會顯示。
修復方法是創建一個新模板(相同的頁面),但用必要的對象值模板標記(即{{object.field_name}}
)填充<input value="...
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.