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.
Related
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')
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
I'm working on a project and I don't get the django forms to render on any of my pages. I've compared it to django girls code, as that is what I usually consult but it looks virtually identical to it. It's not just this page, my other pages have issues with rendering the forms as well. Here's the code:
Views.py
from django.shortcuts import render
from .models import *
from .forms import *
from django.shortcuts import render, get_object_or_404
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.db.models import Sum
from django.utils import timezone
from django.views.decorators.http import require_POST
from .cart import Cart
from django.db import transaction
from django.contrib import messages
#login_required
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=Post)
return render(request, 'rentadevapp/post_edit.html', {'rentadevapp': post_edit}, {'form': form})
Forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text',)
post_edit.html
{% extends 'rentadevapp/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<head>
<link rel="stylesheet" href="{% static 'css/post_edit.css' %}">
</head>
<body>
<div class="container"><br>
<h2>New Post</h2><br>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</div>
</body>
{% endblock %}
Models.py
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
updated_date = models.DateTimeField(auto_now_add=True)
price = models.DecimalField(max_digits=10, decimal_places=2, default='0')
class Meta:
ordering = ('title',)
def created(self):
self.created_date = timezone.now()
self.save()
def updated(self):
self.updated_date = timezone.now()
self.save()
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
I'm pretty stuck and have spent a couple hours trying to figure this out. Any help is really appreciated.
Thanks!
Your form isn't returned to the template in the context.
In Django 1.11 or 2.2 the render function call in your view should return a dictionary of context variables as the third argument, but you've got two dictionaries. The 4th argument where you've got a dictionary containing the form is being passed as content_type which is then used in the HttpResponse so I'm quite surprised there isn't something strange happening or an error seen.
So you're doing;
return render(request, 'rentadevapp/post_edit.html', {'rentadevapp': post_edit}, {'form': form})
What you need to do is;
context = {'form': form, 'rentadevapp': post_edit}
return render(request, 'rentadevapp/post_edit.html', context)
Prior to 1.10 render had a different signature, but the first three arguments of request, template_name, context have been that way since <1.8
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})
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.