0

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
Jicksy John
  • 169
  • 1
  • 2
  • 13

1 Answers1

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
madzohan
  • 11,488
  • 9
  • 40
  • 67
  • 'Task' object has no attribute 'admin_time' This is the error I get now. – Jicksy John Nov 01 '14 at 22:34
  • That worked!! :) Thanks!! There's one problem now. I have one more class UpdateTaskView(LoginRequiredMixin, MyStaffUserRequiredMixin, generic.UpdateView): def form_valid(self, form): Can I use the same form_valid definition there also? – Jicksy John Nov 01 '14 at 22:44
  • I have added UpdateTaskView class also in my main post. If the value of admin_time is edited- that should also be reflected- what would be the changes required for it? – Jicksy John Nov 01 '14 at 22:54
  • It gives me this error: save() got an unexpected keyword argument 'update_fields' – Jicksy John Nov 01 '14 at 23:04
  • sorry I am already sleeping :) yes try copy-paste it to updateview – madzohan Nov 01 '14 at 23:11
  • I meant its perfect now- the code. Thanks for your help, and goodnight!! :) – Jicksy John Nov 01 '14 at 23:12
  • Will it be possible to give this function in forms.py? – Jicksy John Nov 04 '14 at 15:38
  • In this case you can simply remove from form class `admin_time` and use `execution_time` – madzohan Nov 04 '14 at 21:07
  • I have updated the function above, is that the way to do? But it doesn't change the value – Jicksy John Nov 05 '14 at 04:13
  • maybe because you call `super(TaskForm, self).clean()` you don't need to do that, I've updated unswer – madzohan Nov 05 '14 at 12:22
  • It now shows key error: for line admin_time = self.cleaned_data['admin_time'] Exception value: keyerror – Jicksy John Nov 05 '14 at 14:58
  • self.cleaned_data.get('execution_time') I added .get also in. But code runs without any error- but value doesn't get changed! It only shows execution_time – Jicksy John Nov 05 '14 at 16:07
  • I don't know what you expect to see but `def clean_execution_time` should returns only `execution_time` cleaned value to form save – madzohan Nov 05 '14 at 17:21
  • yes, but if admin_time is present then the value in execution_time should be the value of admin_time right? But that change is not visible. – Jicksy John Nov 05 '14 at 17:27
  • add after `execution_time = admin_time` line `print('execution_time changed')`. Or debug it and see if it runs or no. – madzohan Nov 05 '14 at 17:30
  • nothing is changed- how can I debug? I added print statement like you mentioned- but in my terminal- its' not showing. – Jicksy John Nov 05 '14 at 18:18
  • If you created this method in class TaskForm - admin_time was not empty and execution_time didn't change :), I'm using PyCharm IDE and button debug :) but you can http://stackoverflow.com/questions/1118183/how-to-debug-in-django-the-good-way google how to do this – madzohan Nov 05 '14 at 18:34