简体   繁体   中英

how to make a dropdown selection in a CreateView field- Django

i'm adding a new field(location) to my PostCreateView

and I want to be able to select that field if it's already in the database. (like idk New York)

it does show up but obv its not a dropdown.

views.py

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content', 'location'] 
    success_url = '/'

    

models.py

class Location(models.Model):
    location = models.CharField(max_length=100)


    def __str__(self):
        return self.location


    def get_absolute_url(self):
        return reverse('home')

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    location = models.CharField(max_length=100, default="")


    def total_likes(self):
        return self.likes.count()


    def __str__(self):
        return self.title


    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})



I've tried to add this

widgets= {
        'location': forms.Select(attrs={'class': 'form-control'})
    }

right underneath to my class PostCreateView, but I guess it doesn't work since I don't use forms.py and instead I use class PostCreateView inside of views.py

In your models.py file, the location component should be a ForeignKey . In this case, your model should look like so:

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    location = models.ForeignKey(Location, on_delete=models.CASCADE)

When you add that field to your form or defined fields from your CreateView it will appear as a dropdown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM