How to save a form in a database (django) - python

I have a quiz. I have 2 pages, I create the questions and their answers on the first page and I put these questions on the second page, but I want these questions to have the Answer model input, i.e. each question has its own input. When I try to set a query with an Id in the view and the unsuitable Answer form to save does not work, it is not stored in the database. How do I save?
models.py
from django.db import models
# Create your models here.
class Question(models.Model):
question=models.CharField(max_length=100)
answer_question=models.CharField(max_length=100, default=None)
def __str__(self):
return self.question
class Answer(models.Model):
questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions")
answer=models.CharField(max_length=100,blank=True)
def __str__(self):
return str(self.questin)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Question,Answer
class QuestionForm(forms.ModelForm):
class Meta:
model=Question
fields="__all__"
class AnswerForm(forms.ModelForm):
class Meta:
model=Answer
fields="__all__"
views.py
from django.shortcuts import render
from django.shortcuts import render, HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from .forms import QuestionForm,AnswerForm
from .models import Question
import random
def home(request):
form=QuestionForm
if request.method=='POST':
form=QuestionForm(request.POST)
if form.is_valid():
form.save()
return render(request, "question/base.html", {"form":form})
def ans(request):
form=AnswerForm
questions=Question.objects.all()
if request.method=="POST":
instance=Question.objects.get(id=request.POST['i_id'])
print(instance)
form=AnswerForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return render(request, "question/ans.html", {"form":form, "questions":questions})
ans.html
<!DOCTYPE html>
<html>
<head>
<title>question</title>
</head>
<body>
{% for i in questions %}
<form method="POST" novalidate>
{% csrf_token %}
<input type="hidden" name="i_id" value="{{ i.id }}" />
{{i}}
{% for a in form %}
{{a}}
{% endfor %}
<input type="submit" name="sub">
</form>
{% endfor %}
</body>
</html>

Try to different approaches to create the pages in html and c

Related

Django 3: is_valid() is always false using FileField and FloatField

I am trying to make a simple form in Django that accepts some file upload fields and a few float fields. However, when I run this in my browser, the is_valid() never gets triggered even when all forms are filled in. I have looked through the Django docs and have tried to recreate the examples as much as possible, but I can't figure out what is wrong. I know that the is_valid() is not true because the page does not redirect to another page when submit is pressed. Also, if I go into the admin page, no instances of MyModel are made.
Here is my code.
models.py:
from django.db import models
# Create your models here.
class MyModel(models.Model):
file1 = models.FileField()
file2 = models.FileField()
x = models.FloatField()
y = models.FloatField()
z = models.FloatField()
def __str__(self):
return self.file1
forms.py:
from django import forms
from django.forms import ModelForm
from .models import MyModel
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .forms import MyForm
# Create your views here.
def index_view(request):
if request.method == 'POST':
form = MyForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('some_page')
else:
form = DocumentsForm()
return render(request, 'index.html', {'form':form})
index.html:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Home Page!</h1>
<form method="POST" action="/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="Submit">
</form>
</body>
</html>
My guess is it has to do with the fact that you haven't included enctype="multipart/form-data" in your <form> declaration in the HTML. It should look like this:
<form action="/" method="post" enctype="multipart/form-data" class="">
The multipart/form-data is necessary when uploading a file through forms.
Since you are sending both data and files, you need to specify the encoding of the form to:
<form enctype="multipart/form-data" method="POST" action="/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="Submit">
</form>

model forms fiels not displayed in views in django

The problem is that the first_name, last_name and email fields are not displayed in browser. The command prompt is showing no error and server is running smoothly.
I cant figure out whats the problem.Here is my code.I am using django 1.11 and python 3.6
models.py
from django.db import models
# Create your models here.
class signup(models.Model):
first_name=models.CharField(max_length=120,null=True,blank=True)
last_name=models.CharField(max_length=120,null=True,blank=True)
email=models.EmailField()
timestamp=models.DateTimeField(auto_now_add=True,auto_now=False)
updated=models.DateTimeField(auto_now_add=False,auto_now=True)
def __str__(self):
return self.email
forms.py
from django import forms
from .models import signup
class sign_up_form(forms.ModelForm):
class Meta:
model = signup
fields='__all__'
views.py
from django.shortcuts import render,render_to_response
from django.template import RequestContext
from .forms import sign_up_form
# Create your views here.
def home(request):
form = sign_up_form()
return render(request,'signup.html',)
signup.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>join now</h1>
<form method="POST" action="">{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</body>
</html>
I think you omitted to include your form in the template context, inside the render method (note that the default context parameter is None).
def home(request):
form = sign_up_form()
return render(request,'signup.html', {'form': form})
Also, as per PEP8 style guide, please name your classes as CamelCase (SignUpForm for your form, SignUp for your model etc.).

I created a new model signup with appropriate fields which creates users just fine but I am unable to create a log in for the same [Django]

I was following "CodingEntrepreneurs - Try Django Tutorial 5 of 21 - Django Views for the Sign up model" tutorial on YouTube and was able to successfully create a signup model with proper details. After that I wanted to implement sign in feature for the same, so I started following > https://www.youtube.com/watch?v=O4zNUCFtfdY&feature=youtu.be < but I am unable to log in through this process, it is always returning the unable to login page, I am completely lost even though I have spent a lot of time figuring this out on my own. This is the project folder. Any help would be appreciated.
Signin.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Sign In</h1>
{% if form.errors %}
<p> Sorry thats invalid username or password</p>
{% endif %}
<form method="POST" action="/auth/">{% csrf_token %}
<label for="email">E-mail</label><br><input type="email" name="email" value="" placeholder="E-mail"><br>
<label for="password">Password</label><br><input type="password" name="password" placeholder="password">
<input type="submit" >
</form>
</body>
</html>
views.py
from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from django.template import RequestContext
from .forms import SignUpForm,SignInForm
from django.contrib import messages
from django.contrib.auth import authenticate,login
from django.template.context_processors import csrf
# Create your views here.
def home(request):
return render_to_response('index.html')
def signup(request):
form=SignUpForm(request.POST or None)
if form.is_valid():
save_it=form.save(commit=False)
save_it.save()
messages.success(request,'thanku for joining')
return render(request,'signup.html',{'form':form})
def SignIn(request):
c= {}
c.update(csrf(request))
return render_to_response('signin.html',c)
def auth_view(request):
if request.method == 'POST':
email=request.POST['email']
password=request.POST['password']
user=authenticate(email=email,password=password)
if user is not None:
login(request,user)
return render_to_response('LoggedIn.html')
else:
return HttpResponse('<h1>Invalid username/password<</h1>')
from django import forms
from .models import signup
Forms.py
class SignUpForm(forms.ModelForm):
class Meta:
model = signup
widgets={
'password':forms.PasswordInput(),
}
fields='__all__'
class SignInForm(forms.ModelForm):
class Meta:
model= signup
widgets={
'password':forms.PasswordInput(),
}
fields='__all__'
Models.py
from django.db import models
# Create your models here.
class signup(models.Model):
first_name=models.CharField(max_length=120,null=True,blank=True)
last_name=models.CharField(max_length=120,null=True,blank=True)
email=models.EmailField()
password=models.CharField(max_length=100,default="qwerty")
timestamp=models.DateTimeField(auto_now_add=True,auto_now=False)
updated=models.DateTimeField(auto_now_add=False,auto_now=True)
def __str__(self):
return self.email

Image field didn't get saved, raises error 'This field is required'

models.py:
from django.db import models
from django.contrib.auth.models import User
class Electronics(models.Model):
ELEC_CHOICES = (
('LAP', 'Laptops'),
('MOB', 'Mobiles'),
('WAT', 'Watches'),
('CAM', 'Camera'),
)
elec_name = models.CharField(max_length=3, choices=ELEC_CHOICES)
elec_image = models.ImageField('Label', upload_to='C:/Users/User/Desktop/')
elec_price = models.IntegerField('Price')
elec_stock = models.BooleanField(default=False)
forms.py:
from django import forms
from django.forms import ModelForm
from .models import Electronics
class ElectronicsForm(ModelForm):
class Meta:
model = Electronics
fields = '__all__'
views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Electronics
from .forms import ElectronicsForm
# Create your views here.
def eleclist(request):
elec = Electronics.objects.order_by('elec_name')
return render(request, 'index.html', {'elec': elec})
def elecadd(request):
if request.method == 'POST':
form = ElectronicsForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('shopp:eleclist'))
else:
print(form.errors)
else:
form = ElectronicsForm()
return render(request, 'add.html', {'form': form})
my add.html:
<html>
<head><title>Electronics</title></head>
<body>
<form method = "post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="submit" value="create">
</form>
</body>
</html>
I'am first time trying to upload an image using django model forms. But when I clicked submit, the image didn't get saved. It raises error 'this field is required'.
I've looked in some django docs also, but it has very concise material.
You need to add enctype="multipart/form-data" to your form tag, otherwise your file won't be uploaded to server. So update your form template to:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="create">
</form>

CSRF token missing or incorrect in Django form

I am very new to Django forms. I am trying to simply get a value from a text field and store it in a database. I am getting an error report saying:
*Forbidden (403)
CSRF verification failed.
Request aborted.
Reason given for failure:
CSRF token missing or incorrect.
For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function uses RequestContext for the template, instead of Context.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.*
Where am I going wrong?
My views.py code is:
from django.shortcuts import render
from feedback.models import Test
from mysite.forms import TestForm
from django.http import HttpResponse
from django.template import Context, loader
def test_view(request):
form = TestForm
t = loader.get_template('form.html')
c = RequestContext(request,{'n':''})
if request.method=='POST':
form = TestForm(request.POST)
if form.is_valid():
in_name = request.POST.get("firstname")
fd = Test(name = in_name)
fd.save()
return HttpResponse(t.render(c))
My models.py code is:
from django.db import models
from django.forms import ModelForm
class Test(models.Model):
name = models.CharField(max_length=255)
class TestForm(ModelForm):
class Meta:
model = Test
fields = ['name']
My forms.py code is:
from django import forms
class TestForm(forms.Form):
name = forms.CharField()
My HTML template is:
<!DOCTYPE html>
<html>
<head>
<title>test form</title>
</head>
<body>
<form method = "POST">
{% csrf_token %}
First name:<br>
<input type="text" name="firstname" value = {{ n }}>
<br><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
You do it in a wrong, very PHPish, way.
Move the form definition from models.py to the forms.py, so your feedback/forms.py should be:
from django.forms import ModelForm
class TestForm(forms.ModelForm):
class Meta:
model = Test
fields = ['name']
The feedback/views.py should be simplified to:
from django.shortcuts import render, redirect
from feedback.forms import TestForm
def test_view(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
form.save()
return redirect('.')
else:
form = TestForm()
return render(request, 'form.html', {'form': form})
And the template:
<!DOCTYPE html>
<html>
<head>
<title>test form</title>
</head>
<body>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
</body>
</html>

Categories

Resources