How do I populate FOREIGN KEY with a Django form - django

I am trying to give the user the ability to enter data
here is my models named cv :
class Experience_Pro(models.Model):
annee_debut = models.IntegerField()
annee_fin = models.IntegerField()
description_exp_pro = models.TextField(null=True,blank=True)
class Ecole(models.Model):
nom_ecole = models.CharField(max_length=50)
classement = models.IntegerField()
class Academic(models.Model):
annee_debut = models.IntegerField()
annee_fin = models.IntegerField()
type_diplome = models.CharField(max_length=10)
description_academic = models.TextField(null=True,blank=True)
ecole = models.ForeignKey('Ecole' , on_delete=models.DO_NOTHING)
class Cv(models.Model):
experience_Pro = models.ForeignKey('Experience_Pro' ,on_delete=models.CASCADE)
academic = models.ForeignKey('Academic',on_delete=models.CASCADE)
and here is my form
class CvForm(forms.ModelForm):
class Meta:
model = Cv
fields = "__all__"
but instead of getting inputs for the user to enter data i get a dropdownlist of already existed records in my database.

Unfortunately, that is the way django is designed when using a ModelForm.
Realistically, you can create two model forms from the Experience & Academic models and join them in the view.
Multiple Models in a single django ModelForm?

Your cv model doesnt have any fields for input. You are only have the relation with other model as a foreignkey relation. This way you can only access the data here not create one

Related

How would I specify a data table that I have set up postgresql?

I am looking to set up the backend logic for a form where it shoots information to a data table that I set up in postgresql and was wondering, how I would specify the data table that I want to send the information to?
You can do this with a ModelForm. Assuming the 'data table' you mention is the database model class, you declare the Model you are sending information to in the Meta class, as shown here:
class Author(models.Model):
name = models.CharField(max_length=100)
title = models.CharField(max_length=3, choices=TITLE_CHOICES)
birth_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ['name', 'title', 'birth_date']
class BookForm(ModelForm):
class Meta:
model = Book
fields = ['name', 'authors']
Notice where it says "model = Book" or "model = Author". This example is from the Django Documentation on ModelForms. You will need to instantiate your ModelForm class in your view.

I want to add max value to my model field based on the data of another model which is related to it through one to many relationship

Image of django admin panel
This are my two models:
class English(models.Model):
date = models.DateField()
topic = models.CharField(max_length=150)
totalMarks = models.IntegerField()
def __str__(self):
return f"{self.id}. {self.topic}"
class Meta:
verbose_name_plural = "English"
class EnglishMarks(models.Model):
student = models.ForeignKey(UserField, on_delete=CASCADE)
test = models.ForeignKey(English, on_delete=CASCADE, related_name="marks")
marks = models.IntegerField(validators=[MaxValueValidator(English.objects.first().totalMarks),MinValueValidator(0)])
I want the marks field of EnglishMarks Model to not exceed the value of totalMarks field of related data of English Model.
Note: I am using Inlines to populate EnglishMarks table while creating new data in English table

Django - Sqlite Database

Any help is greatly appreciated.
I am using Django and SQLite, I am trying to join the auto generated auth_user table with an input table that I have created using a model.
Models.py;
class Input(models.Model):
height = models.IntegerField(default=0)
waist = models.IntegerField(default=0)
bust = models.IntegerField(default=0)
hips = models.IntegerField(default=0)
class Meta:
db_table = "Project_input"
The purpose of joining the tables is so that when a user logs in the information they enter into my input table is only associated with them.
I understand that I have to add a foreign key to this model! But how do I reference the auth_user table?
Just add a ForeignKey field to the model.
class Input(...):
user = models.ForeignKey('auth.User') # (or `settings.AUTH_USER_MODEL`)
# ...
See the Django docs about foreign keys and other many-to-one relations.
I think, All you need that to edit your model to this
Models.py
from django.contrib.auth.models import User
class Input(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='inpute')
height = models.IntegerField(default=0)
waist = models.IntegerField(default=0)
bust = models.IntegerField(default=0)
hips = models.IntegerField(default=0)
class Meta:
db_table = "Project_input"
With this, you make one to one relationship with the class user which Django provides.

How to create custom relation table for ForeignKey or OnetoOne field?

What I want to do is create a model than can be used to store data about a relation between two elements. With ManytoMany fields, I can use the parameter "through" and specify a model which stores two elements foreign keys as below.
def MyModel(models.Model):
relation = models.ManyToManyField('AnotherModel', through='RelationModel')
def RelationModel(models.Model):
model1 = models.ForeignKey('MyModel')
model2 = models.ForeignKey('AnotherModel')
slug = models.CharField()
What would be the equivalent for a OnetoOne relation or a ForeignKey relation ? I've read the docs about custom managers and some posts on SO so in the end I'm quite confused and I dont know what is the solution. Thanks in advance for any help.
you can do like this
from products.models import VendorDetails
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE)
user_location = models.CharField(max_length=50, null=True)
vendor_category = models.ManyToManyField(VendorDetails, through="UserProfileVendorCategory")
class UserProfileVendorCategory(models.Model):
user_profile = models.ForeignKey(UserProfile)
vendor_category = models.ForeignKey(VendorDetails)
location = models.CharField(max_length=256)

Django admin Trouble saving new records with M2M fields - instance needs to have a primary key value before a many-to-many relationship can be used

Problem Statement:
I am using Django admin to manage many tables, some of which have many-to-many relationships. I am unable to save new records in tables (models) that have manytomany fields defined. I am able to render the add form just fine. The problem is only upon trying to save the record. I do not have the same problem when updating an existing record.
Using the models below, I receive the following error: 'Bout' instance needs to have a primary key value before a many-to-many relationship can be used.
The Bout model has a many-to-many relationship with the Equipment model. The BoutEquipment model is the intermediate model.
I've researched this problem high and low on StackOverflow and via Google, but am thus far unable to find a solution.
Disclosure: I'm new to Django and new-ish to Python. I'm hopeful that there's a relatively simple solution to this problem.
Thanks in advance.
models.py
class Bout(models.Model):
boutid = models.AutoField(db_column=u'BoutID', primary_key=True)
sessionid = models.ForeignKey(Session, db_column=u'SessionID', verbose_name=u'Session')
activitytypeid = models.ForeignKey(Activitytype, db_column=u'ActivityTypeID', verbose_name=u'Activity Type')
locationid = models.ForeignKey(Location, db_column=u'LocationID',verbose_name=u'Location')
equipment = models.ManyToManyField(Equipment, verbose_name=u'Related Equipment', related_name=u'Bout_Equipment', blank=True, null=True) #through = 'BoutEquipment'
intensitymetrics = models.ManyToManyField(Intensitymetric, verbose_name=u'Related Intensity Metrics', related_name=u'Bout_IntensityMetrics', blank=True, null=True) #through = 'BoutIntensitymetric'
def __unicode__(self):
return u'%s %s' % (self.sessionid, self.activitytypeid)
class Meta:
db_table = u'app_bout'
verbose_name = u'Bout'
verbose_name_plural = u'Bouts'
class Equipment(models.Model):
equipmentid = models.AutoField(db_column=u'EquipmentID', primary_key=True)
name = models.CharField("Name", max_length=100, db_column=u'Name')
equipmenttypeid = models.ForeignKey(Equipmenttype, db_column=u'EquipmentTypeID', verbose_name = u'Equipment Type')
def __unicode__(self):
return self.name
class Meta:
db_table = u'app_equipment'
verbose_name = u'Equipment'
verbose_name_plural = u'Equipment'
class BoutEquipment(models.Model):
id = models.AutoField(db_column=u'id', primary_key=True)
boutid = models.ForeignKey(Bout, db_column=u'Bout_ID')
equipmentid = models.ForeignKey(Equipment, db_column=u'Equipment_ID')
def __unicode__(self):
return self.name
class Meta:
db_table = u'app_bout_equipments'
admin.py
class EquipmentAdmin(admin.ModelAdmin):
form = EquipmentForm
inlines = [EquipmentShoeInline, EquipmentLogInline]
list_display = ('name','equipmenttypeid','manufacturer','retired','retiredby','retiredon','notes')
fields = (
'name',
('equipmenttypeid','manufacturer'),
('retired','retiredby','retiredon'),
'notes'
)
class BoutAdmin(admin.ModelAdmin):
form = BoutForm
filter_horizontal = ('equipment','intensitymetrics',)
list_display = ('sessionid','activitytypeid','locationid','sequence','activehand','baddata')
inlines = [BoutDeviceInline,]
fields = (
('sessionid','locationid','activitytypeid'),
'videofilelocation',
'sequence',
'activehand',
'notes',
'baddata',
('equipment','intensitymetrics')
)
A manytomany field in django is a join table between the two models you want to connect to each other.
This happens on SQL level, so both models have to exist in the database.
bout = Bout()
...
equipment = Equipment()
...
bout.equipment.add(equipment)
#fails because bout and equipment are not saved
bout.save()
bout.equipment.add(equipment)
#fails because equipment is not saved
equipment.save()
bout.equipment.add(equipment)
#yay :)