__init __()得到了一个意外的关键字参数' user'当我尝试过滤

时间:2017-08-29 04:31:03

标签: django django-models django-forms django-templates django-views

我想过滤request.user所做的餐馆。关注文档,但当我尝试过滤

时,我不断得到__init__()意外的关键字参数user

forms.py

from .models import Restaurant
from .models import  Item
from django import forms


class LocationCreate(forms.ModelForm):

    class Meta:
        model = Item
        fields = [
            'restaurant'
            'category',
            'food_name'
        ]
    def __init__(self, user=None, *args, **kwargs):
        super(ItemCreate, self).__init__(*args, **kwargs)
        self.fields['restaurant'].queryset = Restaurant.objects.filter(owner=user) 

models.py

class Restaurant(models.Model):
    restaurant_name    = models.CharField(max_length=250)
    restaurant_photo   = models.ImageField(upload_to='roote_image')
    category      = models.ManyToManyField(Category)
    timestamp     = models.DateTimeField(auto_now_add=True, null=True)
    updated       = models.DateTimeField(auto_now=True, null=True)
    owner          = models.ForeignKey(User)

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


class Item(models.Model):
    restaurant= models.ForeignKey(Roote, on_delete=models.CASCADE, null=True)
    food_name = models.CharField(max_length=1000)
    category = models.CharField(max_length=250)
    owner      = models.ForeignKey(User)
    def __str__(self):
        return  self.food_name

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

views.py

class ItemCreate(CreateView):
    model = Item
    fields = ['restaurant','category ', 'food_name ']
    success_url = reverse_lazy('post:index')


    def form_valid(self, form):
        if form.is_valid():
            roote = restaurant.objects.filter(owner =self.request.user)
            instance = form.save(commit=False)
            instance.owner = self.request.user
        return super(ItemCreate, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(ItemCreate, self).get_form_kwargs()
        kwargs['user'] = self.request.user 
        return kwargs

detail.html

{% block body %}

    <div class="col-sm-6 col-sm-offset-3">
        <img src="{{ restaurant.restaurant_photo.url }}" style="width: 250px;" >


        <h1>{{ restaurant.restaurant_name }}</h1>

         {% for item in restaurant.item_set.all %}
             {{ item.food_name }}: {{ item.category}}
             <br>

         {% endfor %}

表单无需过滤器即可运行,但它会引入网站上的每个餐馆实例

完整错误:

return form_class(**self.get_form_kwargs())
TypeError: __init__() got an unexpected keyword argument 'user'

2 个答案:

答案 0 :(得分:3)

您忘了在视图中添加form_class属性

class ItemCreate(CreateView):
    model = Item
    success_url = reverse_lazy('post:index')
    form_class = LocationCreate  # <- here

    def form_valid(self, form):
        if form.is_valid():
            roote = restaurant.objects.filter(owner=self.request.user)
            instance = form.save(commit=False)
            instance.owner = self.request.user
        return super(ItemCreate, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(ItemCreate, self).get_form_kwargs()
        kwargs['user'] = self.request.user 
        return kwargs

答案 1 :(得分:0)

根据docs,这是ModelForm的__init__方法的签名:

def __init__(self, *args, **kwargs)

看到没有user?这是错误消息告诉您的内容。 如果您想要获得用户,请尝试通过self.request.user(或类似的东西,具体取决于您使用的中间件)。

希望有所帮助!