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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With