How to display an Excel sheet in Django? - python

im working on a Django website and i wnat to display an Excel Sheet that can later be edited on the website. Right now i am only able to upload a file but nothing is displayed. I know FileField is probably the way to go but how do i make the file show on the webpage? Django-excel seems does not do the job for me, because i think there is a much easier way to just display a file (but not an image).
Here is my models.py
from django.db import models
class Document(models.Model):
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to="documents/")
uploaded_at = models.DateTimeField(auto_now_add=True)
Here is my views.py
class UploadFileForm(forms.Form):
file = forms.FileField()
def index(request):
documents = Document
template = loader.get_template('documents/index.html')
context = {
'documents' : documents
}
return HttpResponse(template.render(context, request))
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('documents:index')
else:
form = DocumentForm()
return render(request, 'documents/model_form_upload.html', {
'form': form
})
My forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('description', 'document')
and my upload_template.html where the file should be displayed at the end
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<p>Return to Home</p>
I think i'll just have to change something in the views.py but i ran out of ideas. Any answers would be appreciated.

Related

Django Validation is working on django admin but not working on html template

I'm creating a form where if we register it should save data to the database if the form is valid. otherwise, it should raise an error but it doesn't save data to the database, and also some fields are required but if I submit the form it doesn't even raise the error field is required. but if I register it manually on Django admin pannel it works perfectly fine.
here is my model:
class foodlancer(models.Model):
Your_Name = models.CharField(max_length=50)
Kitchen_Name = models.CharField(max_length=50)
Email_Address = models.EmailField(max_length=50)
Street_Address = models.CharField(max_length=50)
City = models.CharField(max_length=5)
phone = PhoneNumberField(null=False, blank=False, unique=True)
def __str__(self):
return f'{self.Your_Name}'
also, I disabled html5 validation
forms.py
class FoodlancerRegistration(forms.ModelForm):
phone = forms.CharField(widget=PhoneNumberPrefixWidget(initial="US"))
class Meta:
model = foodlancer
fields = "__all__"
views.py:
def apply_foodlancer(request):
form = FoodlancerRegistration()
return render(request, 'appy_foodlancer.html', {"form": form})
and finally Django template
<form method="POST" novalidate>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="cta-btn cta-btn-primary">Submit</button>
</form>
Thank you for your time/help
You don't have any form saving logic in your view.
Try something like this:
def apply_foodlancer(request):
if request.method == 'POST':
form = FoodlancerRegistration(data=request.POST)
if form.is_valid(): # if it's not valid, error messages are shown in the form
form.save()
# redirect to some successpage or so
return HttpResponse("<h1>Success!</h1>")
else:
# make sure to present a new form when called with GET
form = FoodlancerRegistration()
return render(request, 'appy_foodlancer.html', {"form": form})
Also check that the method of your form in your HTML file is post. I'm not sure if POST also works.
Avoid defining fields in a modelform with __all__. It's less secure, as written in the docs

Django / Model Forms

Completely new to all computer programming and trying to build an app that tracks my smoking habits. The first step was creating a Django model called packs:
class packs (models.Model):
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, blank=False)
num_packs = models.SmallIntegerField(max_length=10)
cost_packs = models.DecimalField(max_digits=6, decimal_places=2)
Next I created a forms.py page and this is where I started getting lost:
from django.forms import ModelForm
from .models import packs
class packsForm(ModelForm):
class Meta:
model = packs
fields = ['num_packs', 'cost_packs']
Of course that led to my failure in HTML trying to render a page that has all the form data:
{%block content%}
<div class = "form_pack">
<h3>FORM PACK</h3>
<p>
<form method="POST" action="."> {% csrf_token %}
<input text="cost_pack" name=cost_pack>
{{ form }}
<input type="submit" value="save"/>
</form>
</p>
</div>
{% endblock %}
To help my view.py looks like this:
def packs_create(request):
form=packsForm(request.POST or None)
if form.is_valid():
return render(request, 'pack/index.htmnl', {'form': form})
Now when I refresh the page I don't get the form. Just the one input i put in.
Can someone help me sort out which path I got lost in and where I need to connect the dots? I believe my forms.py is not complete, but not sure where to progress...
Thanks,
DrKornballer
Just update your views.py and forms.py you will get your form and can save the data entered.
views.py
def packs_create(request):
if request.method == "POST":
form = packsForm(request.POST)
if form.is_valid():
form.save(commit = True)
else:
form = PacksForm()
return render(request, 'pack/index.html', {'form': form})
forms.py
class packsForm(ModelForm):
class Meta:
model = packs
fields = ('num_packs', 'cost_packs')

Unable to add data to databse from models forms django

I am trying to send data from django forms to backend sqlite3. But I am unable to do so. I am not also getting any error or warning that help me to sort it out.
Here is models.py file
from django.db import models
GENDER_CHOICES = [
('Male', 'M'),
('Female', 'F')]
class upload(models.Model):
name = models.CharField(max_length=100)
gender = models.CharField(max_length=10, choices=GENDER_CHOICES)
phone = models.CharField(max_length=50,null=True)
email= models.EmailField(max_length=50,null=True)
file=models.FileField(upload_to='uploads/')
def __str__(self):
return self.name
here is forms.py file
from django.forms import ModelForm
from .models import upload
class uploadForm(ModelForm):
class Meta:
model = upload
fields = ['name', 'gender', 'phone', 'email','file']
Here is view.py file
from django.shortcuts import render
from .forms import uploadForm
from django.shortcuts import render
def home(request):
if request.method == 'POST':
form = uploadForm()
if form.is_valid():
form=form.save()
return HttpResponseRedirect('/')
else:
form = uploadForm()
return render(request,'home.html',{'print':form})
I am unable to understand where is the issue
This is how template file look like
<form method="post">
{% csrf_token %}
{{ print.as_p }}
<input type="submit" value="Submit">
</form>
EDIT
This issue is with FileField, I removed it, and it start saving in django database. What I want is to save file in media folder and other data in database
I also added enctype="multipart/form-data" in form
I don't think your actually sending anything to the database.
Where is says form = uploadForm() you need state you want the posted data to be sent. so this needs to be form = uploadForm(request.POST) it should then work I believe. Also when saving the form, remove the form=form.save() and leave it as form.save()
Try it out and let us know?
Solution to my post
For handling files, I need to add encryption type to my form as
enctype="multipart/form-data"
Once I added that, to access the files I should use request.FILES along with request.POST
So now I have this home function in views.py file
def home(request):
if request.method == 'POST':
form = uploadForm(request.POST,request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = uploadForm()
return render(request,'home.html',{'print':form})
and my template form looks like
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ print.as_p }}
<input type="submit" value="Submit">
</form>
Credit : https://youtu.be/Rr1-UTFCuH4?t=244

Django ModelForm not saving data to database, Form.save is not working?

List item
Hello I am django beginner having tough time could someone please help me I don't know what am I doing wrong ?
I am trying to create a form and saving some data through it by using form.save(). And I am new to here also so don't mind any mistakes.
Here is my model:
from django.db import models
from stores.models import Store
class Category(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Product(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
price = models.DecimalField(max_digits=5, decimal_places=5)
image = models.ImageField(upload_to='upload_to/')
category = models.ForeignKey(Category, default='Default', on_delete=models.CASCADE, blank=False, null=False)
store = models.ForeignKey(Store, on_delete=models.CASCADE, blank=False, null=False)
Here is my view:
from django.shortcuts import render, redirect
from .forms import NewPro
def pro(request):
if request.method == 'POST':
form = NewPro(request.POST)
if form.is_valid():
form.save()
return redirect('stores_list')
else:
form = NewPro()
return render(request, "default/add_product.html", {'form': form})
def product_list(request):
return render(request, 'default/product_list.html')
Here is my form:
from django import forms
from .models import Product
class NewPro(forms.ModelForm):
class Meta:
model = Product
fields = ('name', 'price', 'image','category', 'store',)
default/add_product.html :
{% extends 'default/base.html' %}
<html>
<head><title>E-Commerce App</title></head>
{% block content %}
<h1>Add Product details</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Product</button>
</form>{% endblock %}
</html>
Settings.py settings
MEDIA_ROOT = '/home/saifi/Saif_project/final_project/MEDIA_ROOT/upload_to'
I can see some indentation issues in the view - but I'll guess that's just formatting when copying into Stackoverflow.
the form.is_valid() check will validate all your form fields and will only write to the database if all the input fields are valid. If it's not saving, the first place I'd check would be for form errors.
In your template you can render the errors with {{form.errors}} and it will list each field and error.
You forgot request.FILES in your pro view function, you have an image file after all.
def pro(request):
if request.method == 'POST':
form = NewPro(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('stores_list')
else:
form = NewPro()
return render(request, "default/add_product.html", {'form': form})
Try using the form this way:
<form action="YOUR_URL_HERE" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Product</button>
</form>
I hope this will help. Welcome aboard ;)
Your indentation is wrong, the else should be for first 'if'
def pro(request):
form = NewPro()
if request.method == 'POST':
form = NewPro(request.POST)
if form.is_valid():
form.save()
return redirect('stores_list')
else:
form = NewPro()
return render(request, "default/add_product.html", {'form': form})

How to add a new instance of Django model with FileField by ModelForm?

I'm a Django beginner. I think my problem is trivial but I can't solve it.
I have a model named Document with one FileField:
class Document(models.Model):
file = models.FileField(upload_to="documents")
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
category = models.ForeignKey(DocumentCategory)
title = models.CharField(max_length=255, unique=True)
description = models.TextField()
def __unicode__(self):
return self.title
I want to add a new instance to this class by this ModelForm:
class DocumentForm(ModelForm):
class Meta:
model = Document
In views.py I have:
def add_document(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
return render_to_response('add_document.html', {'form':form}, context_instance=RequestContext(request))
else:
form = DocumentForm()
return render_to_response('add_document.html', {'form':form}, context_instance=RequestContext(request))
Template for this (i.e. add_document.html):
{% extends "base.html" %}
{{block content %}
<form enctype="multipart/form-data" method="post" action="">{% csrf_token %}
{{form}}
<input type="submit" value="Add document" />
</form>
{% endblock %}
In the Admin Interface adding a model to the database is working correctly and adding a file is in "upload_to" localization. My form does not work. When I try to submit a form I get Filefield error: "This field is required!" Without FileField in model this works before.
I have Django 1.2.5
I torture with it for 3 days and nothing! I'm desperate. Sorry for my language. Please help!
As it is now, a file is required. Are you trying to save the form without a file?
If you want to make the file optional, you need to define it in this way:
class Document(models.Model):
file = models.FileField(upload_to="documents", blank=True, null=True)
As a an additional note, the action parameter you have in the form may be incorrect.
It should be an URL; usually in Django you would want to put ".", but not a completely empty string (""). That said, I do not know if this may be an issue or not.
In you Document model, you have your file set to upload_t0 "documents", but where exactly is upload_to pointed to.
May be this will help.

Categories