Django Application, Django forms - django

I am creating an image classifier application. I am new to Django and what I am trying to do is I take an input image from the user via Django form and running the backend code for classification. After successful submission of the form, I redirect to the same form's page. Again, if I input another/same image, tensorflow throws error. Only when I input image for the first time, error does not occur. Please help!
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = UploadFileForm(request.POST,request.FILES)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
handle_uploaded_file(request.FILES['file'])
# if a GET (or any other method) we'll create a blank form
else:
form = UploadFileForm()
return render(request, 'name.html', {'form': form})
def handle_uploaded_file(f):
#image_bytes = f.read()
#image = Image.open(io.BytesIO(image_bytes))
#image1 = image.resize((224,224))
#dosom(image1)
print(f.name)
dosom(f)
The dosom function takes the input image and classifies it. The error thrown is-
'Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 64), dtype=float32)'

I found a link for the solution to the problem.
https://github.com/RasaHQ/rasa_core/issues/80
from keras import backend as K
and after you've predicted the result, clear the tensorflow session as
K.clear_session()

Related

Do I really need to accommodate both GET and POST request formats in a django form?

I'm new to django but something I don't understand is the need for accommodating both the GET and POST request types when developing a form. Please refer to code below from django docs:
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
The reason this confuses me is because I have developed a GET based form and it is working and I have no need for the POST portion above? See below:
# views.py
def simplifier_form(request):
form = LabelForm()
return render(request, "simplifier.html", {"form": form})
def process_simplifier(request):
label_name = request.GET.get('labels')
results = Disturbance.objects.filter(labeldisturbances__label_name=label_name)
painsresults = Pain.objects.filter(disturbances__pk__in=results).distinct()
total_disturbances = Disturbance.objects.filter(pain__pk__in=painsresults)
total_labels = Label.objects.filter(disturbances__pk__in=total_disturbances).distinct()
context = {'results': results, 'painsresults': painsresults, 'total_disturbances': total_disturbances, 'total_labels': total_labels}
return render(request,'process_simplifier.html', context)
# forms.py
class LabelForm(ModelForm):
labels = forms.ModelChoiceField(
queryset=Label.objects.all(),
to_field_name='label_name',
widget=forms.Select(attrs={'class': 'labels'}),
)
class Meta:
model = Label
fields = ['labels']
So why do the django docs and most examples include code for both methods when you only really use one like in my example above?
The question is... How do you want to process your from when submitted on POST?
Remember, your form can also be submitted on GET... You can decide what you would want to do if submitted on GET.

How can I create a csv importer in django?

I have an application in which the database shows people information.
I currently import the data from a csv file through the following script:
import csv, sys, os
dir_projeto =
"/home/danilo/Documentos/Projetos/transparencia/transparencia/"
sys.path.append(dir_projeto)
os.environ['DJANGO_SETTINGS_MODULE']='settings'
import django
django.setup()
from pessoal.models import Pessoa
data = csv.reader(open("CC_JUNHO.csv"), delimiter=";")
for linha in data:
importacao = Pessoa()
importacao.matricula = linha[0]
importacao.funcionario = linha[1]
importacao.cargo = linha[2]
importacao.data_admissao = linha[3]
importacao.salario_fixo = linha[4]
importacao.tota_bruto = linha[5]
importacao.total_desconto = linha[6]
importacao.liquido = linha[8]
importacao.save()
However, is it possible to do this import through a view and a django template? Example: The template would have a form to add the csv file, in which it would be imported into the db by the view. It is possible? If yes, how?
You can like you said create a form to gather your data. The form then performs a POST to a URL, which triggers a view that processes the data.
The following Django Tutorial elaborates this: https://docs.djangoproject.com/en/2.0/topics/forms/
For Example if your form sends a name, you can use the following to process it:
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})

Use multiple models in a single django form

I have a django application and for a particular form,the data comes from different models with one common field(id) across all models.Instead of using multiple forms and same id for all forms,I want to use a single form to take data from multiple models.How can this be done?
Specify your form as provided in the django docs: https://docs.djangoproject.com/en/1.10/topics/forms/#building-a-form-in-django
Specify the view e.g.
view.py
def get_name(request):
id = request.kwargs['id'] # Get the id from url or however you want to get the id
item = Item.objects.get(name_id=id)
item2 = Item2.objects.get(name_id=id)
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ... e.g.
item.name = form.cleaned_data['name']
item2.name = form.cleaned_data['name2']
item.save()
item2.save()
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
# This is for updating the "name" objects
form = NameForm(initial={'name': item.name, 'name2': item2.name})
# for creating: (but I guess you don't need creating)
# form = NameForm()
return render(request, 'name.html', {'form': form})
Handle the form in the template as you normally would.

Browser (firefox) keeps loading for long django processes

I am using django to perform some activity which takes quite a long time to finish ( around 2-3 hrs).
A django form is filled by the user and submitted to initiate the activity.
The view function does all the required functionality but when everything is finished, a HttpResponse is returned to tell the user that the activity is completed.
The problem is that while the process has been completed in the back-end, my browser(firefox) still keeps on loading instead of display the returned HttpResponse.
Can anyone advice me whether it is a browser issue or something wrong in my code.
views.py
def test(request) :
if request.method == 'POST': # If the form has been submitted...
form = TestForm(request.POST)
if form.is_valid(): # All validation rules pass
form_data = form.cleaned_data
## Get the form data and use it
output, error = executeCommand("##Perform the required action with the form data")
if error == '' :
return HttpResponse('Work Done !! Thanks')
else :
return HttpResponse('Error Occurred')
else:
form = TesForm() # An unbound form
return render_to_response("test.html", { 'form' : form } , context_instance=RequestContext(request))
Use celery to pass the job off to the backend for processing

How to check whether or not a Django form is correctly bound?

Situation
Using Django 1.5, I am using forms.ModelForms to let the user edit database contents. However I can't get the form to update the database upon form.save().
Each of my models correspond to a setting form (the application is a the direct porting of a desktop software in which the user can store several settings). I needed to implement a Reset to default feature, so I thought of having a default object (imported with Django fixtures) which I would use only to reset a second one. The user would only interact with the second model.
pk=1 refers to the base object
pk=2 refers to the custom object
I have several forms on the same page (only foobar here), so basically this what I planned to do:
No POST data
Building form from either pk=1 or pk=2, depending pk=2 has been found or not
Rendering the forms to the template
AJAX request, with POST datas
Getting form content
Checking whether or not the user has permission to edit the model (checksum)
Update the model form POST datas
Returning AJAX response
Code
I have put two debug prints to illustrate the issue I am facing. The form I fetch doesn't seem to be bound to my model.
# Response codes to use in the template
RESPONSES = {
200: {'code':'0xB16B00B5', 'message':'Success'},
400: {'code':'0x8BADF00D', 'message':'Form is not valid'},
403: {'code':'0xBAADF00D', 'message':'No permission to edit the database'},
501: {'code':'0xDEADC0DE', 'message':'POST datas not found'},
}
# Those are the setting labels
TYPES = {
'foobar': {'model':FooBar, 'form':FooBarForm },
}
def index(request):
# Handling form datas
if request.method == 'POST':
response = HttpResponse(simplejson.dumps({'code':RESPONSES[501]['code']}), 'application/json')
for label in TYPES:
# Filtering the right form to handle
if label in request.POST:
model = _fetch_setting(label, mode='model')
form = _fetch_setting(label, mode='form', post=request.POST)
checksum = model.checksum # Somehow, 'form.is_valid()' is altering 'model', need to backup the checksum
if form.is_valid():
# The user has permission to edit the model
if form.cleaned_data['checksum'] == checksum:
if form.has_changed():
print form.cleaned_data['foo'] # Outputs the form data, as expected
form.save()
print model.foo # Outputs the old data
model.checksum = str(uuid4()).replace('-', '')
model.save()
response = HttpResponse(simplejson.dumps({'code':RESPONSES[200]['code']}), 'application/json')
# This one does not
else:
response = HttpResponse(simplejson.dumps({'code':RESPONSES[403]['code']}), 'application/json')
break # We are still inside the label loop
# The form is not valid
else:
response = HttpResponse(simplejson.dumps({'code':RESPONSES[400]['code']}), 'application/json')
# Form not submitted yet, building the HTML forms
else:
forms = {}
label = 'foobar'
for label in TYPES:
forms[label] = _fetch_setting(label, mode='form')
context = {'errors':RESPONSES, 'forms':forms}
response = render(request, 'home/index.html', context)
return response
# Return a setting object (model or form) corresponding to the given label
def _fetch_setting(label, mode='model', post=None):
try:
result = None
default = TYPES[label]['model'].objects.get(pk=1)
try:
model = TYPES[label]['model'].objects.get(pk=2)
except TYPES[label]['model'].DoesNotExist:
model = TYPES[label]['model'].objects.create(
checksum = default.checksum,
foo = default.foo,
bar = default.bar,
)
if mode == 'model':
result = model
if mode == 'form':
print model
result = TYPES[label]['form'](data=post, instance=model) # The 'instance' attribute doesn't seem to be applied
except KeyError:
result = None
finally:
return result
Update
07.10
It does work when I pass the instance to bound with to _fetch_setting. So I guess this issue is coming from the form validation.
def _fetch_setting(label, mode='model', post=None, instance=None):
# ...
if mode == 'form':
if instance:
model = instance
result = TYPES[label]['form'](data=post, instance=model)
# ...
As I commented in my code, form.is_valid() seems to alter the object.
Will flag as answered if no one come with a clean solution.
The issue is, you are creating a new model object with each form.save()
You need to update the same model object with commit=False
if form.cleaned_data['checksum'] == checksum:
if form.has_changed():
print form.cleaned_data['foo'] # Outputs the form data, as expected
model = form.save(commit=False)
model.checksum = str(uuid4()).replace('-', '')
model.save()
From the fabulous manual:
The first time you call is_valid() or access the errors attribute of a ModelForm triggers form validation as well as model validation. This has the side-effect of cleaning the model you pass to the ModelForm constructor. For instance, calling is_valid() on your form will convert any date fields on your model to actual date objects. If form validation fails, only some of the updates may be applied. For this reason, you’ll probably want to avoid reusing the model instance passed to the form, especially if validation fails.