[英]How to filter Django Form dropdown for currently logged-in user (Class Based Views)
I have the two models, Fillup and Car, and the Fillup model has a Foreign key (for recording times you fill up your car with gas, for example), and in the form to create a new Fillup, I want to limit the dropdown for the Car field to only Cars associated with the current user, but right now it's showing all users cars.我有两个模型,Fillup 和 Car,Fillup model 有一个外键(例如,用于记录您为汽车加油的时间),并且在创建新 Fillup 的表单中,我想限制下拉菜单对于 Car 字段,仅显示与当前用户关联的 Cars,但现在它显示所有用户的汽车。 I've seen a couple solutions that involve passing the request into the form from the view but I can't figure out how to do it using the Class Based Views I currently have set up.
我已经看到了一些解决方案,这些解决方案涉及将请求从视图传递到表单中,但我不知道如何使用我目前设置的基于 Class 的视图来完成它。 Here's my code:
这是我的代码:
models.py模型.py
class Fillup(models.Model):
username = models.ForeignKey(User,on_delete=models.CASCADE)
date = models.DateField(default=date.today)
price_per_gallon = models.FloatField()
trip_distance = models.FloatField()
gallons = models.FloatField()
car = models.ForeignKey('Car',on_delete=models.CASCADE)
@property
def total_sale(self):
return round(self.price_per_gallon*self.gallons, 2)
@property
def mpg(self):
return round(self.trip_distance/self.gallons, 4)
class Car(models.Model):
username = models.ForeignKey(User,on_delete=models.CASCADE)
name = models.CharField(max_length=25)
make = models.CharField(max_length=25)
model = models.CharField(max_length=25)
model_year = models.IntegerField(choices=MODEL_YEARS)
status = models.BooleanField(choices=STATUS)
def __str__(self):
return self.name
views.py视图.py
class FillupListView(ListView):
model = Fillup
context_object_name = 'fillup_list'
ordering = ['-date']
# NOT USING THIS YET
# def get_queryset(self):
# return Fillup.objects.filter(user=self.request.user)
class CarListView(ListView):
model = Car
ordering = ['name']
class NewFillup(LoginRequiredMixin,CreateView):
model = Fillup
fields = ('date', 'price_per_gallon', 'trip_distance', 'gallons', 'car')
redirect_field_name = 'fillup_list'
def form_valid(self, form):
form.instance.username = self.request.user
return super().form_valid(form)
class NewCar(LoginRequiredMixin,CreateView):
model = Car
fields = ('name', 'make', 'model', 'model_year', 'status')
redirect_field_name = 'car_list'
def form_valid(self, form):
form.instance.username = self.request.user
return super().form_valid(form)
forms.py forms.py
class FillupForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(FillupForm,self).__init__(*args, **kwargs)
self.fields['car'].queryset = Car.objects.filter(username=user)
class Meta():
model = Fillup
fields = ('date', 'price_per_gallon', 'trip_distance', 'gallons', 'car')
class CarForm(forms.ModelForm):
class Meta():
model = Car
fields = ('name', 'make', 'model', 'model_year', 'status')
The overwriting of the init method in FillupForm was just one of the things I tried to get this to work, adapted from another Stackoverflow answer, but it didn't seem to have any effect. FillupForm 中的 init 方法的覆盖只是我试图让它工作的事情之一,改编自另一个 Stackoverflow 答案,但它似乎没有任何效果。 Any advice/examples to get this working would be appreciated!
任何使这项工作的建议/示例将不胜感激! And let me know if I should supply any more pieces of my code
让我知道我是否应该提供更多我的代码
I ended up getting my answer to this from r/djangolearning on Reddit.我最终从 Reddit 上的 r/djangolearning 得到了我的答案。
I needed to add the following to both of my CreateViews:我需要将以下内容添加到我的两个 CreateViews 中:
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
They also pointed out that I needed to replace the fields=('blah blah blah') on both CreateViews with form_class=forms.Fillup/Car他们还指出我需要用 form_class=forms.Fillup/Car 替换 CreateViews 上的 fields=('blah blah blah')
I hope this helps someone with the same issue as me!我希望这可以帮助和我有同样问题的人!
You can do something like this in the init method.您可以在init方法中执行类似的操作。
cars = Car.objects.filter(username=user)
self.fields['car'].autocomplete = False
self.fields['car'].queryset = users
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.