views.py
class CreateTaskView(LoginRequiredMixin, MyStaffUserRequiredMixin, generic.CreateView):
model = Task
form_class = TaskForm
template_name = 'tasks/form.html'
def get_context_data(self, *args, **kwargs):
ctx = super(CreateTaskView, self).get_context_data(*args, **kwargs)
ctx['task_form'] = ctx.get('form')
ctx['action'] = 'Add'
ctx['cancel_url'] = reverse('tasks.list')
return ctx
def form_valid(self, form):
task_object = form.save(self.request.user, commit=False)
admin_time = form.cleaned_data['admin_time']
if admin_time:
task_object.execution_time=admin_time
task_object.save(self.request.user)
messages.success(self.request, _('Your task has been created.'))
return redirect('tasks.list')
class UpdateTaskView(LoginRequiredMixin, MyStaffUserRequiredMixin, generic.UpdateView):
model = Task
form_class = TaskForm
template_name = 'tasks/form.html'
def get_context_data(self, *args, **kwargs):
ctx = super(UpdateTaskView, self).get_context_data(*args, **kwargs)
ctx['task_form'] = ctx.get('form')
ctx['action'] = 'Update'
ctx['cancel_url'] = reverse('tasks.detail', args=[self.get_object().id])
return ctx
def form_valid(self, form):
admin_time = form.cleaned_data.get('admin_time')
if admin_time:
self.object.execution_time = admin_time
self.object.save()
form.save(self.request.user)
messages.success(self.request, _('Your task has been updated.'))
return redirect('tasks.list')
我在两个类中都使用了相同的函数:def form_valid(self,form)
是否可以在表单中添加此验证?
我的 forms.py
class TaskForm(forms.ModelForm):
keywords = (forms.CharField(
help_text=_('Please use commas to separate your keywords.'),
required=False,
widget=forms.TextInput(attrs={'class': 'medium-field'})))
admin_time = forms.CharField(
help_text=_('Enter If more than 60 minutes.'),
required=False,
widget=forms.TextInput(attrs={'class': 'fill-width'}))
def __init__(self, *args, **kwargs):
if kwargs['instance']:
initial = kwargs.get('initial', {})
initial['keywords'] = kwargs['instance'].keywords_list
kwargs['initial'] = initial
super(TaskForm, self).__init__(*args, **kwargs)
def _process_keywords(self, creator):
if 'keywords' in self.changed_data:
kw = [k.strip() for k in self.cleaned_data['keywords'].split(',')]
self.instance.replace_keywords(kw, creator)
def clean(self):
cleaned_data = super(TaskForm, self).clean()
start_date = cleaned_data.get('start_date')
end_date = cleaned_data.get('end_date')
if start_date and end_date:
if start_date >= end_date:
raise forms.ValidationError(_("'End date' must be after 'Start date'"))
admin_time = cleaned_data.get('admin_time')
if admin_time:
execution_time=admin_time
return cleaned_data
def save(self, creator, *args, **kwargs):
self.instance.creator = creator
super(TaskForm, self).save(*args, **kwargs)
if kwargs.get('commit', True):
self._process_keywords(creator)
return self.instance
class Media:
css = {
'all': ('css/admin_ace.css',)
}
class Meta:
model = Task
fields = ('name', 'short_description', 'execution_time', 'difficulty',
'priority', 'repeatable', 'team', 'project', 'type', 'start_date',
'end_date', 'why_this_matters', 'prerequisites', 'instructions',
'is_draft', 'is_invalid')
widgets = {
'name': forms.TextInput(attrs={'size': 100, 'class': 'fill-width'}),
'short_description': forms.TextInput(attrs={'size': 100, 'class': 'fill-width'}),
'instructions': AceWidget(mode='markdown', theme='textmate', width='800px',
height='300px', wordwrap=True,
attrs={'class': 'fill-width'}),
'start_date': CalendarInput,
'end_date': CalendarInput,
'why_this_matters': forms.Textarea(attrs={'rows': 2, 'class': 'fill-width'}),
'prerequisites': forms.Textarea(attrs={'rows': 4, 'class': 'fill-width'}),
}
我尝试过编辑
def clean(self)
,但它不起作用。当我从views.py
任何帮助将不胜感激
答案 0 :(得分:0)
您可以覆盖模型形式的save()
方法来执行此操作:
def save(self, commit=True):
instance = super(TaskForm, self).save(commit=False)
admin_time = self.cleaned_data['admin_time']
if admin_time:
instance.execution_time=admin_time
instance.save()
return instance