[Answered ]-Saving Django User in Form


I managed to do something similar:

Base class for all models who are associated with a user:

class UserOwnedModel(models.Model):
    user = models.ForeignKey(User, editable=True)

    class Meta:
        abstract = True

Base class for all forms who are associated with a user:

class UserOwnedForm(forms.ModelForm):
    exclude = ["user", ]

    def __init__(self, user, data=None, *arguments, **keywords):
        if data:
            data['user'] = user.id
            forms.ModelForm.__init__(self, data=data, *arguments, **keywords)

I’m not sure if it’s the best solution (and will be glad for any input or suggestions) but it works for me.
This of course completely removes the user field from the form, so if you need to display the user name, you’ll have to play with the code.


Also, instead of this:

new_story = Story()
new_story.title = story_form.cleaned_data["title"]
new_story.topic = story_form.cleaned_data["topic"]
new_story.copy = story_form.cleaned_data["copy"]
new_story.author = request.user
new_story.zip_code = story_form.cleaned_data["zip_code"]
new_story.latitude = story_form.cleaned_data["latitude"]
new_story.longitude = story_form.cleaned_data["longitude"]

You can do this:

new_story = story_form.save()


Something like this:

class Story(UserOwnedModel):
    title = models.CharField(max_length=100)
    topic = models.CharField(max_length=50)
    copy = models.TextField()
    zip_code = models.CharField(max_length=10)
    latitude = models.FloatField(blank=False, null=False)
    longitude = models.FloatField(blank=False, null=False)
    date = models.DateTimeField(auto_now=True, auto_now_add=True)   
    def __unicode__(self):
         return " %s" % (self.title)

class StoryForm(UserOwnedForm):
    class Meta:
        model = Story

def submit_story(request):
    if request.method == "GET":
        story_form = StoryForm(user=request.user)
    elif request.method =="POST":
        story_form = StoryForm(data=request.POST, user=request.user)
        if story_form.is_valid():
            new_story = story_form.save()
            story_form = StoryForm(user=request.user)

I also changed my initial code a bit.

Leave a comment