0

I'm trying to set the value of a Django field inside of the Form class. Here is my model

class Workout(models.Model):
    user = models.ForeignKey(User , db_column='userid')

    datesubmitted = models.DateField() 
    workoutdate = models.DateField(); 
    bodyweight = models.FloatField(null=True);
    workoutname = models.CharField(max_length=250)

Here is the form class, in which i am attempting to achieve this:

class WorkoutForm(forms.ModelForm):

    class Meta: 
        model = Workout

    def __init__(self,*args, **kwargs):
        # this is obviously wrong, I don't know what variable to set self.data to
        self.datesubmitted = self.data['datesubmitted']

Ok, sorry guys. I'm passing the request.POST data to the WorkoutForm in my view like this

w = WorkoutForm(request.POST)

However, unfortunately the names of the html elements have different names then the names of the model. For instance, there is no date submitted field in the html. This is effectively a time stamp that is produced and saved in the database.

So I need to be able to save it inside the form class some how, I think.

That is why I am trying to set the datesubmitted field to datetime.datetime.now()

Basically I am using the form class to make the verification easier, and I AM NOT using the form for it's html output, which I completely disregard.

4
  • So... what are you trying to do? Commented Dec 25, 2012 at 23:59
  • Are you trying to get the posted data? Commented Dec 26, 2012 at 0:00
  • I added more information Commented Dec 26, 2012 at 0:04
  • Your form is a ModelForm the how the html elements have different names? Commented Dec 26, 2012 at 0:17

2 Answers 2

3

You have to do that in the save method of your form

class WorkoutForm(forms.ModelForm):

    class Meta: 
        model = Workout

    def __init__(self,*args, **kwargs):
        super(WorkoutForm, self).__init__(*args, **kwargs)

    def save(self, *args, **kw):
        instance = super(WorkoutForm, self).save(commit=False)
        instance.datesubmitted = datetime.now()
        instance.save()

How ever you can set that in your model also to save the current datetime when ever a new object is created:

datesubmitted = models.DateTimeField(auto_now_add=True)

You can set some extra values set in form as:

form = WorkOutForm(curr_datetime = datetime.datetime.now(), request.POST) # passing datetime as a keyword argument

then in form get and set it:

def __init__(self,*args, **kwargs):
    self.curr_datetime = kwargs.pop('curr_datetime')
    super(WorkoutForm, self).__init__(*args, **kwargs)
Sign up to request clarification or add additional context in comments.

5 Comments

Now what about for other arbitrary values in arbitrary Forms, I would have to validate all of this data before I call the save method correct? Would I have to completely re-define the is_valid() method to accompany these arbitrary values being assigned to an arbitrary form?
the model is going to validate the fields it self. e.g. if you have a field A and it is a required field the form will raise ValidationError if you left it empty
is there any way i can assign that value globally, for instance in the init method? will datesubmitted = self.data['datesubmitted'] do the trick?
Isn't that how you are suppose to access the request.POST data passed to the Form?
I have updated the answer check at the end. you should get the data after it is validated using self.cleaned_data
0

You should not be using a ModelForm for this. Use a normal Form, and either in the view or in a method create a new model instance, copy the values, and return the model instance.

2 Comments

Why is this? I'm closely tied with a Model, so then I thought I was suppose to use a ModelForm
A ModelForm takes the field names from the model. Since this is not what you want, you should not be using one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.