简体   繁体   中英

Not able to compare and update a form field and model field 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>

I have execution_time and admin_time two fields on my html page. While the form is processing If admin_time is present, I want execution_time to be changed to admin_time, that is execution_time=admin_time.

I have added the same in views.py in def form_valid(self,form): but it does not work.

execution_time is given in 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'
)

I want to achieve the same without adding a model for admin_time.

I have one more class in my 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')

If the value of admin_time is changed during edit- then it should also be updated

Below answer is working: what I want to know further is, can I put the code in forms.py? as a single function?

Adding this function in forms.py will it work or do I need to make more changes?

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
# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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