I am having an error in the form django.db.utils.IntegrityError: NOT NULL constraint failed:
in my app I ask the user to create a new project and then is ask via a form to add team member name mail.if the mail already exist in the database the user is invited to by mail to login to the app if the mail is not in the database the user is asked by mail to sign in. Then the invited member is added to the team.
I am getting that error when trying to assign an existing user in the data base
here is my code :
def TeamRegister2(request):
#import pdb; pdb.set_trace()
InviteFormSet = formset_factory(InviteForm2)
if request.method == 'POST':
formset = InviteFormSet(request.POST)
if(formset.is_valid()):
for i in formset:
mail = i.cleaned_data['Email']
if MyUser.objects.filter(email = mail).exists():
user = MyUser(email = mail)
u1 = user.id # get user ID
a1 = MyUser.objects.get(email = request.user.email) #get user email
a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the user
a3 = a2.latest('id') # extract the last project
a4 = a3.team_id # extract the team linked to the project
a4.members.add(u1) # add the member to the team
invited_user = MyUser.objects.get(email = mail)
current_site = get_current_site(request)
message = render_to_string('acc_join_email.html', {
'user': invited_user.first_name,
'domain':current_site.domain,
})
mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
to_email = mail
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
else:
user = MyUser(email = mail)
password = MyUser.objects.make_random_password()
user.set_password(password)
user.is_active = False
user.is_employee = True
user.save()
u1 = user.id #get user id
a1 = MyUser.objects.get(email = request.user.email) #get user email
a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the user
a3 = a2.latest('id') # extract the last project
a4 = a3.team_id # extract the team linked to the project
a4.members.add(u1) # add the member to the team
current_site = get_current_site(request)
message = render_to_string('acc_active_email.html', {
'user':user,
'domain':current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
to_email = user.email
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
messages.success(request, 'testouille la fripouille')
return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':a3.id}))
else:
print("The entered form is not valid")
else:
formset = InviteFormSet()
return render(request,'team_register.html', {'formset':formset})
MyUser Model:
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=150, blank=True, null=True)
last_name = models.CharField(max_length=150, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_hr = models.BooleanField(default=False)
is_candidate = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
company = models.CharField(max_length=100, blank=True, null=True)
Team model:
class Team(models.Model):
team_name = models.CharField(max_length=100, default = '')
team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
members = models.ManyToManyField(MyUser, related_name="members")
def __str__(self):
return self.team_name
Project models:
class Project(models.Model):
name = models.CharField(max_length=250)
team_id = models.ForeignKey(Team, blank=True, null=True)
project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True)
candidat_answers = models.ManyToManyField('survey.response')
any idea how to fix that error and add the user to the team ?
thx you ;)
traceback:
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
328. return Database.Cursor.execute(self, query, params)
The above exception (NOT NULL constraint failed: website_team_members.myuser_id) was the direct cause of the following exception:
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/raphaelbendenoun/Documents/Django Projects/Authentication_project/registration/views.py" in TeamRegister2
85. a4.members.add(u1) # add the member to the team
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in add
934. self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in _add_items
1103. for obj_id in new_ids
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in bulk_create
443. ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _batched_insert
1099. self._insert(item, fields=fields, using=self.db)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _insert
1076. return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
1107. cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
80. return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/utils/six.py" in reraise
685. raise value.with_traceback(tb)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
328. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /registration/auth_team_register3/
Exception Value: NOT NULL constraint failed: website_team_members.myuser_id
You are trying to add an unsaved MyUser instance to the manytomany field. You have to get the object instead of creating a new object.
user = MyUser.objects.get(email=mail)
a4.members.add(user)
Related
Im Created 2 Models.
Account
UserProfil
First Of All, User Register email, fullname, password1, password2. The data Sending To Database in table Account.
Second, User Will Login, if success, he will go to dashboard. in dashboard have a profil Form.
In The Profil Form, He Will input data profil, likes number phone, birth date. etc. and will store in table UserProfil
All of data in UserProfil relationship with Account.
Im Try to create 'Profil Form'. Like This.
my Question is How To Put the data Full_Name in this form ?
i got Error Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name ...
authentication/models.py
class Account(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
full_name = models.CharField(max_length=150)
create_account = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_reviewer = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name']
def __str__(self):
return self.full_name
dashboard/models.py
class UserProfil(models.Model):
jenis_kelamin_choice = (
('Pria', 'Pria'),
('Wanita', 'Wanita' ),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
nik = models.CharField(max_length=11, null=True, unique=True)
nidn = models.CharField(max_length=11, null=True, unique=True)
def __str__(self):
return str(self.user)
dashboard/views.py
class UserProfilFormView(CreateView):
template_name = 'dashboard/profil.html'
form_class = UserProfilForm
def form_valid(self, form):
userPofil = form.save(commit=False)
userPofil.user = Account.objects.get(user__full_name=self.request.user)
userPofil.save()
messages.success(self.request, 'Data Profil Berhasil Disimpan.')
print(self.request.user)
return super().form_valid(form)
File Traceback :
Internal Server Error: /dashboard/profil
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "D:\Project\hibahinternal\dashboard\views.py", line 26, in
form_valid
userPofil.user = Account.objects.get(user__full_name=self.request.user)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 424, in get
clone = self._chain() if self.query.combinator else self.filter(*args,
**kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\query.py", line 968, in
_filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1286, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1112, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted,
self.get_meta())
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-
packages\django\db\models\sql\query.py", line 1539, in names_to_path
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'user' into
field. Choices are: create_account, email, full_name, groups, id,
is_active, is_admin, is_reviewer, is_staff, is_superuser, last_login,
logentry, password, user_permissions, userprofil
[20/Dec/2021 19:31:48] "POST /dashboard/profil HTTP/1.1" 500 136397
Thanks
Your Account has no user field, this also would not make much sense, since that is the user account. You do not need to make a query to the Account model anyway: request.user works with the user model, here account, so you can use request.user directly:
from django.contrib.auth.mixins import LoginRequiredMixin
class UserProfilFormView(LoginRequiredMixin, CreateView):
template_name = 'dashboard/profil.html'
form_class = UserProfilForm
def form_valid(self, form):
form.instance.user = request.user
messages.success(self.request, 'Data Profil Berhasil Disimpan.')
print(self.request.user)
return super().form_valid(form)
Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].
halo i'm working on a project that requires user to give a feedback whenever possible using django rest_framework
but im getting an some difficulties doing that
below is my code snippet & err msg
##mode file
class Review(models.Model):
school = models.ForeignKey(
Profile, on_delete=models.CASCADE, related_name='review')
name = models.CharField(max_length=250, blank=True, null=True)
reviewer_email = models.EmailField()
rating = models.CharField(
max_length=250, blank=True, null=True)
review = models.TextField()
##serializer file
class ReviewSerializer(serializers.ModelSerializer):
class Meta:
model = Review
fields = ('name', 'review', 'id', 'reviewer_email', 'rating')
def perform_create(self, serializer):
id = self.request
print(self.request.user.profile)
serializer.save(school=self.request.user.profile.school_id)
##apiView
class ReviewAPIView(generics.CreateAPIView):
serializer_class = ReviewSerializer
permissions = [permissions.AllowAny]
queryset = Review.objects.all()
err msg
File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/rest_framework/generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/rest_framework/mixins.py", line 19, in create
self.perform_create(serializer)
File "/home/olaneat/Desktop/files/project/django/schMrk/sch-market/schoolDetail/apiviews.py", line 213, in perform_create
print(self.request.user.profile)
AttributeError: 'AnonymousUser' object has no attribute 'profile'
[04/Aug/2021 16:00:59] "POST /school-detail/add-review HTTP/1.1" 500 105554
can anyone help pls
You didn't share the request body.
My guess(from the error) is that you didn't specify the id of the school object it should be related to
You should limit access for non-authorized users. Otherwise, self.request.user could be an AnonymousUser object, which has no a profile relation.
permissions = [permissions.IsAuthenticated]
I am making registration form in django. I have followed Set up subdomains for tenants in a Django web app? example but I get the following error.
Traceback (most recent call last):
File "/Users/pierre/Desktop/Django-app/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/pierre/Desktop/Django-app/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/pierre/Desktop/Django-app/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given
Its been hours and I cannot see where it comes from. I am hoping that a pair of fresh (and more experienced) eyes could see my mistake.
Here are the files I am working with:
models.py
class Client(TenantMixin):
name = models.CharField(max_length=100, default='')
email = models.EmailField(default='')
company = models.CharField(max_length=100, default='')
password = models.CharField(max_length=100, default='')
paid_until = models.DateField()
on_trial = models.BooleanField()
created_on = models.DateField(auto_now_add=True)
#
class Domain(DomainMixin):
pass
forms.py
class NewClientForm(forms.ModelForm):
name = forms.CharField(max_length=100)
email = forms.EmailField(max_length=100)
company = forms.CharField(max_length=100)
password = forms.CharField(widget = forms.PasswordInput)
def clean(self):
email = self.cleaned_data.get('email')
company = self.clean_date.get('company')
email_qs = Client.objects.filter(email=email)
if email_qs.exists():
raise forms.ValidationError(
"this email is already being used"
)
company_qs = Client.objects.filter(company=company)
if company_qs.exists():
raise forms.ValidationError(
'this company name is already identified in our system'
)
return email, company
view.py
class SignupView(View):
def get(self, request):
form = NewClientForm()
return render(request, "register.html", {'form': form})
def post(self, request,*args, **kwargs):
form = NewClientForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
tenant = Client(domain_url='company' + ".inventory4.com", schema_name='company', name= 'name')
tenant.save()
with schema_context(tenant.schema_name):
instance.save()
redirect = 'http://' + 'company' + '.inventory4.com:8000/login'
return HttpResponseRedirect(redirect)
return render(request, "register.html", {'form' : form})
Any help would be greatly appreciated!
I have created registration page , model for it and when user gets registered he gets redirected to home page. When i click on register user is getting inserted in database but when it redirects to home page i am getting this error:
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\KR\Desktop\projects\project2\welcome\homeview.py" in home
14. if request.user.is_authenticated():
File "C:\Python27\lib\site-packages\django\utils\functional.py" in inner
234. self._setup()
File "C:\Python27\lib\site-packages\django\utils\functional.py" in _setup
380. self._wrapped = self._setupfunc()
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in
24. request.user = SimpleLazyObject(lambda: get_user(request))
File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in get_user
12. request._cached_user = auth.get_user(request)
File "C:\Python27\lib\site-packages\django\contrib\auth__init__.py" in get_user
180. user_id = _get_user_session_key(request)
File "C:\Python27\lib\site-packages\django\contrib\auth__init__.py" in _get_user_session_key
59. return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
File "C:\Python27\lib\site-packages\django\db\models\fields__init__.py" in to_python
927. params={'value': value},
Exception Type: ValidationError at /home
Exception Value: [u"'1a3288b3-7588-483f-8e85-1affa952dbbf' value must be an integer."]
This is the model:
class user_model(AbstractBaseUser):
user_id = models.CharField(max_length=50, primary_key=True)
username = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=50, default="None")
last_name = models.CharField(max_length=50, default="None")
email = models.EmailField(default="None")
password = models.CharField(max_length=150, default="abc123")
'''Custom user information fields. '''
myself = models.CharField(max_length=300, default="None")
address = models.CharField(max_length=300, default="None")
mobilePh = models.CharField(max_length=20, default="None")
workPh = models.CharField(max_length=20, default="None")
workEmail = models.EmailField(default="None")
last_login = models.CharField(max_length=50, default="None")
profile_pic = models.ImageField(width_field=None, height_field=None,
blank=True, default="None",
upload_to=upload_profile_pic)
banner_pic = models.ImageField(width_field=None, height_field=None,
blank=True, default="None",
upload_to=upload_banner_pic)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['user_id']
class Meta:
db_table = 'user_model'
app_label = 'welcome'
This is the register view
def register(request):
if request.method == 'POST':
if validate_registration_attributes(request.POST):
user_uuid = uuid.uuid4()
try:
user = User.objects.create(user_id=str(user_uuid), last_login=str(datetime.datetime.now()),
username=request.POST['username'],
first_name=request.POST['first_name'],
last_name=request.POST['last_name'],
email=request.POST['email'],
profile_pic="blank_image.png",
banner_pic="blank_image.png",
password='',
)
user.set_password(request.POST['passwd_1'])
user.save()
login(request, user)
return HttpResponseRedirect('/home')
except Exception as err:
user.delete()
print "Something happened"
raise Exception("""EXCEPTION at register-user.objects.create in
userObject:%s""" % (err))
global exceptmsg
return HttpResponseRedirect('/welcome')
else:
print "New account registration form validation failed"
context = {'RegisterResponse': exceptmsg}
return render(request, 'welcome.html', context)
This is the home view:
def home(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/home')
else:
return HttpResponseRedirect('/welcome')
Is it the problem with the model or anything else. Please help.
I had forgot to override the default user model in settings.py. I changed the value of AUTH_USER_MODEL to myappname.user_model. Now it works fine.
I'm trying to do a POST with the following Serializer -
class VariablePUTSerializer(serializers.ModelSerializer):
owner_id = serializers.SerializerMethodField('get_owner_id')
class Meta:
model = Varmst
resource_name = 'varmst'
fields = ('varmst_id', 'varmst_type', 'varmst_name', 'varmst_value', 'varmst_desc',
'varmst_public', 'owner_id', 'varmst_lstchgtm', 'varmst_publish', 'varmst_readonly',
'varmst_calc', 'varmst_starttype', 'varmst_startdt', 'varmst_startcal',
'varmst_offsets', 'varmst_lstval')
def transform_varmst_id(self, obj, value):
maxid = Varmst.objects.latest('varmst_id').varmst_id
if Varmst.objects.filter(varmst_name=obj.varmst_name).exists():
obj.varmst_id = Varmst.objects.filter(varmst_name=obj.varmst_name).values_list('varmst_id')[0]
return obj.varmst_id
else:
obj.varmst_id = maxid + 1
return obj.varmst_id
def get_owner_id(self, obj):
obj.owner_id = Owner.objects.filter(owner_name='Operations').values_list('owner_id')[0][0]
return obj.owner_id
Upon trying to POST data it gives the following error -
Exception Type: ValueError at /deploy/variable/
Exception Value: Cannot assign "786": "Varmst.owner_id" must be a "Owner" instance.
Varmst.owner_id is a FK reference to Owner.owner_id and I've checked the DB and that value (786) does exist so I'm not sure why passing it into the serializer causes it to fail.
Full Traceback below -
Traceback:
File "D:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python27\lib\site-packages\django\views\generic\base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "D:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "D:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
400. response = self.handle_exception(exc)
File "D:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
397. response = handler(request, *args, **kwargs)
File "D:\Tidal\API\views.py" in put
343. return HttpResponse(serializer.data, status=status.HTTP_201_CREATED)
File "D:\Python27\lib\site-packages\rest_framework\serializers.py" in data
573. self._data = [self.to_native(item) for item in obj]
File "D:\Python27\lib\site-packages\rest_framework\serializers.py" in to_native
351. value = field.field_to_native(obj, field_name)
File "D:\Python27\lib\site-packages\rest_framework\fields.py" in field_to_native
1035. value = getattr(self.parent, self.method_name)(obj)
File "D:\Tidal\API\serializers.py" in get_owner_id
162. obj.owner_id = Owner.objects.filter(owner_name='Operations').values_list('owner_id')[0][0]
File "D:\Python27\lib\site-packages\django\db\models\fields\related.py" in __set__
339. self.field.name, self.field.rel.to._meta.object_name))
Exception Type: ValueError at /deploy/variable/
Exception Value: Cannot assign "786": "Varmst.owner_id" must be a "Owner" instance.
Here are my models -
class Owner(models.Model):
owner_id = models.IntegerField(primary_key=True, db_column='owner_id')
owner_type = models.SmallIntegerField(blank=True, null=True)
owner_name = models.CharField(max_length=30, blank=True)
owner_allagents = models.CharField(max_length=1, blank=True)
class Meta:
managed = False
db_table = 'owner'
class Varmst(models.Model):
varmst_id = models.IntegerField(primary_key=True, db_column='varmst_id')
varmst_type = models.SmallIntegerField(blank=True, null=True)
varmst_name = models.CharField(max_length=30, blank=True)
varmst_value = models.TextField(blank=True)
varmst_desc = models.TextField(blank=True)
varmst_public = models.CharField(max_length=1, blank=True)
owner_id = models.ForeignKey(Owner, db_column='owner_id')
class Meta:
managed = False
db_table = 'varmst'
solved by Kevin Christopher Henry as per the following -
If you name the field owner then the db_column will be owner_id, automatically. Feel free to be explicit about the db_column if you want, but name the field anything but owner_id. Otherwise you lose the ability to distinguish between the Django model instance and the integer id.