Django:表单对象没有属性' user'尽管用户为kwarg?

时间:2018-05-16 14:11:10

标签: python django

当我在视图中实例化TransactionForm时,我收到此错误。回溯如下。

我希望这会有效,因为我已经过了"用户"当我调用Form实例时作为关键字参数,所以我不确定这里的问题是什么?

File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\py\portfolio-project\myportfolio\views.py" in add_transaction
  122.  form = TransactionForm(user = request.user)

File "C:\py\portfolio-project\myportfolio\forms.py" in __init__
  36.       qs_coin = Coin.objects.get(user = self.user)

Exception Type: AttributeError at /myportfolio/add_transaction/
Exception Value: 'TransactionForm' object has no attribute 'user'

Views.py

def add_transaction(request):
    print(request.method)
    print("test1")

    if request.method == "GET":
        if request.is_ajax():
            print("ajax test")

            data = {
                'test': "test1"
            }

            form = TransactionForm(request.GET, user = request.user, coin_price = GetCoin(str(coin.coin)).price)

            return JsonResponse(data)


    form = TransactionForm(user = request.user)
    if request.method == "POST":
        print("test2")
        form = TransactionForm(request.POST, user = request.user)
        if form.is_valid():
            print("test3")
            obj = form.save(commit = False)
            obj.user = request.user
            obj.save()
            return HttpResponseRedirect('/myportfolio/')
        else: 
            print(form.errors)

    return render(request, 'myportfolio/add_transaction.html', {'form': form})

Forms.py

class TransactionForm(forms.ModelForm):     
    CHOICES = ((1, 'Buy'), (2, 'Sell'),)

    coin = forms.ModelChoiceField(queryset = Coin.objects.all()) 
    buysell = forms.ChoiceField(choices = CHOICES)

    field_order = ['buysell', 'coin', 'amount', 'trade_price']

    class Meta:
        model = Transactions
        fields = {'buysell', 'coin', 'amount', 'trade_price'}

    def __init__(self, *args, **kwargs):
        qs_coin = Coin.objects.get(user = self.user)
        super(TransactionForm, self).__init__(*args, **kwargs)
        self.fields['coin'].queryset = qs_coin
        self.fields['price'].queryset = self.coin_price

2 个答案:

答案 0 :(得分:2)

您将用户作为kwarg传递,但您并未将其分配给任何内容。

def __init__(self, *args, **kwargs):
    self.user = kwargs.pop('user')

答案 1 :(得分:2)

在您的TrasactionForm.__init__方法中,在self.user被初始化之前,您引用self.user

您要做的是在使用它之前在构造函数中为self.user赋值。因此,请尝试将构造函数更改为:

class TransactionForm(forms.ModelForm):     
    # ... 

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        # rest of the constructor...