Using multiselect widget for a ForeignKey field Django - python

Good day i seem to be lost in how i want to implement something. so here is how it goes
ive got a carowner model
class carowner(models.Model):
.....
carowner = models.CharField(primary_key=True)
and a cars model
class car(models.Model):
....
carowner_id = models.ForeignKey(carowner)
it has a foreignkey cause each car can only have one carowner
but a carowner can have many cars but i run into a situation where
ive got a modelform
class assigncarownertocar(forms.ModelForm):
car= forms.ModelChoiceField(widget=MultipleSelect())
class Meta:
model=carowner
fields = [# all fields that are needed ]
what i want to happen is when im creating a new carowner asigns him multiple cars in the same form from a queryset i provided when the modelform is initialized.
so everything loads fine in the form. i see the list of cars but once i select one or more i get this
'Select a valid choice. 539421 is not one of the available choices.
what i am asking is should i add the modelmultiplechoicefield to the model that holds the foreign key?
cause right now i have it attached to the carowner model. i dont see documentation stating that this is wrong

Related

Django - Team/User relationships

I'm at a loss... I'm just learning Django and I am really rather confused about how to make a field work the way I would like it to.
I understand that Django has a native "Groups" model. However, I am looking to build my own teams model for customization and practice.
Here is my models.py file for my Users app:
from django.db import models
from django.contrib.auth.models import User
class Team(models.Model):
members = models.ManyToManyField(User)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
admin = models.BooleanField("Admin Status")
Here's where I'm confused. I would like to be able to call the team that the user is part of directly from User.Profile. So, I want to add a field to my Profile class that will automatically populate with the team name when a user is added to a team.
A potential problem I can see is that, currently, I can assign a user to multiple teams. This doesn't bother me, perhaps I can have a Profile model field that automatically populates with a list of all the teams that the user is associated with. Regardless, I can't figure out what type of field I would need to use, or how to do this.
Does that make sense?
A potential problem I can see is that, currently, I can assign a user to multiple teams.
Indeed, you can however easily retrieve the Teams the myprofile object is a member of with:
Team.objects.filter(members__profile=myprofile)
You thus can make a property for the Profile model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
admin = models.BooleanField("Admin Status")
#property
def teams(self):
return Team.objects.filter(
members__profile=self
)
Then you thus access the Teams of a myprofile with myprofile.teams.
So, I want to add a field to my Profile class that will automatically populate with the team name when a user is added to a team.
From my limited knowledge of database, you can add a name field to your Team model.
Keeping in mind your requirement as mentioned in question, i would suggest you to use django reverse relations to get all the teams the profile is associated with
user_teams = User.objects.get(id='user_id').profile_set.all()[0].team_set.all()
to know more about django ORM reverse relation, here is a very short article

Django user daily updating model

I'm new in django. I want to create applications where users will be able to create objects and update them daily (add new days and new descriptions and photos).
So my question is:
1.
In models.py I need to create class Object(models.Model) and use ForeignKey(settings.AUTH_USER_MODEL) or OneToOneRel(settings.AUTH_USER_MODEL) to connect user which create object with this object ?
2.
I need to create an extra class day where there will be fields such as a subtitle description etc and add it to the object class?
3.
How I can create form or views to daily updating ?
1i. You need User and Objects model. You can use built in django User model
You have one to many relation one user can have many objects. Therefore you need foreign key. So make Object model like this:
class Object(models.Model)
title = models.CharField(max_length=100)
description = models.CharField(max_length=1000)
user = ForeignKey(model=User)
Don't understand
Django provides you simple admin which is suitable if you want to just add, update, delete. Otherwise you can use model forms to build your custom views and templates for edit database records. Model Forms
and Forms. Here you will find everything you need to create custom views with model forms.

Pass model objects to choices field in django

I have a model called Student that has a manytomany relationship with a model called Courses. I have another model called Attend in which I want to get all the courses the student is taking and pass it in as a select menu containing the courses the student is taking. I tried to get the id using the foreign key "student" and then get courses belonging to that student and put it in a list and pass it to choices but it didn't work obviously. I would like to know how I can get the courses belonging to the student to appear in the select menu.
Here is my model.
class Attend(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, default="")
time_signed_in = models.DateTimeField(auto_now_add=True)
isSignedIn = models.BooleanField(default=False)
# Below does not work, I get an error 'ForeignKey' object has no attribute 'id'
#courses = User.objects.get(id=student.id).courses
course = models.ForeignKey(Course, on_delete=models.CASCADE)
To render the courses the student is taking you should try using django forms.
If I understand correctly, you want a form that uses ModelMultipleChoiceField:
Allows the selection of one or more model objects, suitable for
representing a many-to-many relation.
class AttendForm(forms.Form):
courses = forms.ModelMultipleChoiceField(queryset=Courses.objects.filter(student__id=id))
That exapmple would only work to show the data to the user and then retrieving its choice. There is a slightly different approach to this case and that is using a ModelForm.
Every ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form.
ModelForm is a "database driven" form in which you can perform many task involving calls to the database easily.
Note: The queryset I used in the example is just an example, you dont have to use it that way.

'makemigrations' asks for a default with none-abstract model inheritance

I'm trying a simple model inheritance:
class Product(models.Model):
creation_date = models.DateTimeField(auto_now_add=True)
class Application(Product):
name = models.CharField(max_length=200)
'makemigrations' asks for a default:
You are trying to add a non-nullable field 'product_ptr' to
application without a default; we can't do that (the database needs
something to populate existing rows).
I saw here that I could Product an abstract model with a Meta class, but I can't do that since I'm refereing it specifically in other models as an actual model:
class Comment(models.Model):
product = models.ForeignKey('Product', related_name="comments")
Running 'makemigrations' when the database is removed also leads to the same issue.
Anything I can do?
Django 1.9
You haven't explained what exactly is the change that you have made, it seems that you have changed your Application model to inherit from Product where it previously inherited from models.Model. That causes django to create a 1 to 1 mapping behind the scenes. The addition of the product_ptr which you didn't add to the model yourself enters the picture
ref: https://docs.djangoproject.com/en/1.9/topics/db/models/#multi-table-inheritance
The inheritance relationship introduces links between the child model
and each of its parents (via an automatically-created OneToOneField).
It's a bit tricky to add this field to a table with data during a migration because this field needs to be unique. If you are merely creatig a new model named Application, a value of 1 would be ok.

How to set to null the reference on a ForeignKey - Django

I've just started in Python and Django and I'm trying to do something pretty easy, but after many hours searching I haven't found the answer, so here it comes my question:
I have to Models: User (CustomUser) and House.
I want to have a field in User that references a House and that can be optional, emulating the fact that a person can be inside (when a reference is attached) or outside (when it's null) a house.
In the House model, I want to have also a "list" of people (Users) that are at a given moment inside the house.
To accomplish this, I've done something like this:
class User(AbstractBaseUser):
# other attrs ...
# (ForeignKey) house: House where the user is right now
house = models.ForeignKey(House,
verbose_name='where is the user right now',
related_name='house_now', blank=True, null=True,
on_delete=models.SET_NULL
)
def leaveHouse(self):
house = self.house.delete()
class House(models.Model):
# (ManyToManyField) people: List of Users that are currently within the house
people = models.ManyToManyField(settings.AUTH_USER_MODEL,
verbose_name='people inside the house right now',
related_name='people',
blank=True
)
def removeUser(self, user):
self.people.remove(user)
The problem is that when I use the function leaveHouse of the User model, instead of setting the ForeignKey to Null or Empty, it deletes the House object referenced to the key.
Any suggestion on what I'm doing wrong, best practices and that kind of stuff please?
Thanks in advance!
EDIT:
Anyway, just a little question related to this.
Why in the django admin if I set the field "house" as "----" (None) works fine, but if I set the field "home" as "----" gives me
"'NoneType' object has no attribute 'pk'"
# (ForeignKey) home: Main house
home = models.ForeignKey(House,
verbose_name='default house',
related_name='home', blank=True, null=True,
on_delete=models.SET_NULL
)
Instead of deleting the related house object, set the link value to None:
self.house = None
self.save()
I know this question is very old and already answered, but I'd like to point out that your model design is not the best for a number of reasons.
You shouldn't set the ManyToMany field in the House model, unless you want a User to be simultaneously in more than one house.
Using a foreign key to the House model when a ManyToMany relationship already exists is wrong as you could set a connection between a User and a House with the ManyToMany connection table and have a null value set for the Foreign Key.
Regarding the use the related_name parameter of the ManyToMany field, I think you understood it wrongly. That's the name you would use to access the houses list from the User model as user.<related_name>. So houses would have been a better choice. The same applies to the related_name of the ForeignKey field to the House model, you would use it to access the users list from a House instance house.<related_name>, in this case people would fit.
I link the documentation of the latest Django version, but this still applies also to older versions
https://docs.djangoproject.com/it/4.0/ref/models/fields/#django.db.models.ForeignKey.related_name
Given this, when you use the removeUser method to remove a user from a house, you are not acting on the ForeignKey as that is another (redundant) relation in the database.

Categories