how to filter one-to-one User models - django-filter

i have classe profile with oneToOne relation withe User class and whene I try to filter with Profil.user field in template I dont have textEdit or input tag to write, but i have list drop down withe all user
please excuse my english i live in afriqua and here we speack french sorry again.
`
class UtilFilters(django_filters.FilterSet):
liste_util=(('association','association'),('employe','employe'),('cartiers',' cartiers'),('organisme','organisme'),('citoyen','citoyen'))
user__username=django_filters.CharFilter(lookup_expr='icontains')
phone = django_filters.CharFilter(lookup_expr='icontains')
list_ch= django_filters.ChoiceFilter(choices=liste_util)
bio_p = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = profile
fields = ['phone','list_ch','bio_p','user']
`

Related

How do I populate my form fields with data from the database Django

Hello I have a form page and I only need users to fill in certain fields, with the rest of the fields being pre-filled for them based on the module they pick.
While I can fetch the objects from my database -- i.e. the dropdown list shows Module Object (1), Module Object (2) -- I need only certain fields in these objects, which is why this similar sounding post couldn't answer my question:
Populate a django form with data from database in view
Here's my forms.py
class inputClassInformation(forms.Form):
module = forms.ModelChoiceField(queryset=Module.objects.all())
duration = forms.CharField(disabled=True, required=False)
description = forms.CharField()
assigned_professors = forms.ModelChoiceField(queryset=Class.objects.filter(id='assigned_professors'))
models.py -- not the full models are shown to reduce the post's length
class Module(models.Model):
subject = models.CharField(max_length=200, default="")
class Class(models.Model):
module = models.ForeignKey(Module, on_delete=models.CASCADE, default="")
duration = models.CharField(max_length=200, default="")
description = models.CharField(max_length=200, default="")
assigned_professors = models.CharField(max_length=200, default="")
So an expected result would be:
1) The Module field shows the subjects, instead of Module objects in its dropdown list and
2) The duration field is automatically filled in for the user, based on the module they picked. The reason is so that the user only has to manually fill in certain fields, while the rest are automatically generated.
This has had me stuck for a long while, help is appreciated. Thanks!
So an expected result would be:
1) The Module field shows the subjects, instead of Module objects in its dropdown list and
2) The duration field is automatically filled in for the user.
These are essentially two different questions.
To answer the first: you can override the:
__str__ method for your Model class for python 3 and django 1.8) and the
__unicode__ method for your Model class for django <1.8 and not python3.
For example, to make subjects appear instead of "XXXX Object" for your class do:
class Module(models.Model):
subject = models.CharField(max_length=200, default="")
def __unicode__(self):
return self.subject
Similarly, change __unicode__ for __str__ as appropriate for your django version.
Now, to answer your second question:
2) The duration field is automatically filled in for the user.
You need to do two things:
Do not display the duration field in your form (unless you want to give the users the chance to sometimes fill it in manually)
Override the save method
An example:
class Class(models.Model):
module = models.ForeignKey(Module, on_delete=models.CASCADE, default="")
duration = models.CharField(max_length=200, default="")
description = models.CharField(max_length=200, default="")
assigned_professors = models.CharField(max_length=200, default="")
def save(self, *args, **kwargs):
self.duration = #The value you'd want to automatically set here#
super(Model, self).save(*args, **kwargs)

Django: Can you create a relationship with an auto-generated through table?

My code looks something like this:
from django.db import models
from django.conf import settings
User = settings.AUTH_USER_MODEL
class Dish(models.Model):
name = models.CharField(max_length=200)
class Meal(models.Model):
name = models.CharField(max_length=200)
dishes = models.ManyToManyField(Dish)
The many-to-many dishes field will result in a database table called 'myapp_meal_dishes' being created that includes id, meal_id, and dish_id fields.
I would like to add a MealDishEater model that connects with that auto-generated table:
class MealDishEater(models.Model):
meal_dish = models.ForeignKey(MealDishes, on_delete=models.CASCADE)
eater = models.ForeignKey(User, on_delete=models.PROTECT)
ate_meal = models.BooleanField(default=False)
Of course, that doesn't work, because MealDishes is not defined. Is there a way to do this or do I have to create my own through table?
You can access the ManyToManyField intermediate model with the through attribute. So this should work:
class MealDishEater(models.Model):
meal_dish = models.ForeignKey(Meal.dishes.through, on_delete=models.CASCADE)
Personally, though, I always create explicit through models for ManyToManyFields rather than allowing such magic.

Django CheckboxSelectMultiple widget : render only selected data by default

Greeting, I have a manytomany field call user in my model_A model, in my form, how can I display only the list of selected data associated to the model_A by default instead of listing entire entries from the User model in my html page? my intention is to create a setting page where I can remove the user associated to a project
below is my code :
model.py :
class model_A(models.Model):
user = models.ManyToManyField(User, blank=True)
form.py :
class EditForm(forms.ModelForm):
prefix = 'edit_form'
class Meta:
model = model_A
fields = '__all__'
widgets = {'user':forms.CheckboxSelectMultiple}
html :
<div class="field">
{{form.user}}
</div>
Any help is much appreciated thanks
Change user queryset inside __init__ method of EditForm class.
class EditForm(forms.ModelForm):
prefix = 'edit_form'
class Meta:
model = model_A
fields = '__all__'
widgets = {'user':forms.CheckboxSelectMultiple}
def __init__(self, **kwargs):
self.event = kwargs.pop('event')
super().__init__(**kwargs)
# replace dots with your conditions in filter
self.fields['user'].queryset = self.user.filter(...)
UPDATE
List users that are associated with Model_A
self.fields['user'].queryset = self.user.all()

Django REST - Resolving Foreign Keys and M2M's in a Serializer

I have the following Models:
class Player(models.Model):
name = models.CharField(max_length=30)
class Achievement(models.Model):
name = models.CharField(max_length=30)
class UnlockedAchievement(models.Model):
achievement = models.ForeignKey(Achievement)
date = models.DateTimeField()
class PlayerAchievements(models.Model):
player = models.ForeignKey(Player)
unlocked_achievements = models.ManyToManyField(UnlockedAchievement, related_name="unlocked_achievements", blank=True, null=True)
With a PUT, I'm trying to resolve both the Player's foreign key as well as the nested relationship of all the Achievements. My JSON data effectively looks like this:
{"name":"playername",
"achievements":
{
"ach1":"timestamp",
"ach2":"timestamp",
}
}
What I can't figure out is the magic combination of which kinds of Serializers to use and, when using them, which serializer fields or nested Serializers to use to be able to resolve Players by name, and the unlocked achievements (and then their Achievement foreign keys) by providing a name.
In this case I don't have access to id numbers, hence why things are done by names.
Such a strange mixture it seems. Can anyone lend a hand? Thanks in advance!
You can use nested relationships to fully include the serialization of a related model:
class AchievementSerializer(serializers.ModelSerializer):
class Meta:
model = Achievement
class UnlockedAchievementSerializer(serializers.ModelSerializer):
achievement = AchievementSerializer(many=False)
class Meta:
model = UnlockedAchievement
class PlayerAchievementsSerializer(serializers.ModelSerializer):
unlocked_achievements = UnlockedAchievementSerializer(many=True)
class Meta:
model = PlayerAchievements
class PlayerSerializer(serializers.ModelSerializer):
player_achievements = PlayerAchievementsSerializer(many=False)
class Meta:
model = Player
Then just filter the Player object by name and serialize it.

Django - How to link to a legacy database via intermediary?

I have to integrate a legacy design with my Django project and I am looking for some advice on using an intermediary. The existing design works but now I need to filter the Project by a third table.
In english - I have a Organization (Django) and which points to many Projects (Legacy). But all of the Project don't refer to that Organization. I have a third table ProjectMap which was build via a Trigger to address that. It corresponds the Organization.name to a project.
How do I glue this together in order allow me to do this.
projects = Organization.objects.get(pk=1).projects.all()
And it won't get ALL of the projects just the ones which match in the third table. Here is what I have so far..
By the way if anyone has a better strategy I'm all ears
class Organization(models.Model):
name = models.CharField(max_length=32)
projects = models.ManyToManyField(Project)
class Project(models.Model):
"""This is the project info page..
Note: 'id' does exist and is the pk.
"""
result_number = models.IntegerField(null=True, db_column='LBLDGRUNNO', blank=True)
building_number = models.IntegerField(db_column='LBLDGNO')
name = models.CharField(max_length=150, db_column='SPIBLGNAME', blank=True)
class Meta:
db_table = u'PROJINFO'
managed = False
class ProjectMap(models.Model):
projinfo_table_id = models.IntegerField(null=True) # 'id' of Project
name = models.CharField(max_length=128, null=True) # 'name' in Organization
Thanks so much!
Not sure if this is what your asking, but you can use the through call on the ManyToManyField to define an intermediate table:
class Organization(models.Model):
name = models.CharField(max_length=32)
projects = models.ManyToManyField(Project, through="ProjectOrganisation")
class Project(models.Model):
#Stuff Here
class ProjectOrganisation(models.Model):
project = models.ForeignKey(Project)
organization = models.ForeignKey(Organization)
#Other Fields Here
Django does this automatically with manytomany fields anyway, just if you want to add extra fields, this is the way to do it.