简体   繁体   English

如何在 CreateView 字段中进行下拉选择 - Django

[英]how to make a dropdown selection in a CreateView field- Django

i'm adding a new field(location) to my PostCreateView我正在向我的 PostCreateView 添加一个新字段(位置)

and I want to be able to select that field if it's already in the database.如果它已经在数据库中,我希望能够 select 该字段。 (like idk New York) (如 idk 纽约)

it does show up but obv its not a dropdown.它确实出现了,但它不是下拉列表。

views.py视图.py

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

    

models.py模型.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就在我的 class PostCreateView 的正下方,但我想它不起作用,因为我不使用 forms.py 而是在 views.py 中使用 class PostCreateView

In your models.py file, the location component should be a ForeignKey .在您的models.py文件中,位置组件应该是ForeignKey In this case, your model should look like so:在这种情况下,您的 model 应该如下所示:

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.当您将该字段添加到表单或从CreateView定义的字段时,它将显示为下拉列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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