I'm trying to utilize Django forms.ModelForm function. However, I can not get it to render in the browser (Firefox and Chrome tested). In both browser inspection of code, the table\form does not show and there is no error coming from Django at all. The only thing that shows from the html file is the "Save button" Is there something I am missing here?
In Models.py
from django.db import models
class Product_sell_create(models.Model):
product_product_sell = models.CharField(max_length=120)
product_price_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_volume_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_location_sell = models.CharField(max_length=120)
product_description_sell = models.TextField(blank=False, null=False)
Forms.py
from django import forms
from .models import Product_sell_create
class ProductName(forms.ModelForm):
class Meta:
model = Product_sell_create
fields = [
'product_product_sell',
'product_volume_sell',
'product_price_sell',
'product_location_sell',
'product_description_sell'
]
Views.py
from django.shortcuts import render
from .forms import ProductName
def products_create_view(request):
form = ProductName(request.POST or None)
if form.is_valid():
form.save()
form = ProductName()
context = {
'form': form
}
return render(request, "sell.html", context)
sell.html
{% include 'navbar.html' %}
<h1> Upper test</h1>
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST </h1>
{% block content %}
{% endblock %}
just did it, you would have problems POSTing your object too:
views.py:
from django.shortcuts import render, redirect
from .forms import ProductName
from .models import Product_sell_create
def products_create_view(request):
if request.method == 'POST':
form = ProductName(request.POST)
if form.is_valid():
prod = form.save(commit=False)
prod.save()
return redirect('../thanks')
else:
form = ProductName()
context = {
'form': form
}
return render(request, "form_test.html", context)
def thanks_view(request):
query = Product_sell_create.objects.all()
return render (request, 'thanks.html', {'query' : query})
forms.py and models.py keeps the same
sell.html:
<h1> Upper test</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST2 </h1>
thanks.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{ query }}</h1>
<h2>THANKS</h2>
</body>
</html>
did you create the 'sell.html' inside a 'templates' folder in your app folder?
MyApp/templates/sell.html
Related
I'm trying to save data entered in this form (below) into a database:
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO</title>
</head>
<body>
{% if user.is_authenticated %}
<form id='add-task' method='post'>{% csrf_token %}
<div class="mb-3">
<input type="text" class="form-control" name="task-name" placeholder="task name">
</div>
<div class="mb-3">
<input type="text" class="form-control" name="task-desc" placeholder="description">
</div>
<div class="mb-3">
<input type="text" class="form-control" name="deadline" placeholder="YYYY-MM-DD">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</br></br>
{% endif %}
</body>
</html>
I'm not sure if I poorly formatted the code or if I'm using the wrong HTML. Is it possible to do this using HTML or should I just use a ModelForm?
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from .models import Task
def home(request):
# checks if user is logged in so that it can display task creation page
if request.user.is_authenticated:
return render(request, 'home.html', {'user': request.user})
# add new task ---> ALL THE CODE BELOW
if request.method == 'POST':
name = str(request.POST['task-name'])
desc = str(request.POST['task-desc'])
deadline = request.POST['deadline']
task = Task(task_name=name, task_desc=desc, task_deadline=deadline)
task.save()
#messages.success(request, "You've added a task.")
return render(request, 'home.html', {})
If you want to get your code as it is running:
def home(request):
# checks if user is logged in so that it can display task creation page
if request.user.is_authenticated:
if request.method == 'POST':
name = str(request.POST['task-name'])
desc = str(request.POST['task-desc'])
deadline = request.POST['deadline']
task = Task(task_name=name, task_desc=desc, task_deadline=deadline)
task.save()
return render(request, 'home.html', {'user': request.user})
else:
return render(request, 'home.html', {})
But you don't need to pass in user as context. This is available anyway.
So you could just do:
def home(request):
if request.method == 'POST':
name = str(request.POST['task-name'])
desc = str(request.POST['task-desc'])
deadline = request.POST['deadline']
task = Task(task_name=name, task_desc=desc, task_deadline=deadline)
task.save()
return render(request, 'home.html')
And request.user will still be available as {{ request.user.is_authenticated }} in your template.
I use modelformset_factory to upload image, but I want to separate the already saved image (A in the below link) and upload image (B in the below link) on two different html template.
How do I resolve this problem?
Here is my code below:
views.py
def post_image(request):
PictureFormSet = modelformset_factory(Picture, form=PictureForm, extra=3)
if request.method == 'POST':
formset = PictureFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
return HttpResponse("Upload done!!")
else:
return HttpResponse("Upload Failed!!")
else:
formset = PictureFormSet()
return render(request, "Image.html", {"formset": formset})
models.py
class Picture(models.Model):
article = models.ForeignKey("Article", related_name="article_photo", on_delete=models.CASCADE)
photo = models.ImageField(upload_to="photo", height_field=None, width_field=None, max_length=100)
first_photo = models.BooleanField(default=False)
urls.py
path('post/image/', post_image),
html
<html lang="zh-Hant-TW">
<head>
<meta charset="UTF-8">
<title>post_image</title>
</head>
<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table>
<input type="submit" value="Sumbit">
</form>
Befor all :
Djano VERSION = 1.8, and it's obligatory that I use this version
Question
I do not know why I cannot update the User instance by a form.
I mean by updating: changing the value in the database and in the request
The User model is not created by me but I use django.contrib.auth.models.User
Code
This is my code
app/forms.py
from django import forms
from django.contrib.auth.models import User
class ModificationForm(forms.ModelForm):
class Meta:
model = User
fields = ['email']
app/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from app.forms import ModificationForm
#login_required
def profil(request):
if request.method == "POST":
form = ModificationForm(data=request.POST, instance=request.user)
if form.is_valid():
form.save()
else:
form = ModificationForm()
return render(request, "profil.html", {'form':form})
profile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Profil</title>
</head>
<body>
<h1>Profil</h1>
<a href='/deconnexion'> Logout </a>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Enregistrer" />
</form>
</body>
</html>
Your posting to the wrong link!
If you do not know it, just leave the action empty in the html insted of action="." !
In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password.
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from .models import Reg
from .forms import LoginForm
from .forms import RegForm
def reg(request):
if request.method == 'POST':
form = RegForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponse('reg success')
else:
print(form.errors)
return HttpResponse("error")
else:
form = RegForm()
return render(request,'reg.html', {'form': form})
def login(request):
if request.method == "POST":
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
un =MyLoginForm.cleaned_data['user']
pw=MyLoginForm.cleaned_data['pwd']
dbuser = Reg.objects.filter(user=un,pwd=pw)
if not dbuser:
return HttpResponse('opppppss login faield')
else:
return HttpResponse('login success')
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def home(request):
return render(request,'home.html')
models.py
from __future__ import unicode_literals
from django.db import models
class Reg(models.Model):
user = models.CharField(primary_key=True,max_length=20)
pwd = models.CharField(max_length=20)
fname=models.CharField(max_length=10)
lname=models.CharField(max_length=10)
dob=models.DateField()
mobno=models.IntegerField()
forms.py
from django import forms
from .models import Reg
class RegForm(forms.ModelForm):
class Meta:
password = forms.CharField(widget=forms.PasswordInput)
model = Reg
widgets = {'pwd': forms.PasswordInput(),}
fields = ['user', 'pwd','fname','lname','dob','mobno']
class LoginForm(forms.Form):
user = forms.CharField(max_length=20)
pwd = forms.CharField(widget=forms.PasswordInput())
home.html
<!DOCTYPE html>
</html>
<html>
<body bgcolor="#00ffff">
<h1>welcome </h1>
click here to register<br>
click here to login
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
reg.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try adding this to your settings.py
SESSION_COOKIE_AGE = 30
Recently, I've been working on a project to make certain tasks that are crucial to a project I am a part of become a lot easier.
The form was working the last time I checked it (a month ago). Since then, I moved it off of my computer and on to a server. The form is no longer submitting.
#forms.py
from django import forms
from .models import OnlineEssay, HardCopy, FaceToFaceConference
class OnlineEssayClientForm(forms.ModelForm):
class Meta:
model = OnlineEssay
fields = [
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"client_email",
"feedback_primary",
"feedback_secondary",
"essay_file",
]
labels = {
'client_first_name': ('First Name'),
'client_last_name': ('Last Name'),
'client_grade': ('Grade Level (As Number)'),
'client_teacher': ('Teacher'),
'client_email': ('Email Address'),
'feedback_primary': ('I need/would like feedback on:'),
'feedback_secondary': ('And,'),
}
class OnlineEssayTutorForm(forms.ModelForm):
class Meta:
model = OnlineEssay
fields = [
"essay_type",
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"client_email",
"feedback_primary",
"feedback_secondary",
"essay_file",
"essay_tutor",
"essay_feedback",
]
class HardCopyTutorForm(forms.ModelForm):
class Meta:
model = HardCopy
fields = [
"essay_type",
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"feedback_primary",
"feedback_secondary",
"essay_tutor",
"essay_feedback",
]
class FaceToFaceConferenceTutorForm(forms.ModelForm):
class Meta:
model = FaceToFaceConference
fields = [
"essay_type",
"client_first_name",
"client_last_name",
"client_grade",
"client_teacher",
"feedback_primary",
"feedback_secondary",
"essay_tutor",
"essay_feedback_notes",
]
<!-- templates/submit.html -->
{% extends 'base.html' %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% block head_title %}Welcome{% endblock %}
</head>
<body>
{% block content %}
<h1>Submit Your Essay</h1>
<div class="bs-callout bs-callout-default">
<p>Fill Out The Form Below, then press Submit</p>
</div
<form method="post" enctype="multipart/form-data">{%csrf_token%}
{{form|crispy}}
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
{% endblock %}
</body>
</html>
#views.py
from django.shortcuts import render
from django import http
# Create your views here.
from .forms import OnlineEssayClientForm
def submit(request):
form = OnlineEssayClientForm(request.POST or None, request.FILES or None)
context = {
"form": form,
"page_title" : "Submit Your Essay",
}
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/success/')
return render(request, "submit.html", context)
It was actually a pretty simple issue. I had forgot to close the </div> tag at the end of the callout. The form submits fine now.