无法比较和更新表单字段和模型字段django

时间:2014-11-01 22:08:58

标签: python django

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):
    admin_time = form.cleaned_data['admin_time']
    if admin_time:
        Task.execution_time=admin_time
    form.save(self.request.user)

    messages.success(self.request, _('Your task has been created.'))
    return redirect('tasks.list')

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'"))
    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'}),
    }

form.html

  <fieldset class="task-info">
  {{ form_field(task_form['execution_time']) }}
  {{ form_field(task_form['admin_time'], help_text=False) }}
  {{ form_field(task_form['difficulty']) }}
  {{ form_field(task_form['priority']) }}
</fieldset>

我的html页面上有execution_time和admin_time两个字段。 正在处理表单如果存在admin_time,我希望execution_time更改为admin_time, 那就是execution_time = admin_time。

我在views.py中添加了相同的内容     def form_valid(self,form):但它不起作用。

execution_time在models.py

中给出
Class Task(CachedModel, CreatedModifiedModel, CreatedByModel):
   execution_time = models.IntegerField(
    choices=((i, i) for i in (15, 30, 45, 60)),
    blank=False,
    default=30,
    verbose_name='estimated time'
)

我想在不添加admin_time模型的情况下实现相同目标。

我的views.py还有一个课程

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):
    form.save(self.request.user)

    messages.success(self.request, _('Your task has been updated.'))
    return redirect('tasks.list')

如果在编辑期间更改了admin_time的值,那么它也应该更新

下面的答案是有效的:我想进一步了解的是,我可以将代码放在forms.py中吗?作为一个单一的功能?

在forms.py中添加此功能会起作用还是需要进行更多更改?

def clean_execution_time(self):
cleaned_data = super(TaskForm, self).clean()
data = cleaned_data.get('execution_time')
admin_time = cleaned_data.get('admin_time')
if admin_time:
    data=admin_time
return data

1 个答案:

答案 0 :(得分:1)

# for create and update view
def form_valid(self, form):
    admin_time = form.cleaned_data.get('admin_time')
    task_object = form.save(self.request.user, commit=False)
    if admin_time:
        task_object.execution_time = admin_time
    task_object.save(self.request.user)


# update
def clean_execution_time(self):
    execution_time = self.cleaned_data.get('execution_time')
    admin_time = self.cleaned_data.get('admin_time')
    if admin_time:
        self.cleaned_data['execution_time'] = execution_time = admin_time

    return execution_time