IntegrityError at /***/ (1048, "Column '***' cannot be null") in python django - python

Hi I am getting this error because I have a field in my additional user info model (user = models.OneToOneField(User)) that I am not filling in at sign up (as I want to let the user do it later).
I wondered if there was any way to solve this problem other than allowing null field in the db?
Cheers

Try to
user = models.OneToOneField(User, null=True, blank=True)
And then recreate your db.
You can find more on https://docs.djangoproject.com/en/1.4/ref/models/fields/#null
Else you can use Proxy models:
class UserExtraInfo(User):
#here your extra fields
In this case you won`t need to create UserExtraInfo instance in same time with User.
Read more on https://docs.djangoproject.com/en/1.4/topics/db/models/#model-inheritance

Integrity error occurred basically when you define some database field as not null and pass
the null or blank value
I am assuming you are storing the value in your database by django form
so in that case you can do like
if request.method == POST: # whatever the method
get_form_obj = form.save(commit = False)
Don't forget to make change in your model user field like (null = True,blank = True)
hope this will help

For me it was depth = 1 in serializers.py, just remove this part and the request goes through. Nested serializers were causing the problem because of this (in console it was showing NestedSerializer(read_only=True):)

Related

Django: Field 'object_id' expected a number but got 'fe2b1fd4313c'

I am getting this error while trying to save a model from the admin section using Django admin, this is the error Field 'object_id' expected a number but got 'id_b2cbfe2b1fd4313c'.. I am using django shortuuid package https://pypi.org/project/shortuuid/ to create id field in django, and i choose to use it because the inbuild UUID field keeps giving this error Django UUIDField shows 'badly formed hexadecimal UUID string' error? and the id looks like this id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True). What would be the problem witht the short uuid field.
Based on this, i quote:
If you filter on the ForeignKey, then Django will filter on the primary key of the target object, and that is normally an AutoField, unless you referred to another (unique) column, or defined another primary key as field.
But i dont know what the issue might be now
Models.py
class Channel(models.Model):
id = ShortUUIDField( length=16, max_length=40, prefix="id_", alphabet="abcdefg1234", primary_key=True,)
full_name = models.CharField(max_length=200)
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="channel")
Views.py
def channel_profile(request, channel_name):
channel = Channel.objects.get(id=channel_name, status="active")
context = {
"channel": channel,
}
return render(request, "channel/channel.html", context)
Your database is not sync with your migrations file, because your problem is easy to solve, Django is expecting an ID (integrer) and you are passing a string.
If you have not push your project into production you can delete the migration folder and migrate again, otherwise you need to update your migrations files to change the type for the UD field

Filter user in django and add to a existing group

I am new to Django and I have failing on a task now for a while. I have searched in the Django docs and here for some questions but there nothing is working for me.
Here is my view:
def user_accept(request):
if request.method == 'POST':
username = AddUser.objects.filter(owner=request.user).get().user_request
group_name = Projects.objects.filter(user=request.user).get().group_url
group = Group.objects.get(name=group_name)
group.user_set.add(username)
delete_user = AddUser.objects.filter(user_request=username)
delete_user.delete()
Here is my model:
class AddUser(models.Model):
owner = models.ForeignKey(User)
title = models.CharField(max_length=20, default='', blank=True)
user_request = models.CharField(max_length=30, default='')
answer = models.BooleanField(default=False)
AddUser model is used for users to request access to a specific project. So when a user is requesting a project, data is saved to the AddUser model.
The user field is set to the "owner" of the project so I can filter every project with a proper owner.
If the owner decides to accept the request my user_accept view is executed. Here is the problem, when I try to add the username into the group, I get the following error:
invalid literal for int() with base 10: 'myusername'
I have tried to convert the username with int(username) and tried to get the username's user_id but nothing seems to work... I think it have something to do how I filter my objects but I don't get it.
So thanks a lot for your time, and have a happy new year!
You need the user id or the user object itself to add a user with group.user_set.add.
You can either retrieve the user object from the username, provided usernames are unique and add that:
user = User.objects.get(username=user_request)
group.user_set.add(user)
Or change your AddUser model to store the requester's id via a OneToOne field or ForeignKey instead of username.
Django default groups doesn't allow you to add username into it.
You have to add User objects.
Try
add_user_object = AddUser.objects.filter(owner=request.user).get()
group.user_set.add(add_user_object.owner)

Adding username when submitting form on django

I am trying to store the username of the user currently logged in when they submit information on a form on a django website.
This is what my models.py file looks like so far:
from django.db import models
from django.contrib.auth.models import User
class Transfer(models.Model):
id = models.AutoField(primary_key=True)
username = User._meta.get_field('username')
amount = models.DecimalField(max_digits=10, decimal_places=2)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
however this doesn't seem to work. The migrations etc work fine and the server runs, but when I submit information on the form I get the following error:
Exception Type: IntegrityError
Exception Value: UNIQUE constraint failed: transfer_transfer.username
Any advice on how I could get the username to save would be very helpful.
Thanks in advance
That declaration doesn't make any sense in a model definition. It might "work", in the sense that you get a field with the same properties as User.username, but it isn't doing anything useful; you could just as well define it directly as models.CharField.
Instead you need to define a ForeignKey from Transfer to User, and call it user; there is plenty of documentation on how to do this, and also plenty of questions here on how to fill in the user field automatically on form submission.

Creating a new instance of a Custom User Model in Django

I have a model which is an extension of a User model in Django 1.8. I am also connecting to a MySQL database for this.
class LibraryUser(models.Model):
user_id = models.OneToOneField(User)
is_catalogue_subscriber = models.BooleanField(default=True)
is_research_subscriber = models.BooleanField(default=True)
library_membership_number = models.CharField(max_length=64)
The reason why I extended the User model, of course is to use the authentication framework.
So now, I want to create a new LibraryUser using the library_membership_number as the login username. How should I do so? Do I create the User first then reference the LibraryUser?
ie given some_ variables either received by a POST or by migration of users to the new table
u = User.objects.create_user(email=some_email, password=some_password)
lu = LibraryUser(library_membership_number, user_id = u.id)
lu.save()
Or is there a correct way to do this? Tried finding online but can't find something to particularly address this problem.
You should assign value to the specify fields as the following:
lu = LibraryUser(library_membership_number= '...', user_id = user)
lu.save()
library_membership_number
You can't just assign a variable to library_membership_number. model is a object containing the fields. You should appoint the field and assign it: library_membership_number= '...', or model can't parse which field you will store.
user_id
It has defined foreignkey in advance. It can accept another model object to store: user_id = user. Don't call attribute of the user to store in LibraryUser.

MySQL gives an "Unknown column 'user.id' in 'field list'" error using Django's automatic id

I have my User model set up with no primary key so that the automatic id will be used instead. However, when I try to access it using Django's "_set" notation when it is referenced through a foreign key:
def postDetails(request, pk)
post = Post.objects.get(pk=pk)
if post.user_set.all(): # Errors on this line
[...]
I get an error from MySQL:
OperationalError at /webApp/postDetail/42/ (1054,
"Unknown column 'user.id' in 'field list'")
What am I doing wrong? Should I be accessing it differently? Are there limitations to the automatic id?
Model for reference:
class Post(models.Model):
name = models.CharField(max_length=128)
blog = models.ForeignKey('Blog')
active = models.BooleanField(blank=True)
created_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'post'
def __unicode__(self):
return self.name
class User(models.Model):
level = models.ForeignKey(Level)
post = models.ForeignKey(Post)
name = models.CharField(max_length=64)
note = models.CharField(max_length=4096)
active = models.BooleanField(blank=True, default=True)
class Meta:
managed = False
db_table = 'user'
Something else that I thought to include: I did run syncdb before running this.
EDIT : wrong answer. check comments below
The problem is that you have managed set to False. According to the documentation
If False, no database table creation or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed=False. All other aspects of model handling are exactly the same as normal. This includes
Adding an automatic primary key field to the model if you don’t declare it. To avoid confusion for later code readers, it’s recommended to specify all the columns from the database table you are modeling when using unmanaged models.
You will need to define the primary key as this is not done by default anymore.
Not 100% sure, but I think even though Django will add the id field to the model class, that field will not propagate to the DB with syncdb.
One way to try it would be to rename the existing User table, run syncdb and see if the User table is created. If not (which is likely because of the managed flag) try again with managed=True. If the id field appears in this case then my guess is you'll have to add it manually to the User table with the same parameters as the automatically created one.

Categories