Django / Model Forms - python

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

Related

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

Django form are not showing in html template

I'm trying to create a form in Django template but it is just not showing the fields
here is my files
models.py where i created the desired table
class ReportMessage(models.Model):
sender = models.ForeignKey(UserModel, related_name="report_message_sender", on_delete='CASCADE')
message = models.ForeignKey(Message, on_delete='CASCADE')
created_at = models.DateTimeField(auto_now=True)
reason = models.TextField(max_length=1500)
is_read = models.BooleanField(default=False)
forms.py where i created the form to edit only one field in the table
class ReportMessageForm(forms.Form):
class Meta:
model = ReportMessage
fields = ['reason', ]
views.py where i created the view for the form
#login_required
def report_message(request, pk):
current_user = request.user
reported_message = get_object_or_404(Message, pk=pk)
if request.method == "POST":
report_message_form = ReportMessageForm(request.POST)
if report_message_form.is_valid():
model_instance = report_message_form.save(commit=False)
model_instance.sender = current_user
model_instance.message = reported_message
model_instance.save()
return redirect('report_confirm')
else:
report_message_form = ReportMessageForm()
context = {
'report_message_form': report_message_form,
}
return render(request, 'fostania_web_app/report_message.html', context)
def report_confirm(request):
return render(request, 'fostania_web_app/report_confirm.html')
and urls.py where the urls i used for the views
path('report/messages/<int:pk>/', views.report_message, name="report_message"),
path('report/confirm', views.report_confirm, name="report_confirm"),
and finally that is how i used the form in the html template
{% extends 'fostania_web_app/base.html' %}
{% block content %}
{% load static %}
<form action="" method="post" name="ReportMessageForm" align="right">
{% csrf_token %}
{{ report_message_form }}
<input type="submit" class="btn btn-success" style="width: 100px;" value="إرسال" />
</form>
{% endblock %}
and then all what i see in the html page is the submit button and there is no form labels or input or anything.
In your forms.py if you are not using ModelForm then you have to explicitly declare the fields for the forms
reason = forms.Charfield()
Or you can use ModelForm which inherits from the model you specify.
You should specify the model in the Meta class while using ModelForm.You can also specify required fields from the Model in the fields list in Meta class
Class myform(forms.ModelForm)
Class Meta:
model = your_model_name
fields= [reason,]
Cheers
:)
I think that your problem is in your model form because you are using forms.Form and you need to use forms.ModelForm
class ReportMessageForm(forms.ModelForm):
class Meta:
model = ReportMessage
fields = ['reason', ]
def report_confirm(request):
return render(request, 'fostania_web_app/report_confirm.html', context) #add the context
You need to pass in the "context" so that it shows in the template

Django ModelForm; User, this field is required

I am having some issues with a (model)form consisting of just a single button. When I try to submit the form this message is displayed:
user
This field is required.
The ModelForm looks like this:
from django.forms import ModelForm
from .models import HulpOproep
class HulpOproepForm(ModelForm):
class Meta:
model = HulpOproep
fields = ['user', ]
The Model looks like this:
class HulpOproep(models.Model):
user = models.ForeignKey(User)
time = models.DateTimeField(auto_now_add=True, verbose_name='Tijd')
def __str__(self):
return '%s %s' % (self.user.username, str(self.time))
def username(self):
return self.user.username
def first_name(self):
return self.user.first_name
def last_name(self):
return self.user.last_name
class Meta:
verbose_name = 'Hulp Oproep'
verbose_name_plural = 'Hulp Oproepen'
The View looks like this:
def verzend_oproep(request):
if request.method == 'POST':
form = HulpOproepForm(request.POST)
if form.is_valid():
oproep = form.save(commit=False)
oproep.user = request.user
oproep.save()
return redirect('portal/index/')
else:
form = HulpOproepForm()
return render(request, 'portal/verzend_oproep.html', {'form': form})
The Template:
{% extends "base.html" %}
{% block head %}
<title>Zorggroep | Hulp Oproep</title>
{% endblock %}
{% block body%}
<h1>Verstuur Hulpoproep</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_P }}
{{ form.errors }}
<button type="submit" class="save btn btn-default">Verstuur</button>
</form>
{% endblock %}
The 'user' in the HulpOproep model is a ForeignKey and should be the currently logged in user's User object. I tried to specify this using the line:
oproep.user = request.user
So what should happen is:
Get the current user's 'User' object and use it as the 'HulpOproepForm.user'. This way the 'HulpOproepForm.user' is the 'HulpOproep.user' and a Foreign Key.
I have followed multiple tutorials and have searched around, but I cannot find a solution. I'm sorry if the answer is logical, but I have been using Django for only 5 days and have 1.5 months of programming experience under my belt.
Thank you!
Thanks PatNowak and Radek!
I did not know the form was waiting for user input instead of code input. I managed to fix it by adding exclude to the ModelForm.
class HulpOproepForm(ModelForm):
class Meta:
model = HulpOproep
exclude = ['user', 'time']

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.

Categories