0

I am getting the following error: Cannot assign "<django.db.models.fields.related.ForeignKey>": "Worry.user" must be a "User" instance.

I trying to assign the id of the current user to an object I have just created.

This is part of my models.py:

from django.contrib.auth.models import User  
from django.forms import ModelForm  
from django.db import models  

    class UserForm (ModelForm) :  
        class Meta:  
            model = User        
    class Worry(models.Model) :    
        user = models.ForeignKey(User) #Many worries to 1 user relation

This is part of my views.py:

from django.db import models  
from django.shortcuts import render_to_response, redirect, get_object_or_404  
from django.template import RequestContext  
from django.contrib.auth.models import User  
from holaProy.models import UserForm, Worry, WorryForm, Statistics, StatisticsForm  
def worry_add (request):  
    form = WorryForm (request.POST or None)  
    if form.is_valid():      
        wform.user = models.ForeignKey('User')  #HERE IS THE PROBLEM I THINK
        wform.save()  
        return redirect (index)  
    return render_to_response ('holaProy/worry_add.html', {'worry_form': form}, context_instance = RequestContext(request))</code>

How should I do it in order to succesfully assign the current user id to the "user" field for the actual worry instance?

3 Answers 3

4

The issue is, indeed, on that line:

wform.user = models.ForeignKey('User')

wform.user should be set to a User instance. Something like this:

user = request.user    # Retrieve proper user according to your needs
wform.user = user
0
0

Try:

def worry_add(request):
    form = WorryForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        worry = form.save(commit=False)
        worry.user = #assign this to an instance of a User object
        worry.save()
0

That's the line where you are having your problem.

Basically, you are searching for a string. You need to get the actual database object before. Try this:

User = User.objects.get(pk='User')
wform.user = models.ForeignKey('User')  #Now User refers to the database object, not a string

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.