简体   繁体   English

Django - 按当前登录用户的车辆过滤帖子表单选项

[英]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.

相关问题 如何过滤当前登录用户的 Django 表单下拉列表(基于类的视图) - How to filter Django Form dropdown for currently logged-in user (Class Based Views) Django:过滤当前登录用户的 ListView(多多多场) - Django: Filter ListView on currently logged-in user (manytomanyfield) 在 Django 中,我如何知道当前登录的用户? - In Django, how do I know the currently logged-in user? 根据登录用户过滤Django管理控制台行 - Filtering Django admin console rows based on the logged-in user 根据当前登录的用户自定义django表单 - Customizing django form based on currently logged in user django-以以下形式加载当前登录的用户信息 - django - load currently logged in user information in the form 在 Django 模板中显示当前登录用户喜欢的所有用户配置文件(在 ManytoMany 字段下) - Display all User profiles, in Django template, liked by the currently logged-in User (under ManytoMany field) 按当前登录的用户过滤模型选择字段 - filtering modelchoicefield by currently logged in user 过滤Django管理员更改列表以根据登录用户显示特定行 - Filtering Django admin changelist to show specific rows based on the logged-in user 如何获取Django中当前登录用户的用户id? - How to get the currently logged in user's user id in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM