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, ...)
Related
I try to create simple SingleObjectMixin class, later i will use it with render_json_response() for providing AJAX data streaming. The main goal is basket for online store. So there is simple test class:
class Test(SingleObjectMixin):
model = GoodsDescription
slug_url_kwarg = 'test_id'
slug_field = 'artikul' # pk field in 'GoodsDescription' table
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return render(request, 'temp_code.html', {'msg':self.object.name})
So the mistake is:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/test%3D5/
Django Version: 1.10.5
Python Version: 2.7.12
Installed Applications:
['alexbase',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'easy_thumbnails']
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 "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/user/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/.local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
Exception Type: TypeError at /admin/test=5/
Exception Value: object() takes no parameters
SingleObjectMixin is, well, a mixin. It's not a full view you can inherit from. You should use DetailView instead.
URL conf string should be right:
url(r'^(?:test=(?P<test_id>\d+))/$', login_required(views.TestAJAXView), name='temp_code'),
Finally, i want to use class like this:
class TestAJAXView(JSONResponseMixin, SingleObjectMixin):
model = GoodsDescription
slug_url_kwarg = 'test_id'
slug_field = 'artikul'
json_dumps_kwargs = {"indent": 2}
def get(self, request, *args, **kwargs):
self.object = self.get_object()
context_dict = {
"category": self.object.category,
"name": self.object.name
}
return self.render_json_response(context_dict)
But exception was raised, so i tried this:
class Test(SingleObjectMixin):
model = GoodsDescription
slug_url_kwarg = 'test_id'
slug_field = 'artikul' # pk field in 'GoodsDescription' table
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return render(request, 'temp_code.html', {'msg':self.object.name})
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.
I want to create bills in my app. I have one extra_bill_form and multible item_forms.
view:
def ExtraBillView(request):
item_form_set = formset_factory(ItemForm, formset=BaseItemFormSet, can_delete=True)
extra_bill_form = ExtraBillForm()
if request.method == 'POST':
item_form_set = BaseItemFormSet(request.POST)
extra_bill_form = ExtraBillForm(request.POST)
if extra_bill_form.is_valid() and item_form_set.is_valid():
al1 = extra_bill_form.cleaned_data.get('adress_line1')
al2 = extra_bill_form.cleaned_data.get('adress_line2')
al3 = extra_bill_form.cleaned_data.get('adress_line3')
al4 = extra_bill_form.cleaned_data.get('adress_line4')
for form in item_form_set:
pass
pdb.set_trace()
else:
extra_bill_form = ExtraBillForm()
item_form_set = formset_factory(ItemForm, formset=BaseItemFormSet, extra=0, max_num=5, min_num=1)
context = {
'extra_bill_form': extra_bill_form,
'item_form_set': item_form_set,
}
return render(request, 'extra_bill.html', context)
form:
class ExtraBillForm(forms.Form):
adress_line1 = forms.CharField(label='Adresszeile 1:', required=True)
adress_line2 = forms.CharField(label='Adresszeile 2:', required=False)
adress_line3 = forms.CharField(label='Adresszeile 3:', required=False)
adress_line4 = forms.CharField(label='Adresszeile 4:', required=False)
class ItemForm(forms.Form):
name = forms.CharField(label='Artikelname:')
ust = forms.IntegerField(label='UST:', initial=20)
price_nto = forms.IntegerField(label='Preis netto:', required=False)
price_brt = forms.IntegerField(label='Preis brutto:', required=False)
class BaseItemFormSet(BaseFormSet):
def clean(self):
if self.price_nto is None:
if self.price_brt is None:
return
if any(self.errors):
return
If I submitt my forms, I get an error:
'BaseItemFormSet' object has no attribute 'absolute_max'
how to solve this problem?
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/calculator/extrabill/
Django Version: 1.9.4
Python Version: 3.5.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_ajax',
'django_bootstrap_dynamic_formsets',
'Bank',
'bootstrap3',
'Building',
'Calculator',
'CounterChange',
'Customer',
'Credit',
'Hackgut',
'Heatingplant',
'Index',
'jquery',
'jquery_ui',
'Measurement',
'Price',
'Rate']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/usr/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/usr/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/klaus/PycharmProjects/waerme/Calculator/views.py" in ExtraBillView
94. if extra_bill_form.is_valid() and item_form_set.is_valid():
File "/usr/lib/python3.5/site-packages/django/forms/formsets.py" in is_valid
316. self.errors
File "/usr/lib/python3.5/site-packages/django/forms/formsets.py" in errors
290. self.full_clean()
File "/usr/lib/python3.5/site-packages/django/forms/formsets.py" in full_clean
337. for i in range(0, self.total_form_count()):
File "/usr/lib/python3.5/site-packages/django/forms/formsets.py" in total_form_count
116. return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max)
Exception Type: AttributeError at /calculator/extrabill/
Exception Value: 'BaseItemFormSet' object has no attribute 'absolute_max'
The formset factory creates the formset class. You should only call formset_factory once. You can do this outside of the view.
ItemFormSet = formset_factory(ItemForm, formset=BaseItemFormSet, extra=0, max_num=5, min_num=1)
Then, in your view, instantiate the ItemFormSet that was created by formset_factory. You shouldn't instantiate BaseItemFormSet.
if request.method == 'POST':
item_form_set = ItemFormSet(request.POST)
...
else:
item_form_set = ItemFormSet() # blank formset for GET request
context = {
'extra_bill_form': extra_bill_form,
'item_form_set': item_form_set,
}
return render(request, 'extra_bill.html', context)
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.