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.
Related
my models.py
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_details = models.TextField(default='')
mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True)
isDraft = models.BooleanField(default=True)
ratings = models.FloatField(default=0)
no_of_students_registered = models.IntegerField(default=0)
# registered_students = models.ManyToManyField(RegisteredNames, null=True, blank=True)
no_of_students_attended = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
class RegisteredNames(models.Model):
name = models.CharField(max_length=100, unique=True)
liveclass_id = models.ForeignKey
I am creating a endpoint where when a user register himself his name will get added to registered_students , so i had made a registered students ManyToMany Field hoping it will get updated when a user is registered but then i understand that it will contain all the names that are present in the RegisteredNames Model meaning names registered across all the liveclasses but i want only the names that are registered for a particular liveclass in the field so i need a array like field which i think is not possible so please help me in improving my logic, how can i achieve it
The documentation and django tutorials are very good: https://docs.djangoproject.com/en/3.2/topics/db/models/ https://docs.djangoproject.com/en/3.2/intro/tutorial02/#creating-models
Your code is very close. You don’t need the many-to-many field, and you need to specify the type of the Foreign key relationship in the RegisteredNames. You can do this:
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_details = models.TextField(default='')
mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True)
isDraft = models.BooleanField(default=True)
ratings = models.FloatField(default=0)
no_of_students_attended = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
class RegisteredNames(models.Model):
name = models.CharField(max_length=100, unique=True)
liveclass = models.ForeignKey(LiveClass_details, on_delete=Models.CASCADE)
Then, simply:
name = RegisteredNames.objects.create(name="Dhruv", liveclass_id=1)
To get all the registered names from a liveclass_details:
names = LiveClass_details.objects.get(id=1).registerednames_set.all()
num_reg = len(names)
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']
I a trying to generate a primary key using the other fields of the model.
unique_id = models.CharField(max_length=10, primary_key=True)
restaurant_name = models.CharField(max_length=100)
manager_name = models.CharField(max_length=50)
email = models.EmailField(max_length=100, unique=True)
mobile_no = models.CharField(unique=True, validators=[validate_mobile], max_length=10)
state = models.CharField(choices=STATES, max_length=2)
city = models.CharField(max_length=20)
pincode = models.CharField(max_length=8, validators=[validate_pincode])
street_address = models.CharField(max_length=100)
password = models.CharField(max_length=256)
You can make use of the default field option.
See: https://docs.djangoproject.com/en/2.0/ref/models/fields/#default
Just like how it's done on UUIDField.
See: https://docs.djangoproject.com/en/2.0/ref/models/fields/#uuidfield
Then I'm guessing just try to assign your algo each and every time on your unique_id
My model has a default pk with AutoField (integer) but later on i discovered that i need to use BigAutoField instead!
And also i have data in then with other models referencing the student model:: how do i change the pk field to BigAutoField and also reflects on other referencing models
class Student(models.Model):
matric_no = models.CharField(max_length=20, unique=True) # first set it to U(random)
password = models.CharField(max_length=128)
session = models.ForeignKey(Session, null=True)
programme = models.ForeignKey(Programme, null=True)
school = models.ForeignKey(School, null=True)
course_comb = models.ForeignKey(CourseComb, null=True)
serial = models.IntegerField(null=True)
current_level = models.CharField(max_length=3, choices=LEVEL_CHOICES, default='100', null=True)
last_login = models.DateField(null=True)
is_active = models.CharField(max_length=1, default=1, choices=((1, 1), (0, 0)))
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
a model referencing Student
class Profile(models.Model):
student = models.OneToOneField(Student, on_delete=models.CASCADE)
attachment = models.ImageField(null=True, blank=True, verbose_name="Profile Image")
surname = models.CharField(max_length=255, null=True, verbose_name="Surname")
othernames = models.CharField(max_length=255, null=True, verbose_name="Othernames")
SEX_CHOICES = (
("M", "Male"),
("F", "Female")
)
Set primary_key=True in the field definition:
id = models.BigAutoField(primary_key=True)
If you want to use this in multiple models you could also make an abstract model and let others inherit it:
class BigPkAbstract(models.Model):
id = models.BigAutoField(primary_key=True)
class Meta:
abstract = True
And in your other models:
class SomeModel(BigPkAbstract):
<your model here>
I made some basic models for a listing of a business, like so:
class Business(models.Models):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=225, blank=True)
address = models.CharField(max_length=150, blank=True)
city = models.CharField(max_length=150, blank=True)
state_id = models.IntegerField(null=True, blank=True)
zip = models.CharField(max_length=33, blank=True)
country = models.CharField(max_length=150, blank=True)
url = models.CharField(max_length=765, blank=True)
class States(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=96)
state_abbr = models.CharField(max_length=24, blank=True)
In the admin when I edit each business it shows the state_id field. But how do I connect it with the state model to show a select dropdown listing of the states?
Also, how do I show the state abbreviation in the view of a business?
An alternative that doesn't require a separate state table:
from django.contrib.localflavor.us.us_states import STATE_CHOICES
class Business(models.Models):
...
state = models.CharField(max_length=2, choices=STATE_CHOICES, null=True, blank=True)
...
Edit in 2015 (django 1.8)
you should check the django official localflavor repo: https://github.com/django/django-localflavor.
from localflavor.us.models import USStateField
class Business(models.Models):
…
state = USStateField(null=True, blank=True)
…
Some tests are available on the repo for this specific usage.
Docs available here.
You need to use a ForeignKey field.
Make the following changes.
class Business(models.Models):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=225, blank=True)
address = models.CharField(max_length=150, blank=True)
city = models.CharField(max_length=150, blank=True)
#state_id = models.IntegerField(null=True, blank=True)
# Define a new state field that creates a ForeignKey relationship with States
state = models.ForeignKey('States', null=True, blank=True)
zip = models.CharField(max_length=33, blank=True)
country = models.CharField(max_length=150, blank=True)
url = models.CharField(max_length=765, blank=True)
class States(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=96)
state_abbr = models.CharField(max_length=24, blank=True)
#Define the __unicode__ method, which is used by related models by default.
def __unicode__(self):
return self.state_abbr
By default ForeignKey fields append '_id' to the field name when creating the column name in the database. So, the new "state" field in the Business class will automatically use the column "state_id" that you've previously defined, unless you've changed some of the default behavior of Django.
For more on this:
Check out Django's documentation of
the ForeignKey field
Search "ForeignKey" on stackoverflow.com