Django AttributeError: Form object has no attribute _errors

2024/10/15 22:24:10

I'm overriding the init method in my form andthis is now returning an error 'TransactionForm' object has no attribute '_errors'.

I would expect this to work because I've included super in my init, however perhaps I don't understand how to use this correctly. An explanation would be appreciated. What do I need to do to get form.errors working?

Full traceback

Traceback:

File "C:\ProgramFiles\Python36\lib\site-packages\django\core\handlers\exception.py" ininner35. response = get_response(request)

File "C:\ProgramFiles\Python36\lib\site-packages\django\core\handlers\base.py" in_get_response128. response = self.process_exception_by_middleware(e, request)

File "C:\ProgramFiles\Python36\lib\site-packages\django\core\handlers\base.py" in_get_response126. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\py\portfolio-project\myportfolio\views.py" in add_transaction136. return render(request, 'myportfolio/add_transaction.html', {'form': form})

File "C:\Program Files\Python36\lib\site-packages\django\shortcuts.py"in render36. content = loader.render_to_string(template_name, context, request, using=using)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\loader.py" inrender_to_string62. return template.render(context, request)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\backends\django.py"in render61. return self.template.render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" in render175. return self._render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" in _render167. return self.nodelist.render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" in render943. bit = node.render_annotated(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" inrender_annotated910. return self.render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\loader_tags.py" inrender155. return compiled_parent._render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" in _render167. return self.nodelist.render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" in render943. bit = node.render_annotated(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" inrender_annotated910. return self.render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\loader_tags.py" inrender155. return compiled_parent._render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" in _render167. return self.nodelist.render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" in render943. bit = node.render_annotated(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" inrender_annotated910. return self.render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\loader_tags.py" inrender67. result = block.nodelist.render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" in render943. bit = node.render_annotated(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" inrender_annotated910. return self.render(context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" in render999. return render_value_in_context(output, context)

File "C:\ProgramFiles\Python36\lib\site-packages\django\template\base.py" inrender_value_in_context978. value = str(value)

File "C:\ProgramFiles\Python36\lib\site-packages\django\utils\html.py" in 371. klass.str = lambda self: mark_safe(klass_str(self))

File "C:\ProgramFiles\Python36\lib\site-packages\django\forms\forms.py" in str136. return self.as_table()

File "C:\ProgramFiles\Python36\lib\site-packages\django\forms\forms.py" in as_table279. errors_on_separate_row=False)

File "C:\ProgramFiles\Python36\lib\site-packages\django\forms\forms.py" in_html_output196. top_errors = self.non_field_errors() # Errors that should be displayed above all fields.

File "C:\ProgramFiles\Python36\lib\site-packages\django\forms\forms.py" innon_field_errors305. return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))

File "C:\ProgramFiles\Python36\lib\site-packages\django\forms\forms.py" in errors173. if self._errors is None:

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

forms

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 = Transactionsfields = {'buysell', 'coin', 'amount', 'trade_price'}def __init__(self, coin_price = None, user = None, *args, **kwargs):if user:self.user = userqs_coin = Portfolio.objects.filter(user = self.user).values('coin').distinct()super(TransactionForm, self).__init__(self.user, *args, **kwargs)self.fields['coin'].queryset = qs_coinif coin_price:self.coin_price = coin_pricesuper(TransactionForm, self).__init__(self.user, self.coin_price, *args, **kwargs)self.fields['price'] = self.coin_price

Views

def add_transaction(request):print(request.method)print("test1")print(request.GET)if request.method == "GET":if request.is_ajax():print("ajax test")data = {'test': "test1"}form = TransactionForm(request.GET, user = request.user, coin_price = GetCoin("Bitcoin").price)return JsonResponse(data)form = TransactionForm()if request.method == "POST":print("test2")form = TransactionForm(request.POST)if form.is_valid():print("test3")obj = form.save(commit = False)obj.user = request.userobj.save()return HttpResponseRedirect('/myportfolio/')else: print(form.errors)return render(request, 'myportfolio/add_transaction.html', {'form': form})
Answer

Form's superclass __init__ method not called if coin_price and user not provided. That's why such form's attributes as _errors was not created. You need to rewrite form's __init__ like this:

def __init__(self, coin_price = None, user = None, *args, **kwargs):super(TransactionForm, self).__init__(*args, **kwargs)if user:self.user = userqs_coin = Portfolio.objects.filter(user = self.user).values('coin').distinct()self.fields['coin'].queryset = qs_coinif coin_price:self.coin_price = coin_priceself.fields['price'] = self.coin_price

To make super.__init__() called in any cases.

https://en.xdnf.cn/q/69231.html

Related Q&A

Add new keys to a dictionary while incrementing existing values

I am processing a CSV file and counting the unique values of column 4. So far I have coded this three ways. One uses "if key in dictionary", the second traps the KeyError and the third uses &…

ImportError: cannot import name aiplatform from google.cloud (unknown location)

I was wondering where that error comes from. The package has to be installed additionally to google.cloud

What does : TypeError: cannot concatenate str and list objects mean?

What does this error mean?TypeError: cannot concatenate str and list objectsHeres part of the code:for j in (90.,52.62263.,26.5651.,10.8123.):if j == 90.:z = (0.)elif j == 52.62263.:z = (0., 72., 144.…

How do I create a fixed-length, mutable array of Python objects in Cython?

I need to have an array of python objects to be used in creating a trie datastructure. I need a structure that will be fixed-length like a tuple and mutable like a list. I dont want to use a list bec…

How to install atari-py in Windows 10? [duplicate]

This question already has answers here:OpenAI Gym Atari on Windows(5 answers)Closed 3 years ago.I tried to install lib pack atari-py, and can not find any clear information, most of them wrote that it …

Using pyplot to create grids of plots

I am new to python and having some difficulties with plotting using pyplot. My goal is to plot a grid of plots in-line (%pylab inline) in Juypter Notebook.I programmed a function plot_CV which plots cr…

matplotlib: deliberately block code execution pending a GUI event

Is there some way that I can get matplotlib to block code execution pending a matplotlib.backend_bases.Event?Ive been working on some classes for interactively drawing lines and polygons inside matplo…

Connecting Keras models / replacing input but keeping layers

This questions is similar to Keras replacing input layer. I have a classifier network and an autoencoder network and I want to use the output of the autoencoder (i.e. encoding + decoding, as a preproce…

PySpark 2.x: Programmatically adding Maven JAR Coordinates to Spark

The following is my PySpark startup snippet, which is pretty reliable (Ive been using it a long time). Today I added the two Maven Coordinates shown in the spark.jars.packages option (effectively "…

Python: How to create simple web pages without a huge framework? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum…