简体   繁体   中英

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

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

You're passing the user as a kwarg, but you're not assigning it to anything.

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.

What you want to do is assign value to self.user in the constructor before using it. Therefore, try changing your constructor to:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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