gpt4 book ai didi

python - Django 属性错误 : Form object has no attribute '_errors'

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:59 25 4
gpt4 key购买 nike

我正在覆盖我的表单中的 init 方法,现在返回错误“TransactionForm”对象没有属性“_errors”

我希望它能工作,因为我在我的 init 中包含了 super,但也许我不明白如何正确使用它。一个解释将不胜感激。我需要做什么才能使 form.errors 正常工作?

完整的回溯

Traceback:

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 136. return render(request, 'myportfolio/add_transaction.html', {'form': form})

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

File "C:\Program Files\Python36\lib\site-packages\django\template\loader.py" in render_to_string 62. return template.render(context, request)

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

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render 175. return self._render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in _render 167. return self.nodelist.render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render 943. bit = node.render_annotated(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render_annotated 910. return self.render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\loader_tags.py" in render 155. return compiled_parent._render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in _render 167. return self.nodelist.render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render 943. bit = node.render_annotated(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render_annotated 910. return self.render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\loader_tags.py" in render 155. return compiled_parent._render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in _render 167. return self.nodelist.render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render 943. bit = node.render_annotated(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render_annotated 910. return self.render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\loader_tags.py" in render 67. result = block.nodelist.render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render 943. bit = node.render_annotated(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render_annotated 910. return self.render(context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render 999. return render_value_in_context(output, context)

File "C:\Program Files\Python36\lib\site-packages\django\template\base.py" in render_value_in_context 978. value = str(value)

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

File "C:\Program Files\Python36\lib\site-packages\django\forms\forms.py" in str 136. return self.as_table()

File "C:\Program Files\Python36\lib\site-packages\django\forms\forms.py" in as_table 279. errors_on_separate_row=False)

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

File "C:\Program Files\Python36\lib\site-packages\django\forms\forms.py" in non_field_errors 305. return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield'))

File "C:\Program Files\Python36\lib\site-packages\django\forms\forms.py" in errors 173. if self._errors is None:

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

表格

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, coin_price = None, user = None, *args, **kwargs):

if user:
self.user = user
qs_coin = Portfolio.objects.filter(user = self.user).values('coin').distinct()
super(TransactionForm, self).__init__(self.user, *args, **kwargs)
self.fields['coin'].queryset = qs_coin

if coin_price:
self.coin_price = coin_price
super(TransactionForm, self).__init__(self.user, self.coin_price, *args, **kwargs)
self.fields['price'] = self.coin_price

浏览量

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.user
obj.save()
return HttpResponseRedirect('/myportfolio/')
else:
print(form.errors)

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

最佳答案

如果未提供 coin_priceuser,则不会调用表单的父类(super class) __init__ 方法。这就是为什么没有创建 _errors 等表单属性的原因。您需要像这样重写表单的 __init__:

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

if coin_price:
self.coin_price = coin_price
self.fields['price'] = self.coin_price

使 super.__init__() 在任何情况下都被调用。

关于python - Django 属性错误 : Form object has no attribute '_errors' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50407569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com