How can I create a csv importer in django? - 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})

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.

Django Application, Django forms

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()

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.

What URL patterns should I have for a multi-page signup form (using Django)?

First Post, so forgive any noob-iness -- I'm trying to create a multi-page product sign-up form. I can get the form to display and the submit button, but I can't find any examples of URL patterns for my urls.py file. I found another similar question with the following suggestions:
"You need to write a view to handle your request.(did that) You need to edit urls.py to map your quiz url to the function in views.py (trying, but failing). So when a request with that quiz url comes Django applies that view function.
When I Redirect the user to the new url is the problem. I can't seem to find an example of what the next pattern should be. Here's my urls.py code (index.html and details.html are my templates so far):
url(r'^signup/$', 'signup.views.select_product', name='select_product'),
url(r'^signup/(?P<product_id>\d+)/$', 'signup.views.subscriber_signup', name='subscriber_signup'),
#...
Here's my view code:
def select_product(request):
title = "get yourself an e-edition. wurd."
pform = ProductForm(request.POST)
if request.method == 'POST': # If the form has been submitted...
pform = ProductForm(request.POST) # A form bound to the POST data
if pform.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('signup/index.html') # Redirect after POST
else:
form = ProductForm() # An unbound form
return render_to_response('signup/index.html', {'title': title, 'pform': pform}, context_instance=RequestContext(request))
def subscriber_signup(request, product_id):
signup = Product.objects.get(id=product_id)
title = "get yourself an e-edition. wurd."
sform = SubscriberForm(request.POST)
if request.method == 'POST': # If the form has been submitted...
sform = SubscriberForm(request.POST) # A form bound to the POST data
if sform.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('signup/detail.html') # Redirect after POST
else:
sform = SubscriberForm() # An unbound form
return render_to_response('signup/detail.html', {'title': title, 'sform': sform, 'signup': signup,}, context_instance=RequestContext(request))
Or use Django's form wizard which was designed for this.
so part of the problem was I was using the (User) model in my Subscriber class, which the SubscriberForm was based. I ditched that and made a form based on a normal class with the objects defined individually.
Here's the URL patterns that eventually worked.
url(r'^signup/$', 'signup.views.select_product', name='select_product'),
url(r'^signup/(?P<product_id>\d+)/$', 'signup.views.subscriber_signup', name='subscriber_signup'),
url(r'^signup/(?P<product_id>\d+)/thankyou/$', 'signup.views.thankyou', name='thankyou'),
thanks for the responses.
Anthony

Django: How to prepopulate file upload path with current file path?

I have a modelform that my views generate an HTML form for editing content. Currently, it's able to pull in the current stored text content, like this:
#login_required
def edit_person(request, s_id, p_id):
p = get_object_or_404(Person, id=p_id)
if request.method == 'POST':
form = PersonForm(request.POST, request.FILES)
if form.is_valid():
p.name = request.POST['name']
p.title = request.POST['title']
handle_uploaded_file(request.FILES['photo'], request.FILES['photo'].name, 'media/images/people/')
p.photo = request.FILES['photo']
p.order = request.POST['order']
p.save()
return HttpResponseRedirect('/section/'+s_id+'/')
else:
return HttpResponse("error")
else:
form = PersonForm({ 'name': p.name, 'title': p.title, 'photo': p.photo, 'order': p.order })
return render_to_response('auth/edit-form.html', { 'form': form }, context_instance=RequestContext(request))
return HttpResponseRedirect('/section/'+s_id+'/')
However, the photo file path is blank. I don't want the user to have to upload a new file every time they edit something if they don't want to change the image. How do I get the file upload field to appear pre-populated and not overwrite itself if they don't change it? Thanks.
Believe it or not, it can be done! However, it requires the use of a custom django app called django-file-resubmit
Note that app as given only works for the widgets in admin and requires sorl-thumbnail.
You may prefer to use my fork:
https://github.com/JordanReiter/django-file-resubmit
It's a general-purpose version for use everywhere a ModelForm is used that doesn't have any other prerequisites.
It's pretty cool in that it automagically stores the file on submission (even if there is a validation error) and retrieves it from the cache when the widget is rendered in the form.
This is literally all you have to do to implement it:
import file_resubmit.widgets
class PersonForm:
""" existing code here """
photo = forms.ImageField(required=False, widget=file_resubmit.widgets.ResubmitImageWidget())