I'm trying to override clean() method of the form to check, whether attribute IBAN is unique or not. Each user can have IBAN. For some reason, django says that form has no attribute IBAN which isn't true. As you can see it's a first attribute of the form.
Do you know what's problem?
class TranslatorRegistrationForm(forms.Form):
IBAN = forms.CharField(max_length=40, required=True)
first_name = forms.CharField(max_length=40, required=True)
last_name = forms.CharField(max_length=40, required=True)
languages = forms.ModelMultipleChoiceField(Language.objects.all(), label='Languages: ',
help_text="You can choose from UNKNOWN levels, to gain level, you will be tested")
def __init__(self,user,*args, **kwargs):
super(TranslatorRegistrationForm, self).__init__(*args, **kwargs)
self.user = user
def clean(self):
cleaned_data = super(TranslatorRegistrationForm, self).clean()
if len(UserProfile.objects.filter(IBAN=self.IBAN).exclude(user=self.user))>0:
raise ValidationError
return cleaned_data
TRACEBACK:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/register-as-translator/
Django Version: 1.8.12
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'SolutionsForLanguagesApp',
'crispy_forms',
'super_inlines',
'django_tables2',
'language_tests',
'smart_selects',
'django_extensions',
'constance',
'constance.backends.database',
'nested_inline')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.locale.LocaleMiddleware')
Traceback:
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\SolutionsForLanguagesApp\views.py" in register_as_translator
110. if register_as_translator_form.is_valid():
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in is_valid
184. return self.is_bound and not self.errors
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in errors
176. self.full_clean()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in full_clean
393. self._clean_form()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\venv\lib\site-packages\django\forms\forms.py" in _clean_form
417. cleaned_data = self.clean()
File "C:\Users\Milano\PycharmProjects\FutileStudio\SolutionsForLanguages_2\SolutionsForLanguagesApp\forms.py" in clean
116. if len(UserProfile.objects.filter(IBAN=self.IBAN).exclude(user=self.user))>0:
Exception Type: AttributeError at /register-as-translator/
Exception Value: 'TranslatorRegistrationForm' object has no attribute 'IBAN'
Since you are validating the value of a single field iban, it would be better to define a clean_iban method instead of clean:
def clean_iban(self):
iban = self.cleaned_data['IBAN']
# Note using exists() is more efficient and pythonic than 'len() > 0'
if UserProfile.objects.filter(IBAN=iban).exists():
raise ValidationError('Invalid IBAN')
return iban
The clean method is meant for validating fields that depend on each other. If you override clean, you can't assume that a value will be in cleaned_data.
def clean(self):
cleaned_data = super(TranslatorRegistrationForm, self).clean()
if 'iban' in cleaned_data:
iban = cleaned_data['iban']
if len(UserProfile.objects.filter(IBAN=self.IBAN).exclude(user=self.user))>0:
raise ValidationError('Invalid IBAN')
return cleaned_data
Once you've called super(TranslatorRegistrationForm, self).clean(), you should be able to access the value of the IBAN field in cleaned_data['IBAN']. The attribute self.IBAN is a field definition, rather than the field's value.
Related
I have seen a bit of similar threads here in SO but cant seem to solve it. Here is my model:
class Association(models.Model):
'''
For members declared as groups
'''
member=models.ManyToManyField(User,related_name='association_user')
name=models.CharField(max_length=50)
def __str__(self):
return self.name
class Meta:
ordering=('name',)
The many-to-many relationship ended up creating, i think, a table under the hood with the following definitions:
association_id
user_id
I don't know if it is refering to the that field association nor how to add values to that table from my views.
my forms.py
class NewAssocationForm(forms.ModelForm):
'''
this is used to create a new form
'''
class Meta:
model=Association
fields=['name',]
labels=['Assocation Name'),]
and my views.py:
#login_required
def make_new(request):
'''
Register a new association or corporate
'''
if request.method=='POST':
form=NewAssocationForm(request.POST or None)
if form.is_valid():
new_association=form.save(commit=False)
new_association.member=request.user
new_association.save()
#add a message then redirect
return HttpResponseRedirect('/corporates/done/)
else:
form=NewAssocationForm(request.POST or None)
else:
form=NewAssocationForm(request.POST or None)
return render(request, "association_new.html", locals())
I don't have a field named association in my model at all. I doubt it is constraint erorr cos i can insert records to the table from the shell without any issues.
Here is my traceback.
Environment:
Request Method: POST
Request URL: http://localhost:9000/corporates/new/
Django Version: 1.10
Python Version: 3.4.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'widget_tweaks',
'welcome',
'members',
'corporates']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\pyworks\agrigo\env\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "D:\pyworks\agrigo\env\agrigo\corporates\views.py" in make_new
78. new_association.member=request.user
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
499. manager = self.__get__(instance)
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__
476. return self.related_manager_cls(instance)
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __init__
783. (instance, self.source_field_name))
Exception Type: ValueError at /corporates/new/
Exception Value: "<Association: North Side>" needs to have a value for field "association" before this many-to-many relationship can be used.
Thanks for anyone who went through the long post. Apparently, I shouldn't specify user. So, deleting the line:
new_association.member=request.user
solved the issue. Makes sense; dumb me.
I am using Django User model for one of the select field.
However i am not able to pass only users linked to a commmon organisation/company.
I have a onetoone profile linking for each user. This one to onetoone model is again linked to organisation model.
Now need a form where select field should have users linked to organisation model.
Here is my form.py:
class taskaddform(forms.ModelForm):
def __init__(self,user, *args, **kwargs):
self.user = kwargs.pop('user', None)
self.request = kwargs.pop('request', None)
super(taskaddform, self).__init__(*args, **kwargs)
self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
class Meta:
model=tasktable
fields=('task','assigned_to','discription','documents',)
views.py:
#login_required
def taskadd(request):
if request.method=='POST':
form=taskaddform(request.POST,request.FILES,request.user)
if form.is_valid():
new_form=form.save(commit=False)
new_form.created_by=request.user
new_form.company=request.user.company.entity
new_form.save()
return HttpResponseRedirect(reverse('taskadd'),messages.add_message(request, messages.SUCCESS,'Task added succesfully.'))
else:
form=taskaddform(request.user)
return render(request,'taskadd.html',{'form':form})
Error Log:
Request Method: GET
Request URL: http://127.0.0.1:8000/task/taskadd/
Django Version: 1.10
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'user'
traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/task/taskadd/
Django Version: 1.10
Python Version: 2.7.10
Installed Applications:
('invoice',
'support',
'task',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'widget_tweaks')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/Users/pulkitsharma/Documents/workspace1/tiktant/task/views.py" in taskadd
38. form=taskaddform(request.user)
File "/Users/pulkitsharma/Documents/workspace1/tiktant/task/forms.py" in __init__
11. self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
Exception Type: AttributeError at /task/taskadd/
Exception Value: 'NoneType' object has no attribute 'user'
Updated views.py.
#login_required
def taskadd(request):
if request.method=='POST':
form=taskaddform(request, request.POST,request.FILES,request.user)
if form.is_valid():
new_form=form.save(commit=False)
new_form.created_by=request.user
new_form.company=request.user.company.entity
new_form.save()
return HttpResponseRedirect(reverse('taskadd'),messages.add_message(request, messages.SUCCESS,'Task added succesfully.'))
else:
form=taskaddform(request)
return render(request,'taskadd.html',{'form':form})
and in your forms.py --
class taskaddform(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
self.request = request
super(taskaddform, self).__init__(request, *args, **kwargs)
self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
I am trying to build a view with 2 models using inlinefactory.
Models.py
class serviceinvoice(models.Model):
user=models.ForeignKey(User,related_name='invoice')
invoice_number=models.PositiveIntegerField()
#invoice_no = models.CharField(max_length = 500, default = increment_invoice_number, null = True, blank = True)
invoice_date = models.DateField()
invoice_receivable=models.ForeignKey(Receivables,null=True)
total_amount=models.DecimalField(decimal_places=2,max_digits=20)
total_amountwithtax=models.DecimalField(decimal_places=2,max_digits=20)
def __str__(self):
return self.invoice_number
class serviceinvoiceitems(models.Model):
user=models.ForeignKey(settings.AUTH_USER_MODEL,related_name='serviceinvoiceitems')
invoice_number=models.ForeignKey(serviceinvoice)
Product=models.CharField(max_length=1000,null=True)
UOM=models.CharField(max_length=100,null=True)
Quantity=models.FloatField(null=True)
Rate=models.FloatField(null=True)
Tax_rate=models.FloatField(null=True)
def __str__(self):
return self.invoice_number
forms.py
createinvoiceformset = inlineformset_factory(serviceinvoice, serviceinvoiceitems,fields='__all__')
class createinvoice(forms.ModelForm):
class Meta:
model = serviceinvoice
exclude = ('user',)
widgets = {
'invoice_date': forms.DateInput(attrs={'class':'datepicker'}),
}
views.py
#login_required
def createinvoice(request):
if request.method == 'POST':
inv_form=createinvoice(data=request.POST)
if inv_form.is_valid():
new_form=inv_form.save(commit=False)
new_formset=createinvoiceformset(request.POST,instance=new_form)
if new_formset.is_valid():
new_form.save()
new_formset.save()
return HttpResponse('Invoice created')
else:
inv_form=createinvoice()
new_formset=createinvoiceformset(instance=serviceinvoice())
inv_form.fields["invoice_receivable"].queryset=Receivables.objects.filter(user=request.user)
return render(request,'account/createinvoice.html',{'inv_form':inv_form,'new_formset':new_formset})
This is rendered in template with following error.
_wrapped_view() missing 1 required positional argument: 'request'
Traceback
Environment:
Request Method: GET
Request URL: http://localhost:8000/invoice/createinvoice/
Django Version: 1.8.9
Python Version: 3.4.0
Installed Applications:
('invoice',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "D:\pythonspace\tiktant\invoice\views.py" in createinvoice
106. inv_form=createinvoice(instance=request)
Exception Type: TypeError at /invoice/createinvoice/
Exception Value: _wrapped_view() missing 1 required positional argument: 'request'
Your view name createinvoice clashes with your form createinvoice. They should be different.
Your code would be much clearer if you used underscores for function names (e.g. def create_invoice(...)), and CamelCase for class names (e.g. class CreateInvoice(...), CreateInvoiceFormSet, ...)
Ahoy Mateys!
got a simple model with a simpel form here:
class Hardware(models.Model):
type_name = models.CharField(max_length=60)
def __unicode__(self):
return self.type_name
class HardwareForm(ModelForm):
class Meta:
model = Hardware
fields = ['type_name']
and this is used by my simple views function:
def createHardware(request):
if request.method == 'POST':
form = HardwareForm('request.POST')
if form.is_valid():
new_hardware = form.save()
return render_to_response('administration/overview.html')
else:
form = HardwareForm()
return render_to_response('administration/create_hardware.html', {
'form': form, }, context_instance = RequestContext(request))
this is the Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/ticket/createHardware/
Django Version: 1.6.6
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ticket')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\bachi_000\workspace\Help\src\ticket\views.py" in createHardware
155. if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
129. return self.is_bound and not bool(self.errors)
File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
121. self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
273. self._clean_fields()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
282. value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Python27\lib\site-packages\django\forms\widgets.py" in value_from_datadict
207. return data.get(name, None)
Exception Type: AttributeError at /ticket/createHardware/
Exception Value: 'str' object has no attribute 'get'
so i got several forms with much more data in it, and there is no problem to pass an empty form to the html page, fill it out and POST them back to the function to get the data in the form. run is_valid() and pass the data to a new instance of the model (to add some more data to it)
why do i get here this error?
You need to be passing in a dictionary to your HardwareForm, not a string.
Change in your views.py
form = HardwareForm('request.POST')
to:
form = HardwareForm(request.POST)
I would like to redirect the success_url to the same form after the form was submitted and valid. Online I found a description of a solution, however this solution and my other code option generate the same error message.
Exception Value: 'NoneType' object has no attribute 'find'
urls.py
url(r'^pictures/(?P<id>\d+)/$', PictureUpload.as_view(), name='picture_upload'),
...
1st views.py option
copies the existing link path
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = lambda self: self.request.path
2nd views.py option
recreates the link path based on the reverse url plus the id
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = reverse('picture_upload',
kwargs={'id': self.kwargs.get('id', None)})
Both options end up in the same traceback.
Request Method: POST
Request URL: http://127.0.0.1:8000/pictures/2/
Django Version: 1.5.1
Python Version: 2.7.1
Installed Applications:
('django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'picture',
'debug_toolbar')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in post
165. return self.form_valid(form)
File "/Users/Development/project/apps/picture/picture_views.py" in form_valid
180. return super(PictureUpload, self).form_valid(form)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in form_valid
65. return HttpResponseRedirect(self.get_success_url())
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/http/response.py" in __init__
388. parsed = urlparse(redirect_to)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlparse
134. tuple = urlsplit(url, scheme, allow_fragments)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlsplit
173. i = url.find(':')
Exception Type: AttributeError at /pictures/2/
Exception Value: 'NoneType' object has no attribute 'find'
It looks like neither of your get_success_url implementations actually return the URL, so assuming that's not just a cut-and-paste error you're passing None to the HttpResponseRedirect.