[英]Django - Filtering Post Form option by currently logged-in User's Vehicle
I'm a django newbie and i'm making a form where a User can make a Post and pick one of his Vehicles for the Post.我是一个 django 新手,我正在制作一个表格,用户可以在其中发布帖子并选择他的一辆车作为帖子。 The Vehicle and the Post models are created like so:
Vehicle 和 Post 模型是这样创建的:
*blog/models.py*
class Post(models.Model):
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, null=True)
def get_absolute_url(self):
return reverse('post-detail', kwargs ={'pk': self.pk} )
*vehicles/models.py*
class Vehicle(models.Model)*:
TESLA = 'TESLA'
MAZDA = 'MAZDA'
VOLVO = 'VOLVO'
VEHICLE_CHOICES = (
(TESLA, "Tesla"),
(MAZDA, "Mazda"),
(VOLVO, "Volvo"),
)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
model = models.CharField(max_length=9,
choices=VEHICLE_CHOICES,
default=TESLA)
def __str__(self):
return self.model
My blog views:我的博客观点:
*blog/views.py*
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = [ 'vehicle']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
I would like to filter the vehicles so that only the current logged in User's vehicles show up in the form, i've tried a variety of different solutions but I seem to be going around in circles, if you could help me out that would be awesome.我想过滤车辆,以便只有当前登录用户的车辆显示在表格中,我尝试了各种不同的解决方案,但我似乎在兜圈子,如果你能帮我解决问题惊人的。 Thanks!
谢谢!
Since you are using createview, you can create a form in forms.py.由于使用的是createview,所以可以在forms.py中创建表单。 First you have to send the logged in user to the form, then in the form, pop the user from kwargs and use it to filter the vehicles.
首先,您必须将登录用户发送到表单,然后在表单中,从 kwargs 弹出用户并使用它来过滤车辆。
views.py视图.py
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
form_class = PostForm
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['vehicle']
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super().__init__(*args, **kwargs)
self.fields['vehicle'].queryset = Vehicle.objects.filter(owner=user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.