Choices in Django forms - django

I am editing the code below to fit forms. What would be the most convenient replacement for choices (below) in a way that they would function similarly to their use in models?
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(max_length=30)
USER_LEVEL = (
('admin', 'Admin'),
('staff', 'Staff'),
('hof', 'Head of Facilities'),
('user', 'User'),
)
user_level = forms.CharField(max_length=7, choices=USER_LEVEL, default='user')

It sounds like you want to use a ChoiceField.
user_level = forms.ChoiceField(max_length=7, choices=USER_LEVEL, default='user')

Related

Make a form that pulls choices from table in DB and then allows user to change to different foreign keys

So I have a user model with the following columns:
username = models.CharField(db_column='Username',max_length=32,unique=True)
email = models.CharField(db_column='Email',max_length=255)
password = models.CharField(db_column='Password',max_length=128)
prosthodontist = models.ForeignKey('Prosthodontist',on_delete=models.SET_NULL,null=True)
I'm trying to make a dropdown that allows the user to change their Prosthodontist value through django forms. It can't be a static list cause it has to always have every available Prosthodontist as they get added.
Just for show this is what I have so far along the lines of the form:
class ChangeProsthodontistForm(forms.ModelForm):
class Meta:
model = User
fields = ('prosthodontist',)
prosthodontist = forms.ChoiceField(
label = "Prosthodontist",
widget = forms.Select(
attrs={
'id':'prosthodontist',
},
),
choices=()
)
Please help me with this cause I'm really confused I feel like I could be able to iterate through the entries with a for loop but I feel like there has to be a better way through Django.
You answer is ModelChoiceField.
prosthodontist = forms.ModelChoiceField(
# ...
queryset = Prosthodontist.objects.all(),
# ...
)

Django retrieve key of group ChoiceField

retrieve key of group ChoiceField
MEDIA_CHOICES = (
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)
),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)
),
('unknown', 'Unknown'),
)
class ressource(models.Model):
....
media = models.CharField(max_length=50, choices=MEDIA_CHOICES)
in field media i have vinyl or cd or vhs or dvd...but how retrieve audio,video, unknown ?
You should prove us more details. First of all choices should be iterable object (tuple for example as it's in your case), but your tuple is very complicated in your case (Django can not process this). You should pass something like this as a choices.
choices example (This is good tuple code)
CHOICES = (
('key', 'value') # key will be inserted in database (and validation purposes), and value is just for representation purposes.
)
LANGUAGES = (
('python', 'Python'),
('js', 'JS'),
('ruby', 'Ruby'),
)
Imagine that, you are trying to retrieving object from database.
class ressource(models.Model):
''' This is your model '''
media = models.CharField(max_length=50, choices=MEDIA_CHOICES)
res = ressource.objects.get(pk=1) # retrieve data from database.
print(res.media) # returns string object. you will read actual value of media field
''' But if you want to read all available choices on this field, Django provide as _meta api. You can use it very nice way '''
res = ressource.objects.get(pk=1)
fields = res._meta.fields # This will return tuple-like object.
for field in fields:
if field.name == 'media':
# you want to find "media" field
print(field.choices) # This will return all available choices on your media field
Hope, it helps you. Good luck.

use django_filters to filter for multiple arguments

I am using Relay, Django, Graphene Graphql.
I would like to use django_filters to filter for multiple arguments of type on accommodation. This is described in my schema file and atm looks like:
class AccommodationNode(DjangoObjectType) :
class Meta:
model = Accommodation
interfaces = (relay.Node,)
filter_fields = ['type']
This works perfectly if I pass a single string like: {"accommodationType": "apartment"}, but what if I want to filter for all accommodations that are apartments OR hotels? something like: {"accommodationType": ["apartment","hotel"]}
This is my model:
class Accommodation(models.Model):
ACCOMMODATION_TYPE_CHOICES = (
('apartment', 'Apartment'),
('host_family', 'Host Family'),
('residence', 'Residence'),
)
school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='accommodations')
type = models.CharField(
max_length=200,
choices=ACCOMMODATION_TYPE_CHOICES,
default='apartment'
)
def __str__(self):
return str(self.school) + " - " + self.type
Is there any way I can do this without writing custom filters as are suggested here? For only one filter field this is a great solution but I'll end up having around 50 throughout my application including linked objects...
Have a look at Django REST Framework Filters:
https://github.com/philipn/django-rest-framework-filters
It supports more than exact matches, like in, which you are looking for, but also exact, startswith, and many more, in the same style of Django's ORM. I use it frequently and have been impressed - it even integrates with DRF's web browseable API. Good luck!
like FlipperPA mentioned, I need to use 'in'. According to the django_filter docs:
‘in’ lookups return a filter derived from the CSV-based BaseInFilter.
and an example of BaseInFilter in the docs:
class NumberRangeFilter(BaseInFilter, NumberFilter):
pass
class F(FilterSet):
id__range = NumberRangeFilter(name='id', lookup_expr='range')
class Meta:
model = User
User.objects.create(username='alex')
User.objects.create(username='jacob')
User.objects.create(username='aaron')
User.objects.create(username='carl')
# Range: User with IDs between 1 and 3.
f = F({'id__range': '1,3'})
assert len(f.qs) == 3
The answer to my question:
class AccommodationNode(DjangoObjectType) :
class Meta:
model = Accommodation
interfaces = (relay.Node,)
filter_fields = {
'type': ['in']
}
With the argument {"accommodationType": "apartment,hotel"} will work

Django choicefield choices not displaying

Im using a choicefield and setting 2 values - 'students', 'teachers',
but for some reason when the form displays it only shows 'teachers' and not 'students'.
class SignUpShortForm(SignUpForm):
role = forms.ChoiceField(
choices=[],
widget=forms.Select(attrs={'class':'form-control'}),
label='I am a...',
)
self.fields['role'].choices = [('Teacher', 'Teacher2')]
Please look here You add to your choices only values without keys. Code might look like this:
CHOICES = (
('students', 'Students'),
('teachers', 'Teachers'),
)
class SignUpShortForm(SignUpForm):
role = forms.ChoiceField(
choices=CHOICES,
widget=forms.Select(attrs={'class':'form-control'}),
label='I am a...',
)

How can I apply forms.ModelChoiceField to a model-form? (Django)

I am a complete beginner with little understanding of widgets etc, I'm using a model-based form that needs to have a drop-down selection box for dietary preferences. this is what I tried to do earlier (obviously wrong):
class Register(models.Model):
dietry_preferences = forms.ModelChoiceField( queryset = "none", "vegetarian", "vegan", "halaal", "kosher", empty_label = "none")
can anyone shed some light on this?
ModelChoiceField is related to forms. It is unclear if you want to build a form or a model. Therefore, for a model:
class Register(models.Model):
PREFERENCES = (
('vt', "vegetarian"),
('vg', "vegan"),
....
)
dietry_preferences = models.CharField(max_length=5, choices=PREFERENCES)
Then you would build a modelform appropriately.
Reference: Django documentation, choices
Otherwise, for a form:
class Register(forms.Form):
PREFERENCES = (
('vt', "vegetarian"),
('vg', "vegan"),
....
)
dietry_preferences = forms.ChoiceField(choices=PREFERENCES)
Reference: Django documentation, ChoiceField