Question:
How to create a dropdown menu in django?

Problem:

Hello I have the following model and form


models.py

class Project(models.Model):

    name            = models.CharField(max_length=255, null=False)

    user            = models.CharField(max_length=255, null=True)

    notes           = models.TextField(null=True)


forms.py

class ProjectForm(ModelForm):


class Meta:

    model       = Project

    fields      = ["name", "user", "notes"]


How can I create a dropdown menu based on the builtin users in django, so that in my project form for users, I would have a drop down menu for the users instead of a textbox?


Solution 1:

You need to change the model to use User model and update form.


New models.py

from django.db import models

from django.contrib.auth import get_user_model



User = get_user_model()



class Project(models.Model):

    name = models.CharField(max_length=255, null=False)

    user = models.ForeignKey(User, on_delete=models.CASCADE)

    notes = models.TextField(null=True)


New forms.py

from django import forms

from .models import Project, User



class ProjectForm(forms.ModelForm):

    user = forms.ModelChoiceField(queryset=User.objects.all(), empty_label="Select a user")


    class Meta:

        model = Project

        fields = ['name', 'user', 'notes']


Suggested blogs:

>Invoking Python script from scons and pass ARGLIST

>Migrate From Haruko To AWS App: 5 Simple Steps

>PHP cURL to upload video to azure blob storage

>PHP Error Solved: htaccess problem with an empty string in URL

>Plugins and Presets for Vuejs project

>Python Error Solved: load_associated_files do not load a txt file

>Python Error Solved: pg_config executable not found

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Setting up a Cloud Composer environment: Step-by-step guide


Ritu Singh

Ritu Singh

Submit
0 Answers