Here is my code:
In forms.py
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ("title","business_partner","transaction")
widgets = {
'transaction': forms.NumberInput()
}
In views.py
def uploadpdf(request,pk):
project_form = ProjectForm(request.POST)
if project_form.is_valid() and request.FILES:
project_form.instance.user = request.user
project = Project.objects.get(id=pk)
project.title = project_form['title']
project.business_partner = project_form['business_partner']
project.transaction = project_form['transaction']
project.save()
project = Project.objects.get(id=pk)
file_path = None
for file in request.FILES:
file = request.FILES[file]
pdf_file = PDFFile(file=file, filename=file.name)
pdf_file.project = project
pdf_file.save()
if PRODUCTION:
file_path = HOST_NAME +'/'+ str(pdf_file.file)
else:
file_path = HOST_NAME +'/media/'+ str(pdf_file.file)
resp = HttpResponse(f'{{"message": "Uploaded successfully...", "id": "{project.id}","url":"{file_path}","title": "{project.title}"}}')
resp.status_code = 200
resp.content_type = "application/json"
return resp
else:
return reverse("dashboard:homepage")
When I run this, it says like "TypeError: Field 'transaction' expected a number but got <django.forms.boundfield.BoundField object at 0x000001A803935250>."
Looking forward to hearing a good solution.
You want to use the cleaned_data attribute of the form instead of the field itself like so:
project.transaction = project_form.cleaned_data['transaction']
Edit: Note that you should have to do the same for the other fields.
Related
The questions is not actual
How can I make links from field author for TabularInline? For now I implement this (source: https://stackoverflow.com/a/10011307/9112151):
class Post(models.Model):
title = models.CharField(max_lenght=100)
author = models.ForeignKey('User', on_delete=models.CASCADE)
def add_link_field(target_model = None, field = '', link_text = unicode):
def add_link(cls):
reverse_name = target_model or cls.model.__name__.lower()
def link(self, instance):
app_name = instance._meta.app_label
reverse_path = "admin:%s_%s_change" % (app_name, reverse_name)
link_obj = getattr(instance, field, None) or instance
url = reverse(reverse_path, args = (link_obj.id,))
return mark_safe("<a href='%s'>%s</a>" % (url, link_text(link_obj)))
link.allow_tags = True
link.short_description = reverse_name + ' link'
cls.link = link
cls.readonly_fields = list(getattr(cls, 'readonly_fields', [])) + ['link']
return cls
return add_link
#add_link_field('author')
class PostInline(admin.TabularInline):
model = Post
Maybe there is built-in decision?
Set show_change_link = True on your inline to display a link to the admin change form for an inline object
class PostInline(admin.TabularInline):
model = Post
show_change_link = True
How to add field value manually from view?
model.py
class Connect(models.Model):
username = models.CharField(max_length=255)
password = models.CharField(max_length=255,null=True, blank=True)
conft = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return unicode(self.username)
form.py
class NacmForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput,required = False)
conft = forms.Textarea()
class Meta:
model = Connect
fields = ['username', 'password','conft']
labels = {'conft':_('Config'),}
view.py
class config_static(View):
def post(self, request, *args, **kwargs):
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
userValue = formm['username'].value()
passValue = formm['password'].value()
if ipform.is_valid() and formm.is_valid():
simpanForm = formm.save()
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
vendor = form.cleaned_data.get('vendor')
.......
//some code//
.......
simpanIp = form.save(commit=False)
simpanIp.connect_id = simpanForm
simpanIp.save()
simpanForm.save()
.........
//some code//
i want to set "conft" value manually, maybe like
configuration = "some config"
conft = configuration
i already tried
configuration = "some config"
NacmForm(initial={'conft': configuration })
or
formm.fields['conft'].initial = configuration
or
formm = NacmForm(request.POST, initial={"conft": configuration })
when i use that code above, the value isnt save to database, then i tried this
Connect.objects.create(conft=configuration)
its save to database but not in same row
formm.cleaned_data returns dictionary. So, you can add/update/remove keys manually. initial={} This is for rendering purposes (Which adds in html forms initial values value="something"). As far as i understand you want to modify incoming data when HTTP POST is made. Try like this.
class config_static(View):
def post(self, request, *args, **kwargs):
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
userValue = formm['username'].value()
passValue = formm['password'].value()
if ipform.is_valid() and formm.is_valid():
# If both form is valid
formm.cleaned_data['conft'] = '<new_value>' # + this is added logic
simpanForm = formm.save()
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
vendor = form.cleaned_data.get('vendor')
.......
//some code//
.......
simpanIp = form.save(commit=False)
simpanIp.connect_id = simpanForm
simpanIp.save()
simpanForm.save()
.........
//some code//
forms.py
class NacmForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput,required = False)
# conft = forms.Textarea()
class Meta:
model = Connect
fields = ['username', 'password','conft']
labels = {'conft':_('Config'),}
Hope, it helps you.
so after googling, i just add this line
class config_static(View):
def post(self, request, *args, **kwargs):
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
userValue = formm['username'].value()
passValue = formm['password'].value()
if ipform.is_valid() and formm.is_valid():
# If both form is valid
simpanForm = formm.save()
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
vendor = form.cleaned_data.get('vendor')
.......
//some code//
.......
simpanForm.conft = "ip route configuration" # i add this
simpanIp = form.save(commit=False)
simpanIp.connect_id = simpanForm
simpanIp.save()
simpanForm.save()
.........
//some code//
in view.py:
#require_POST
#csrf_exempt
def ipn(request):
transactions_logger = logging.getLogger("django")
processor = Ipn(request.POST, logger=transactions_logger)
verification_success = processor.verify_ipn()
encoding = request.POST.get('ok_charset', None)
data = QueryDict(request.body, encoding=encoding)
if verification_success:
form = OkpayIpnForm(data)
if form.is_valid():
print("ALL FINE!!")
form.save()
return HttpResponse("")
In forms.py:
class OkpayIpnForm(forms.ModelForm):
class Meta:
model = OkpayIpn
exclude = []
Code for IPN Checkprocessor = Ipn(request.POST, logger=transactions_logger:
class Ipn(object):
OKPAY_VERIFICATION_URL = 'https://checkout.okpay.com/ipn-verify'
OKPAY_IPN_INVALID = b'INVALID'
OKPAY_IPN_VERIFIED = b'VERIFIED'
OKPAY_IPN_TEST = b'TEST'
OKPAY_STATUS_COMPLETED = 'completed'
__verification_result = False
def __init__(self, request_data, logger):
if 'ok_verify' in request_data:
raise Exception("ok_verify must not be present in initial request data for {}".format(
self.__class__.__name__
))
self._request_data = request_data
self.logger = logger
return
def verify_ipn(self):
self.__verification_result = False
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
verify_request_payload = {
'ok_verify': 'true',
}
verify_request_payload.update(self._request_data)
resp = requests.post(self.OKPAY_VERIFICATION_URL, data=verify_request_payload, headers=headers)
if resp.content == self.OKPAY_IPN_VERIFIED or resp.content == self.OKPAY_IPN_TEST:
self.__verification_result = True
# if resp.content == self.OKPAY_IPN_VERIFIED: # anyway disable test on production.
# self.__verification_result = True
return self.__verification_result
All is ok, I revice IPN and validate it, then I try to validate form and save it to Database.
But form doesn't pass validation and doesn't save to database.
Thank You for help
Problem was that 1 CharField of Model for saving IPN has maxlength=20, but recieved 40 symbols.
Thx jape he advised to add in form validation else statement and print form.errors
the error of of form validation was :
<li>ok_item_1_type<ul class="errorlist"><li>Ensure this value has at most 20 characters (it has 40).</li></ul></li>
Is it possible for an inlineformset_factory to take in a ModelForm as well as a model. When I try to run this I get an error message 'NoneType' object is not iterable.
Please help, I've spent an entire day trying to figure this out. Thanks.
Code:
Model.py
class FilterForm(ModelForm):
firstFilter = forms.BooleanField(label='First Filter', initial=False, required=False)
class Meta:
model = Filter
exclude = ('order')
class Controller(models.Model):
protocol = models.CharField('Protocol',max_length=64, choices=PROTOCOLS, default='http')
server = models.CharField('Server', max_length=64, choices=SERVERS, default='127.0.0.1')
name = models.CharField('Name', max_length=64)
def __unicode__(self):
return self.protocol + '://' + self.server + '/' + self.name
view.py
def controller_details(request, object_id):
controller = Controller.objects.get(pk=object_id)
controllerURI = controller.protocol + '://' + controller.server + '/' + controller.name
FilterFormSet = inlineformset_factory(Controller, FilterForm, extra=5)
if request.method == 'POST':
formset = FilterFormSet(request.POST, request.FILES, instance=controller)
if formset.is_valid():
filters = []
# Save all the filters into a list
forms = formset.cleaned_data
for form in forms:
if form:
protocol = form['protocol']
server = form['server']
name = form['name']
targetURI = form['targetURI']
filterType = form['filterType']
firstFilter = form['firstFilter']
if firstFilter == True:
aFilter = Filter(controller=controller, protocol=protocol, server=server, name=name, targetURI=targetURI, filterType=filterType, order=0)
else:
aFilter = Filter(controller=controller, protocol=protocol, server=server, name=name, targetURI=targetURI, filterType=filterType, order=-1)
filters.append(aFilter)
# Find the first filter in the list of filters
for index, aFilter in enumerate(filters):
if aFilter.order == 0:
break
if filters[index].targetURI:
test = "yes"
else:
for aFilter in filters:
aFilter.save()
else:
formset = FilterFormSet(instance=controller)
return render_to_response('controller_details.html', {'formset':formset, 'controllerURI':controllerURI}, context_instance=RequestContext(request))
UPDATE: If you intended to create a FormSet with Controller and Filter models where Filter holds a FK to the Controller, you need:
FilterFormSet = inlineformset_factory(Controller, Filter, form=FilterForm)
Note that in your code above, you're only passing the the Controller model class, which caused some confusion.
Ok, so I'm fairly new to Django, but have been reading both the online django book and the djangoproject documentation, but I can't seem to figure this error out:
I've got an 'Orders' model:
class Orders(models.Model):
client_id = models.ForeignKey(Client)
order_date = models.DateField(auto_now_add = True)
due_date = models.DateField()
completion_date = models.DateField(blank=True, null=True)
rush_order = models.BooleanField(default=False)
billing_option = models.ForeignKey(Billing)
patient_first_name = models.CharField(max_length=30)
patient_middle_name = models.CharField(max_length=30, blank=True)
patient_last_name = models.CharField(max_length=30)
client_patient_id = models.CharField(max_length=30, blank=True)
emodel_patient_id = models.CharField(max_length=30)
special_instructions = models.TextField(blank=True)
order_items = models.ManyToManyField(Order_Items)
def __unicode__(self):
return '%s : %s %s O: %s F: %s' % (self.client_id, self.patient_first_name, self.patient_last_name, self.order_date, self.completion_date)
class Meta:
ordering = ['client_id']
I've got a 'SearchOrderForm' modelform:
class SearchOrderForm(ModelForm):
class Meta:
model = Orders
exclude = ('rush_order', 'billing_option', 'client_patient_id', 'special_instructions', 'order_items',)
and I've got an 'order_status' function:
def order_status(request):
error = False
error_searching = False
if request.method == 'POST':
OrderFormSet = SearchOrderForm()
formset = OrderFormSet()
if formset.is_valid():
cd = formset.cleaned_data()
emodels_results = cd()
emodels_results = cd(queryset = Order.objects.filter(Q(patient_first_name=search)|Q(patient_last_name=search)|Q(client_id=search)))
patient_first_name = request.POST('patient_first_name', None)
if patient_first_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_first_name=patient_first_name))
patient_last_name = request.POST('patient_last_name', None)
if patient_last_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_last_name=patient_last_name))
client_id = request.POST('client_id', None)
if client_id:
emodels_results = emodels_results(queryset = Order.objects.filter(client_id=client_id))
return render_to_response('search_results.html', {'models': emodels_results})
else:
emodels_results = "Still messed up!"
return render_to_response('search_results.html', {'models': emodels_results})
else:
error_searching = True
form = SearchOrderForm()
return render_to_response('order_status.html', {'form': form, 'error': error, 'error_searching': error_searching})
I can fill out my form with no problems, but when I submit the form I get back the following error message:
Traceback:
File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "C:\emodel_tracking..\emodel_tracking\tracker\views.py" in order_status
105. formset = OrderFormSet()
Exception Type: TypeError at /accounts/profile/orderstatus/
Exception Value: 'SearchOrderForm' object is not callable
Does anyone know what I'm doing wrong with my SearchOrderForm that's causing Django to say that it is not callable?
I think you want either of these:
OrderFormSet = SearchOrderForm()
if OrderFormSet.is_valid():
formset = SearchOrderForm()
if formset.is_valid()
With the second way being the preferred syntax style. As a matter of nitpicking, Django offers a FormSet type which is different than the Form type so it is convention to refer to instances of Forms as "form":
form = SearchOrderForm()
if form.is_valid():
You are going to have some other problems with your code:
def order_status(request):
error = False
error_searching = False
if request.method == 'POST':
#instead of:
#OrderFormSet = SearchOrderForm()
#formset = OrderFormSet()
#instantiate an instance of your ModelForm
#(I'd normally name it "form")
formset = SearchOrderForm()
if formset.is_valid():
cd = formset.cleaned_data()
#cd is now a Python dictionary
#these next 2 lines don't make sense, what is your intention?
emodels_results = cd()
emodels_results = cd(queryset = Order.objects.filter(Q(patient_first_name=search)|Q(patient_last_name=search)|Q(client_id=search)))
#you've already used your form to process and clean
#the incoming POST data. use the cleaned data instead
#patient_first_name = request.POST('patient_first_name', None)
patient_first_name = cd.get('patient_first_name','')
#use data from the form's cleaned_data as in the line above
#I'm not sure what your intention is with how the emodels_results
#is but you'll need to rework that for it all to work
if patient_first_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_first_name=patient_first_name))
patient_last_name = request.POST('patient_last_name', None)
if patient_last_name:
emodels_results = emodels_results(queryset = Order.objects.filter(patient_last_name=patient_last_name))
client_id = request.POST('client_id', None)
if client_id:
emodels_results = emodels_results(queryset = Order.objects.filter(client_id=client_id))
return render_to_response('search_results.html', {'models': emodels_results})
else:
emodels_results = "Still messed up!"
return render_to_response('search_results.html', {'models': emodels_results})
else:
error_searching = True
form = SearchOrderForm()
return render_to_response('order_status.html', {'form': form, 'error': error, 'error_searching': error_searching})