4

What's the right way to assign a User object from django.contrib.auth.models in a view to a model object with a foreign key reference to User? Example new_contact in:

def index(request):
    form = SignupForm(request.POST or None)
    if form.is_valid():
        new_contact = form.save(commit=False)
        new_contact.user = request.user
        new_contact.save()
        # send_mail ...
        return HttpResponseRedirect(reverse('app:template'))
    else:
        return render_to_response('index.html', {'form': form}, context_instance=RequestContext(request))

"new_contact.user = request.user" throws error ValueError at / Cannot assign "": "Contact.user" must be a "User" instance because request.user is an object wrapper, not the actual User (which doesn't exist yet). But if I set new_contact.user = auth.get_user(request) [based on answer here: valueError in modelforms ], it returns NameError 'auth' even though I'm importing django.contrib.auth into my view. What's the right way to do this? thanks

My modelform is:

from django import forms
from .models import Contact

class SignupForm(forms.ModelForm):
 class Meta:
    model = Contact
    fields = ['name','email','company']
Community
  • 1
  • 1
Chris B.
  • 1,505
  • 5
  • 26
  • 48

2 Answers2

8

The import statement should be:

from django.contrib.auth import get_user

And the actual call to get_user():

new_contact.user = get_user(request)

FYI, quote from django.contrib.auth source:

def get_user(request):
    """
    Returns the user model instance associated with the given request session.
    If no user is retrieved an instance of `AnonymousUser` is returned.
    """
    ...

Hope that helps.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

You're missing a step here, somehow. You say the user doesn't exist yet, but that's because you don't have any code that creates it. You need to do that - it's not going to be done for you.

The best way is to subclass the existing UserCreationForm from contrib.auth.forms and add your fields to it.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • He's not creating a user record, so he would not use the UserCreationForm. He's creating a contact record which has a User as a foreign key. `request.user` corresponds to the logged-in user. You either did not read the question carefully or did not understand the concept of lazy evaluation — when he says the User record does not exist yet, he means that because it is a lazily evaluated object, it exists as a wrapper to the actual object, which is supposed to be returned when needed. – Jordan Reiter Mar 17 '15 at 13:49