简体   繁体   English

Django:尽管将user传递为kwarg,但是Form对象没有属性'user'?

[英]Django: Form object has no attribute 'user' despite passing user as kwarg?

I'm getting this error when I instantiate the TransactionForm in my view. 我在视图中实例化TransactionForm时遇到此错误。 The traceback is below. 追溯如下。

I would expect this to work because I'm passing "user" as a keyword argument when I call the Form instance, so I'm not sure what the problem is here? 我希望这能起作用,因为在调用Form实例时我将“ user”作为关键字参数传递,所以我不确定这是什么问题?

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 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 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

You're passing the user as a kwarg, but you're not assigning it to anything. 您将用户传递为kwarg,但未将其分配给任何用户。

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

In your TrasactionForm.__init__ method you are referencing self.user before self.user has been even initialized. TrasactionForm.__init__方法中,您甚至在self.user尚未初始化之前就引用了self.user

What you want to do is assign value to self.user in the constructor before using it. 您要做的是在使用构造函数之前将值分配给self.user Therefore, try changing your constructor to: 因此,尝试将构造函数更改为:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM