Django - Null value in column "imageLink" violates not-null constraint - python

I've been trying to setup an upload possibility for a form (with the intent to upload pictures) to a database, which is linked to other data in the list but every time I try to run it, it won't ignore the null that is suppose to be the picture. I've been reading up and trying to get this fixed for a solid day and a half but there isn't a lot of documentation to be found on this subject. Am I missing a place where the file needs to be uploaded to and/or is there a way to ignore the null if there hasn't been a photo added to the list?
Error message:
IntegrityError at /createproduct/
null value in column "imageLink" violates not-null constraint
DETAIL: Failing row contains (81, Comedy, Comic, DC, 5, Engels, 5, Henk, haHAA, null, 808, 2000-04-02).
Form snippet 1:
class PRegistrationForm(ModelForm):
ProductsEntry = Products(prodNum=products.id, prodName=products.prodName, prodPrice=products.prodPrice,
prodStock=products.prodStock)
ProductsEntry.save()
ProdData = ProductDetails(prodNum=products(prodNum=products.id), genre=products.genre,
type=products.type, publisher=products.publisher,
totalPages=products.totalPages, language=products.language,
rating=products.rating, author=products.author, desc=products.desc,
imageLink=products.imageLink, pubDatum=products.pubDatum)
ProdData.save()
if commit:
products.save()
return products
Form snippet 2:
class ProductDetails(forms.Form):
products_prodName = forms.CharField(required=True, max_length=200)
products_prodPrice = forms.DecimalField(required=True, max_digits=5, decimal_places=2)
products_prodStock = forms.IntegerField(required=True, max_value=5000, min_value=1)
products_genre = forms.CharField(required=False, max_length=15)
products_type = forms.CharField(required=False, max_length=15)
products_publisher = forms.CharField(required=True, max_length=30)
products_totalPages = forms.IntegerField(required=True, max_value=2000, min_value=1)
products_language = forms.CharField(required=False, max_length=25)
products_rating = forms.IntegerField(required=False, max_value=5, min_value=1)
products_author = forms.CharField(required=True, max_length=30)
products_desc = forms.CharField(required=True, max_length=2000)
products_imageLink = forms.FileField(allow_empty_file=True, required=False)
products_pubDatum = forms.DateField(required=False)
def __init__(self, *args, **kwargs):
super(ProductDetails, self).__init__(*args, **kwargs)
self.fields['products_prodName'].label = "Titel:"
self.fields['products_prodPrice'].label = "Prijs:"
self.fields['products_prodStock'].label = "Quantiteit:"
self.fields['products_genre'].label = "Genre:"
self.fields['products_type'].label = "Type:"
self.fields['products_publisher'].label = "Uitgever:"
self.fields['products_totalPages'].label = "Bladzijden:"
self.fields['products_language'].label = "Taal:"
self.fields['products_rating'].label = "Score:"
self.fields['products_author'].label = "Schrijver:"
self.fields['products_desc'].label = "Beschrijving:"
self.fields['products_imageLink'].label = "Foto:"
self.fields['products_pubDatum'].label = "Uitgeefdatum:"
Models:
class Products(models.Model):
class Meta:
verbose_name_plural = "Products"
prodNum = models.IntegerField(primary_key=True)
prodName = models.CharField(max_length=200)
prodPrice = models.DecimalField(max_digits=5, decimal_places=2)
prodStock = models.IntegerField()
def __str__(self):
return (str(self.prodNum))
class ProductDetails(models.Model):
class Meta:
verbose_name_plural = "Product details"
prodNum = models.ForeignKey(Products, db_column='prodNum')
genre = models.CharField(max_length=50)
type = models.CharField(max_length=50, default="Comic")
publisher = models.CharField(max_length=50)
totalPages = models.IntegerField()
language = models.CharField(max_length=25, default="Engels")
rating = models.IntegerField()
author = models.CharField(max_length=50)
desc = models.TextField()
imageLink = models.CharField(max_length=300)
pubDatum = models.CharField(max_length=30, default="1 januari, 1990")

You haven't added null= True to your field, default is False.
As in the docss
null
If True, Django will store empty values as NULL in the database. Default is False.
So this should work:
imageLink = models.CharField(null=True, max_length=300)

Related

Django AttributeError at /customer/2/ 'ReverseManyToOneDescriptor' object has no attribute 'all'

Hi I am trying to resolve my error issues that I am trying to filter in my customer template. In my views if I place entry_objects= Entry.objects.all(). It is fine, but I want to be able to filter by customer. My query set worked but I can't do reverse bottom to up. :(
Models.py:
class customer(models.Model):
name = models.CharField(max_length= 200, null = True)
phone = models.CharField(max_length= 200, null = True)
email = models.CharField(max_length= 200, null = True)
date_created = models.DateTimeField(auto_now_add=True, null= True)
def __str__(self):
return self.name
class UserTopic(models.Model):
#category for user to chose
#User interest
text = models.CharField(max_length=120, null =True) #we want to display characters with max 250
date_added = models.DateTimeField(auto_now_add=True, null=True ) #allows realtime accuracy upon upload
#string representation of model
def __str__(self):
return self.text
class Tag(models.Model):
tag_name = models.CharField(max_length=15, null=True)
def __str__(self):
return self.tag_name
#entry model
class Entry(models.Model):
cust_name = models.ForeignKey(customer, null= True, on_delete=models.SET_NULL)
tags = models.ForeignKey(Tag, null = True, on_delete=models.CASCADE)
topic = models.ForeignKey(UserTopic, null = True, on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.text[:10]+"..."
# ...
on_delete=models.DO_NOTHING,
Views.py:
def customer_page(request, pk_test):
customer_objects = customer.objects.get(id=pk_test),
entry_objects = customer.entry_set.all()
#entry = Entry.objects.all()
context = {
'entry_objects': entry_objects,
'customer_objects': customer_objects,
}
return render(request, 'user_log/customer.html', context)
Put a related_name field on your Foreign Key so that other model can refer this model back using realated_name field.
class Entry(models.Model):
cust_name = models.ForeignKey(customer, null= True, on_delete=models.SET_NULL, related_name="entries")
Use your customer object (retrieved using pk) to reach all his entries
customer_objects = customer.objects.get(id=pk_test),
entry_objects = customer_objects.entries.all()
Note: I believe customer_objects is retrieved correctly using pk. Use sigular name customer_object not customer_objects .

Is there a way to make foreign key from an attribute to another from other class in django?

class Assignatura(models.Model):
"""docstring for Assignatura"""
nom = models.CharField(max_length = 40)
codi = models.IntegerField()
any_academic = models.CharField(max_length = 7)
class Matricula(models.Model):
"""docstring for Matricula"""
nia_alumne = models.ForeignKey(Alumne, null = False, on_delete=models.CASCADE, verbose_name = 'Nom alumfne')
codi_assignatura = models.ForeignKey(Assignatura, null = False, on_delete=models.CASCADE)
any_academic = models.CharField(max_length = 7)
image = models.ImageField(upload_to="matriculas", null=True)
i Want that codi_assignatura gets only codi from Assignatura
You can make the code field of the Assignatura unique:
class Assignatura(models.Model):
"""docstring for Assignatura"""
nom = models.CharField(max_length=40)
codi = models.IntegerField(unique=True)
any_academic = models.CharField(max_length=7)
If the target field is unique, then you can specify a to_field=… parameter [Django-doc] in the ForeignKey:
class Matricula(models.Model):
"""docstring for Matricula"""
nia_alumne = models.ForeignKey(Alumne, null=False, on_delete=models.CASCADE, verbose_name='Nom alumfne')
codi_assignatura = models.ForeignKey(Assignatura, to_field='codi', null=False, on_delete=models.CASCADE)
any_academic = models.CharField(max_length=7)
image = models.ImageField(upload_to="matriculas", null=True)
Now the codi_assignatura_id field will store the code of the Assignatura to which it is referring.

Django rest framework raw queries select not working

I want to use a raw query in order to make a JOIN in a many to many relationship, and show it in the Django Rest Framework.
But the "SELECT" part of the query is not working, and it shows whatever the serializer has in "fields" and thus the JOIN is also not working.
serializers.py:
class UserTestSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
views.py:
class UserTestQuery(viewsets.ModelViewSet):
queryset = User.objects.raw('SELECT * ' +
'FROM users_user ' +
'INNER JOIN sysadmin_works_as ON users_user.user_id = sysadmin_works_as.employee_id;')
serializer_class = UserTestSerializer
I want to show a join in the API with these 3 models, so I must use raw SQL. Why is it not working?
And the models I'm using are:
class User(AbstractUser):
first_name = None
last_name = None
username = None
user_id = models.AutoField(primary_key=True)
email = models.EmailField(_('email address'), unique=True)
national_id_number = models.CharField(max_length=30)
f_name = models.CharField(max_length=100)
l_name = models.CharField(max_length=100)
star_count = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True,null=True)
is_superuser = models.BooleanField(default = False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True,null=True)
deleted_at = models.DateTimeField(blank = True, null=True)
date_joined = models.DateTimeField(auto_now_add=True,null=True)
app_role = models.ForeignKey(App_roles,related_name='employee',on_delete=models.SET_NULL,blank=True,null=True) #Un Rol_de_Aplicacion le pertenece a muchos usuar
class Works_as(models.Model):
work_id = models.AutoField(primary_key=True)
started_at = models.DateTimeField(auto_now_add=True)
updates_at = models.DateTimeField(auto_now=True)
r_created_at = models.DateTimeField(auto_now_add=True)
r_updated_at = models.DateTimeField(auto_now=True)
r_deleted_at = models.DateTimeField(auto_now=False,blank=True,null=True)
employee = models.ForeignKey(User,related_name='works_as',on_delete=models.SET_NULL,blank=True,null=True)
position = models.ForeignKey(Position,related_name='works_as',on_delete=models.SET_NULL,blank=True,null=True)
class Position(models.Model):
position_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
deleted_at = models.DateTimeField(blank=True,null=True)
upper_position = models.ForeignKey('self',on_delete=models.SET_NULL,blank=True,null=True)
department = models.ForeignKey(Department,related_name='positions',on_delete=models.SET_NULL,blank=True,null=True)
hierarchy_level = models.OneToOneField(Employee_Hierarchy,related_name='position',on_delete=models.SET_NULL,blank=True,null=True)

Django Rest Framework : Fields are not getting create or update after making custom methods inside models

class UserInfo(models.Model):
user_id = models.AutoField(primary_key=True)
user_firstname = models.CharField(max_length=20, verbose_name = "First Name")
user_lastname = models.CharField(max_length=20, verbose_name = "Last Name")
user_email = models.EmailField(max_length=50, verbose_name = "Email Id")
user_dob = models.DateField(auto_now = False, auto_now_add=False, verbose_name = "Date of Birth")
user_mobileno = models.CharField(max_length=14, verbose_name = "Contact No")
user_image = models.ImageField(upload_to = upload_location,
null=True,
blank=True,
width_field = "width_field",
height_field = "height_field", verbose_name = "Profile Picture")
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
user_password = models.CharField(max_length=20, verbose_name = "Password")
user_blood_group = models.CharField(max_length=5, verbose_name = "Blood Group")
user_location_id = models.ForeignKey(Location, on_delete=models.CASCADE, verbose_name = "Current Location")
user_profession = models.CharField(max_length=20, verbose_name = "Profession")
user_fb_id = models.CharField(max_length=20, verbose_name = "Facebook Contact", blank=True)
user_random_id = models.CharField(max_length=20, verbose_name = "Registration Id")
user_created_date = models.DateField(auto_now = True, auto_now_add=False)
user_updated_date = models.DateField(auto_now = True, auto_now_add=False)
def get_name(self):
return "%s %s" % (self.user_firstname, self.user_lastname)
def __str__(self):
return "%s %s" % (self.user_firstname, self.user_lastname)
Not when i made following post request, it's saving user_firstname & lastname and even not updating. And get_name method returning " ".
Folowing is my serializer
class UserSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='get_name')
class Meta:
model = UserInfo
fields = ['user_id','name']
Can anyone help to out this?
Pass the parameters for creating object according to name defined in serializer that will work as you have desired make sure you pass values for all the parameters that can not be null. Now incase you want user to pass the parameter name instead of user_firstname & user_lastname you will need to get the value for name while creating & split name to get firstname & lastname & assign it to user_firstname & user_lastname.

Trying to insert a new column with a list of foreign field in django_tables2

I'm using the django_tables2 to show a list of "repair details". So far so good. However I want to add a new field (it's not in the model): a list of service reports. The relation is 1 to many. and show the serial number which is in another model. It's quite difficult since I add the field but the render_NEW_FIELD doesn't work and i couldn't reach the list of service reports since in the table model I have just access to the record and not to the repair_detail model. I'm using django_tables 0.15
repair/models.py
class RepairDetail(models.Model):
repair = models.ForeignKey('Repair')
repair_detail_number = models.IntegerField()
article_code = models.CharField(max_length=30)
registered_date = models.DateField(null=True)
registered_uid = models.IntegerField(null=True)
registered_initials = models.CharField(max_length=2, null=True)
customer_reference = models.CharField(max_length=20, null=True)
db2_recnum = models.IntegerField()
def __unicode__(self):
return str(self.repair_detail_number)
class ServiceReport(models.Model):
repair_detail = models.ForeignKey('RepairDetail')
status = models.ForeignKey('ServiceReportStatus', on_delete=models.PROTECT)
serial_number = models.ForeignKey('core.SerialNumber')
customer = models.ForeignKey('core.Company')
contact = models.ForeignKey('core.Contact', null=True, on_delete=models.SET_NULL)
project = models.ForeignKey('core.Project')
project_code = models.CharField(max_length=4)
identifier = models.CharField(max_length=1)
repair_date = models.DateField(null=True)
repair_uid = models.IntegerField(null=True)
repair_initials = models.CharField(max_length=2, null=True)
booking_date = models.DateField(null=True)
core/models.py
class SerialNumber(models.Model):
product = models.ForeignKey("Product")
panel = models.ForeignKey("Panel", null=True, blank=True, default = None)
serial_number = models.CharField(max_length=30, default='')
manifest = models.TextField(null=True)
def __unicode__(self):
return self.serial_number
repair/tables.py
class RepairDetailTable(tables.Table):
#serials = tables.Column(accessor='servicereport.serialnumber.serialnumber')
serial = tables.Column()
def __init__(self, *args, **kwargs):
super(RepairDetailTable, self).__init__(*args, **kwargs)
class Meta(object):
model = RepairDetail
fields = ('id', 'repair_detail_number', 'article_code', 'registered_date', 'registered_initials', 'customer_reference', 'serials')
attrs = {'class': 'table table-striped table-bordered protonic'}
empty_text = "No records found."
If you want (1:N instead of N:1) to concatenate all related models in the table cell try to do this in your model layer by setting property, something like this:
class RepairDetail(models.Model):
# ...
#property
def service_reports_list(self):
return self.servicereport_set.all()
Define your own column (inherit tables.Column) and override render method
Add it to your table class:
class RepairDetailTable(tables.Table):
# ...
service_reports_list = YourOwnColumn(some_kwargs)
# ...

Categories

Resources