python - Anonymous user error -
i'm trying save form data anonymous user, below error when trying save form data in createview". i'm not clear issue is?
valueerror: cannot assign "<simplelazyobject: <django.contrib.auth.models.anonymoususer object @ 0x11126bc18>>": "euser.user" must "user" instance.
models:
class euser(models.model): online_account = models.booleanfield() supplier1 = models.onetoonefield(supplieraccount) supplier2 = models.onetoonefield(supplieraccount) supplier3 = models.onetoonefield(supplieraccount) address = models.onetoonefield(address) user = models.foreignkey(settings.auth_user_model) class supplieraccount(models.model): supplier = models.foreignkey(supplier) username = models.charfield(max_length=255) password = models.charfield(max_length=255)
form:
class servicetypeform(forms.modelform): # bool_choices = ((false, 'no'), (true, 'yes')) # online_account = forms.booleanfield(widget=forms.radioselect(choices=bool_choices)) def __init__(self, *args, **kwargs): super(servicetypeform, self).__init__(*args, **kwargs) self.fields['service_type'].initial = 'd' class meta: model = euser fields = ('service_type', 'online_account')
view:
class servicetypeview(createview): form_class = servicetypeform template_name = "standard_form.html" success_url = '/' def form_valid(self, form): form.instance.user = self.request.user super().form_valid(form) online_account = form.cleaned_data['online_account'] if online_account: return redirect('../online') else: return redirect('../address')
if user not logged in, request.user
anonymous user. doesn't make sense assign anonymous user form.instance.user
, because anonymous user not exist in database or have primary key.
how change code depends on how want application work.
if want allow anonymous users create service types,
if self.request.user.is_authenticated(): form.instance.user = self.request.user
for work, need change user field make optional.
user = models.foreignkey(settings.auth_user_model, blank=true, null=true)
after making change, you'll need run makemigrations
, migrate
, update database.
another option restrict view logged in users. in django 1.9+, can loginrequiredmixin
.
from django.contrib.auth.mixins import loginrequiredmixin class servicetypeview(loginrequiredmixin, createview): ...
Comments
Post a Comment