This field is required error in django default image - django

I set my imagefield as NONE but when i tried to enter data without image from django admin panel it is showing that This field is required.
this is my urls.py
`
class dish(models.Model):
dish_id = models.AutoField
dish_name = models.CharField(max_length=255)
dish_size = models.CharField(max_length=7)
dish_price = models.IntegerField()
dish_description = models.CharField(max_length=255)
dish_image = models.ImageField(upload_to="", default=None)
dish_date = models.DateField()
def __str__(self):
return self.dish_name
`
How to set it as none if user not select any image

dish_image = models.ImageField(upload_to="", default=None, blank=True, null=True)
Both blank=True and null=True are needed. Here’s why: What is the difference between null=True and blank=True in Django?
——-
Also, you don’t need dish_id. IDs are automatically generated and accessed with model_instance.pk
https://docs.djangoproject.com/en/4.1/topics/db/models/#automatic-primary-key-fields

Related

I have a problem with Django database. in model

I have specified that my bio and image fields can be empty, but why does it give me an error and say that I have to fill it in?
class User_account(models.Model):
email = models.EmailField()
fullname = models.CharField(max_length=30)
username = models.CharField(max_length=20)
password = models.CharField(max_length=30)
marital_status = models.BooleanField(default=False)
bio = models.CharField(null=True, max_length=200)
visitor = models.IntegerField(default=0)
image = models.ImageField(null=True, upload_to='profile_img')
Specifying null=True [Django-doc] does not mean the field is not required. null=True has only impact on the database: it makes the field NULLable. You should use blank=True [Django-doc] to make the field not required:
class User_account(models.Model):
# …
bio = models.CharField(null=True, blank=True, max_length=200)
# …
image = models.ImageField(null=True, blank=True,
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from User_account to UserAccount.

Can't save tags in admin using django-taggit

I am using django-taggit and I can't save the tags when creating a new post from the admin panel, when I edit a post I had already created before adding django-taggit, it saves the tags well, what might be the problem?
Models.py
class BlogPost(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='blog_posts')
description = models.CharField(max_length=500)
content = RichTextUploadingField(config_name='awesome_ckeditor')
tags = TaggableManager()
category = models.ForeignKey(
'Category', related_name='category', on_delete=models.CASCADE)
cover = models.ImageField(upload_to='images/')
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
#read_time = models.TimeField(null=True, blank=True)
status = models.IntegerField(choices=STATUS, default=0)
series = models.IntegerField(choices=SERIES, default=0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("blog:detail", args=[str(self.slug)])
Do you receive any error during saving post? Did you make python manage.py migrate after installing django-taggit and include it to INSTALLED_APPS? You have made change in the model so you need to prepare your db to work with new data.

Django - populate model with foreignkey via csv import?

I've trying to setup a model to be populated with a csv file, and to use one of the fields as a foreignkey:
First, I tried creating a model from an existing postgresql table using inspectdb, migrating and then change the type of the field I want to relate from charfield to foreignkey, but I got errors
Then I tried creating an empty model with the inspectdb description, then importing a csv in postgresql, and finally changing the field i want to foreignkey. In the admin site I can view the imported data and the relations, but when I query the model I got another error with the foreignkey field, and it wont let me migrate (cant recognize the charfield, it asks for integer)
-the csv column I want for a foreignkey is charfield, when i create the model before importing the csv i got an error, then checking the datatype in the postgres table is says integer, can it be set to charfield??
What workflow work best for importing a csv to a model and use one of the fields as a foreignkey (charfield type)??
Thanks
This is the model to be related to :
class D_Roles(models.Model):
predio = models.CharField(max_length=254)
dest = models.CharField(max_length=254)
dir = models.CharField(max_length=254)
rol = models.CharField(max_length=254)
vlr_tot = models.FloatField()
ub_x2 = models.FloatField()
ub_y2 = models.FloatField()
instrum = models.CharField(max_length=254)
codzona = models.CharField(max_length=254)
nomzona = models.CharField(max_length=254)
geom = models.MultiPointField(srid=32719)
def __str__(self):
return self.rol
class Meta():
verbose_name_plural = "Roles SII"
The models I want to populate with csv:
class Dom2015CertInf(models.Model):
id = models.CharField(primary_key=True, max_length=80)
nombre_archivo = models.CharField(max_length=180, blank=True, null=True)
derechos = models.CharField(max_length=120, blank=True, null=True)
dir_calle = models.CharField(max_length=120, blank=True, null=True)
dir_numero = models.CharField(max_length=120, blank=True, null=True)
fecha_certificado = models.CharField(max_length=50, blank=True, null=True)
numero_certificado = models.CharField(max_length=50, blank=True, null=True)
numero_solicitud = models.CharField(max_length=50, blank=True, null=True)
#Original field from inspectdb
#rol_sii = models.CharField(max_length=50, blank=True, null=True)
#FOREIGNKEY Changed after creating the model and importing the csv
rol_sii = models.ForeignKey(D_Roles, db_column='rol_sii', on_delete=models.CASCADE, default=0)
zona_prc = models.CharField(max_length=120, blank=True, null=True)
def __str__(self):
return str(self.numero_certificado)
class Meta:
managed = True
verbose_name_plural = "2015 Certificados Informaciones Previas"
ordering = ['numero_certificado']

Django: creating M2M relationship inline

I'm trying to create a view with a formset of forms for the "Link" model. The problem is that in each form I would like the user to have the possibility of not just choosing from the already created TargetLink objects, but to edit them inline.
class ClientUrl(models.Model):
client = models.ForeignKey(UpstreamClientModel, null=True)
url = models.URLField(unique=True, null=False)
active = models.BooleanField(default=True)
def __unicode__(self):
return self.url
class Meta:
verbose_name = 'url'
ordering = ['url']
KEYWORD_TYPES = (
('PN', 'Pending'),
('MN', 'Money'),
('BR', 'Brand'),
('LT', 'Long Tail'),
)
class ClientKeyword(models.Model):
client = models.ForeignKey(UpstreamClientModel, null=True)
kw_type = models.CharField('keyword type', max_length=2,
choices=KEYWORD_TYPES, default='LT')
keyword = models.CharField(max_length=150, unique=False)
directions = models.CharField(max_length=200, blank=True,
help_text='e.g: 25 chars, use "affordable rental cars"')
def __unicode__(self):
return self.keyword
class Meta:
ordering = ['keyword', ]
unique_together = ('client', 'keyword')
class TargetLink(models.Model):
keyword = models.ForeignKey(ClientKeyword, related_name='target_links')
url = models.ForeignKey(ClientUrl, related_name='target_links')
def __unicode__(self):
return '{0}:{1}'.format(self.keyword, self.url)
class Link(models.Model):
client = models.ForeignKey(UpstreamClientModel, related_name='links')
target = models.ForeignKey(Target, related_name='links')
user = models.ForeignKey(User, blank=True, null=True, related_name='links')
link_type = models.ForeignKey(LinkType, related_name='links')
site = models.ForeignKey(Site, blank=True, null=True,
related_name='links')
site_url = models.URLField(blank=True,
help_text='leave blank until url is live')
month = models.DateField(blank=True, null=True)
target_links = models.ManyToManyField(TargetLink, related_name='links')
How could I accomplish this?
One way might be to have a form that is outside of your formset for the TargetLinks and use Knockout.js or another client-side framework to push the updated choices for TargetLinks to the target_links field in the formsets.

Overriding Django profiles' profile_detail view

I installed django profiles/registration and everything seems to be fine. When a user registers their profile is created also. Now what i want to do is query another Model which is Company based on the user id of User. I dont want to change django-profiles view but add the extra field on urls to match and query Company model. When i hardcode the url (ex:put the id number of the userprofile like so userprofile=1, it works.). So when a user is logged in and goes to profile detail page Company assigned to them is queried based on their user.id.
class UserProfile(models.Model):
user = models.OneToOneField(User)
#email = models.CharField(max_length=200, blank=True, null=True)
# Other fields here
#company = models.ForeignKey(Company,blank=True,null=True)
#office = models.CharField(max_length=200, blank=True, null=True)
def __unicode__(self):
return self.user.username
class Company(models.Model):
userprofile = models.ForeignKey(UserProfile, null=True, blank=True)
comp_name = models.CharField(max_length=200,blank=True,null=True)
comp_address = models.CharField(max_length=200,blank=True, null=True)
comp_email = models.CharField(max_length=200,blank=True, null=True)
comp_zip = models.IntegerField(blank=True, null=True)
comp_phone = models.IntegerField(blank=True, null=True)
comp_city = models.CharField(max_length=200,blank=True, null=True)
#comp_state = models.USStateField(blank=True, null=True
comp_state = models.CharField(blank=True, max_length=2)
compwebsite = models.URLField(max_length=200, blank=True, null=True)
twitterurl = models.URLField(max_length=200, blank=True, null=True)
facebookurl = models.URLField(max_length=200, blank=True, null=True)
def __unicode__(self):
return self.comp_name
url(r'^profiles/(?P<username>\w+)/$', 'profiles.views.profile_detail', {'extra_context':{'queryset':Company.objects.filter(userprofile=request.user.id)}},),
You might want to call it from inside a view
from *** import profile_detail
def my_view(request, username):
extra_context = {}
return profile_detail(request, queryset=Company.objects.filter(userprofile=request.user.id),
template_name="my_template.html",
paginate_by=20,
extra_context=extra_context)