Unable to add data to databse from models forms django - python

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

Related

How to take boolean field input from HTML into my Django model?

I have used Django forms for creating users and I extended the default User model by adding a boolean field, so I defined a new form for it. But I couldn't take input from HTML form to this boolean field. Shall I change my HTML form code?
Following are my code samples:
models.py
# accounts.models.py
from django.db import models
from django.contrib.auth.models import User
class SpecialUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
flag = models.BooleanField()
def __str__(self):
return self.title
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms.widgets import CheckboxInput
from .models import SpecialUser
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
class SuperUserForm(forms.ModelForm):
class Meta:
model = SpecialUser
fields = ['flag']
widgets = {
'flag': CheckboxInput(attrs={'class': 'flag'}),
}
views.py
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
sp_form = SuperUserForm(request.POST)
if form.is_valid() and sp_form.is_valid():
user = form.save()
sp_form = sp_form.save(commit=False)
sp_form.user = user
sp_form.save()
messages.success(request, 'Account created!')
return redirect('login')
else:
form = RegisterForm()
sp_form = SuperUserForm()
messages.warning(request, 'Your account cannot be created.')
return render(request, 'register.html', {'form': form})
HTML form code:
<form method="post" class="form-group">
{% csrf_token %}
{{ form|crispy }}
<label for="flag">Special User: </label>
<input id="flag" class="flag" type="checkbox" name="flag">
<button type="submit" class="btn btn-success">Sign up</button>
</form>
In your views.py you're creating a local variable for a SpecialUser form, sp_form, that is neither loaded into the context data nor templated in the HTML form code.
You can load sp_form into the context data by adding it to the context dict passed to render(). This will allow the template to see the variable. For example:
return render(request, 'register.html', {'form': form, 'sp_form': sp_form})
And then you can render it in the template. For example, underneath the main form:
{{ form|crispy }}
{{ sp_form|crispy }}
For starters this is generally not how you would want to extend the user model in a Django application. You would want to inherit from AbstractUser and add your fields to that model and run migrations. At least in this case, that would be ideal, then you could simply define the field on your RegisterForm.fields and let {{ form|crispy }} render the form for you. Naturally, you could call form.save() and move on with your life.
To clarify why this may not be working, it is generally not good practice to render your own fields for a form unless absolutely necessary. If you insist on doing it this way, note that Django prefixes the id with id_ so in your case it would be <label for="id_name">...</label> and <input id="id_flag" ...

How to display an Excel sheet in Django?

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.

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

Input in forms not getting through in Django

I'm following Mike Hibbert's tutorial on links. The site works perfectly fine, however, the input I put in the form is not being updated or transmitted in the database.
from forms import LocationForm
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
from django.http import HttpResponse
from core.models import Location
from django.shortcuts import render
class LocationListView(ListView):
model = coremodels.Location
template_name='location/list.html'
def create2(request):
if request.method =='POST':
form = LocationForm(request.POST)
if form.is_valid():
form.save
return HttpResponseRedirect('/location/')
else:
form = LocationForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('location/create_location.html', args)
my models.py
class Location(models.Model):
title = models.CharField(max_length=300)
description = models.TextField(null=True, blank=True)
address = models.TextField(null=True, blank=True)
hours = models.TextField(null=True, blank=True)
my create_location.html:
{% block sidebar %}
<ul>
<li> Cancel</li>
</ul>
{% endblock %}
<form action="" method="post"> {% csrf_token %}
<ul>
{{form.as_ul}}
</ul>
and finally my forms.py
from django import forms
from models import Location
class LocationForm (forms.ModelForm):
class Meta:
model = Location
fields =('title', 'description', 'address')
<input type="submit" name="submit" value="create location">
</form>
No error or anything, site works perfect, however if I click on create new location and try submit a new location on the create_location.html it goes back to the locations (list.html) but without the new one.
I also tried updating the views with the code from the documentation
return render(request, 'location/create_location.html',{'form': form})
but didn't work.
What do I do wrong?
Thanks in advance
def create2(request):
if request.method =='POST':
form = LocationForm(request.POST)
if form.is_valid():
form.save
You're not calling form.save(), you're just "stating" the function name (which here does nothing).
Use
def create2(request):
if request.method =='POST':
form = LocationForm(request.POST)
if form.is_valid():
form.save()
and you should be good to go.

Form submit not POST's the value in Django

When i just tried to save data using this simple form , it is not getting posted . Is there anything wrong in declaration of actions or url's ?
Here the request.method is GET instead of POST even-though the form method is set as POST
Model file
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=30, null=True, blank=True)
company_id = models.CharField(max_length=30)
def __unicode__(self):
return self.name
Form.py uses the modelform
from contact.models import Contact
from django.forms import ModelForm
class AddcntForm(ModelForm):
class Meta:
model = Contact
Views
from contact.forms import AddcntForm
from django.contrib import messages
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template.context import RequestContext
def add_cnt(request, form_class=AddcntForm):
print request.method
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
form.save(request)
messages.success(request, "New Contact added.")
return redirect('##success##')
else:
form = form_class()
return render_to_response(
'vec/add_cnt.html',
{'form': form},
context_instance=RequestContext(request))
Url
from django.conf.urls import *
from django.conf import settings
urlpatterns = patterns('contact.views',
url(r'^addcnt/$', 'add_cnt', name='add_cnt'),
)
template file is as follows
{% block content %}
<form method="post" action="/hr/addcnt/" >{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Ok" />
</form>
{% endblock %}
You're passing the request.GET querydict to your form when the method is POST. You should pass request.POST instead.
Also you're passing the request to form.save(). The only (optional) argument expected by ModelForm.save() is a boolean "commit" flag which, if true, prevent the form from effectively saving the instance (cf https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/#the-save-method). Remember that in Python each object have a boolean value... IOW you're saying the form to not save your instance ;)
I was confused too with the same issue.
When the form is called initially it is "GET" request so the statement -print request.method will print "GET".
After entering values in the form if you click on submit, you can see in the console the same statement -print request.method will print "POST" which is actually a post request.

Categories