This code can't possibly work at all, because you override the __init__
method of the form so that a) you only accept a request
argument - and not any of the other things a form is expecting, like data
or initial
- and b) you never call the superclass init method to initialise the things the rest of the form code expects. You need to preserve the signature and call super.
def __init__(self, * args, ** kwargs):
request = kwargs.pop('request')
self.user = request.user
super(InterestsForm, self).__init__( * args, ** kwargs)
I'm overriding the init method in my form anycodings_django andthis is now returning an error anycodings_django 'TransactionForm' object has no attribute anycodings_django '_errors'. ,Exception Type: AttributeError at anycodings_django /myportfolio/add_transaction/ Exception anycodings_django Value: 'TransactionForm' object has no anycodings_django attribute '_errors',Form's superclass __init__ method not anycodings_django called if coin_price and user not anycodings_django provided. That's why such form's anycodings_django attributes as _errors was not created. anycodings_django You need to rewrite form's __init__ like anycodings_django this:,File "C:\Program anycodings_django Files\Python36\lib\site-packages\django\forms\forms.py" anycodings_django in str 136. return anycodings_django self.as_table()
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 = 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
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.user
obj.save()
return HttpResponseRedirect('/myportfolio/')
else:
print(form.errors)
return render(request, 'myportfolio/add_transaction.html', {
'form': form
})
Form's superclass __init__ method not anycodings_django called if coin_price and user not anycodings_django provided. That's why such form's anycodings_django attributes as _errors was not created. anycodings_django You need to rewrite form's __init__ like anycodings_django this:
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
Now this code works fine when field1 does not have unique=True set but not when field1 has unique=True property set. When the unique property is set then the form.is_valid() fails. It gives an AttributeError. 'BaseModel' object has no attribute '_default_manager'. , The moment I remove unique=True from my field it works perfectly fine. Just a caveat here. I am creating MyModel object dynamically creating the object by loading the class dynamically using the approach described here. http://stackoverflow.com/a/547867/161628 , I have an abstract model BaseModel having a field with unique=True. BaseModel obviously has abstract=True. Now I create a MyModel which inherits from BaseModel. , So are you saying ModelForm with an abstract model is not supported? I can load it dynamically but it looks cleaner this way.
Now I have a view that tries to create a new entry in MyModel with data in post request.
def add_new(request, id) { myModel = MyModel() # I am actually creating MyModel dynamically but that should not matter if request.method == 'POST': form = MyModelForm(request.POST) if form.is_valid(): mymodel.field1 = form.cleaned_data['field1'] mymodel.field2 = form.cleaned_data['field3'] mymodel.save() return render_to_response("mytemplate.html", { 'form': form }, RequestContext(request)) else: pass # return some error here }
My concern is that it fails with the unique field only with the following stack trace:
"AttributeError at /create_new type object 'BaseModel' has no attribute '_default_manager' Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, * callback_args, ** callback_kwargs) File "django_bug_19271/testproj/testproj/views.py" in create_new 33. if form.is_valid(): File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in is_valid 124. return self.is_bound and not bool(self.errors) File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in _get_errors 115. self.full_clean() File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in full_clean 272. self._post_clean() File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in _post_clean 338. self.validate_unique() File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in validate_unique 347. self.instance.validate_unique(exclude = exclude) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in validate_unique 633. errors = self._perform_unique_checks(unique_checks) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in _perform_unique_checks 717. qs = model_class._default_manager.filter( ** lookup_kwargs) Exception Type: AttributeError at / create_new Exception Value: type object 'BaseModel' has no attribute '_default_manager' Request information: GET: No GET data POST: csrfmiddlewaretoken = u '**********' my_id = u '1' name = u 'Rohit' FILES: No FILES data COOKIES: csrftoken = '****'
Django AttributeError: Form object has no attribute '_errors',Django error: AttributeError at 'Manager' object has no attribute 'create_user',Django AttributeError 'ModelFormOptions' object has no attribute 'concrete_fields',django form error : Caught AttributeError while rendering: 'NoneType' object has no attribute 'label'
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 = 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