Form errors - required field - python

I am building a CRUD app on Django.
I can create, read, and delete just fine, but the update function does not work. I have edited the views.py file (it was a template) to print the error.
Here are the relevant pieces of my code:
#models.py
from django.db import models
class Item(models.Model):
id = models.AutoField(primary_key=True)
etype = models.CharField(max_length=100)
etitle = models.CharField(max_length=100)
eauthor = models.CharField(max_length=100)
estatus = models.CharField(max_length=20)
class Meta:
db_table = "Item"
#views.py
...
def edit(request, id):
item = Item.objects.get(id=id)
return render(request,'edit.html', {'item':item})
def update(request, id):
item = Item.objects.get(id=id)
form = ItemForm(request.POST, instance = item)
print(form.errors)
if form.is_valid():
try:
form.save()
except Exception as e: print(e)
return redirect("/items/show")
return render(request, 'edit.html', {'item': item})
...
I guess the problem has to be in edit.html file, but I cannot figure it out.
#edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}"/>
</head>
<body>
<form method="POST" class="post-form" action="http://127.0.0.1:8000/items/update/{{item.id}}">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type:</label>
<div class="col-sm-4">
<input type="text" name="etype" id="id_etype" required maxlength="100" value="{{ item.etype }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Title:</label>
<div class="col-sm-4">
<input type="text" name="etitle" id="id_etitle" required maxlength="100" value="{{ item.etitle }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Author:</label>
<div class="col-sm-4">
<input type="text" name="eatuhor" id="id_eauthor" required maxlength="100" value="{{ item.eauthor }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Status:</label>
<div class="col-sm-4">
<input type="text" name="estatus" id="id_estatus" required maxlength="20" value="{{ item.estatus }}" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</div>
</form>
</body>
</html>
P.S: I am new to both Django and Software Development, so any kind of feedback is welcome.

I advise you to use UpdateView, its really easier.
Show here Click
Example views.py
class ItemUpdate(UpdateView):
model = Item
template_name = 'edit.html'
Example edit.html:
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
</form>

Related

How to add comment without refreshing the page itself in django

I was making a blog website, I am new to django and I don't know how to add comment without refreshing the page itself. I was trying to do with the help of tutorial but they are not helping anymore
here is my html file
<div class="row">
<div class="comment-section col-8">
{% for i in data %}
<li>{{i}}</li><br>
{% endfor %}
</div>
<div class="col-4">
<h4 class="m-3">{{comments.count}} Comments...</h4>
{% for j in comments %}
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{j.title}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{j.visitor.name}}</h6>
<p class="card-text">{{j.description}}</p>
</div>
</div>
{% endfor %}
<hr>
<h3>Comment here</h3>
<form method="post" id="comment-form">
{% csrf_token %}
<input type="hidden" id="contentId" name = 'contentId' value="{{ result.id }}">
<div class="form-group">
<input type="hidden" id="name" name="name" class="form-control" value="{{request.session.user.name}}" readonly>
</div>
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name="title" class="form-control">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" cols="30" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-secondary">Submit</button>
</form>
</div>
here is my views.py file
def addComment(request):
if request.method == 'POST':
post_id = request.POST['contentId']
title = request.POST['title']
description = request.POST['description']
user = request.session['user']['id']
con = Comment(
post_id=post_id,
title=title,
description=description,
visitor_id=user,
)
con.save()
print()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

Why aren't changes saved when editing a Django product?

Created a website with products. I need to make a window for editing them on the site in order to change the manufacturer and other characteristics. This must be done in a pop-up window. I have data displayed, I change it, but nothing changes when I save it. How can this problem be solved.
My vievs:
def parts(request):
added = ''
error = ''
PartAllView = Part.objects.order_by('-id')
if request.method == 'POST' and 'parts_add' in request.POST:
form = PartForm(request.POST, request.FILES)
if form.is_valid():
form.save()
added = 'Добавлено'
else:
error = 'Данная запчасть уже добавлена'
if request.method == 'POST' and 'parts_edit' in request.POST:
PartPost = int(request.POST['parts_edit'])
PartID = Part.objects.get(id=PartPost)
if PartID:
PartID.save()
added = 'Запчасть успешно отредактирована'
else:
error = 'Ошибка редактирования'
form = PartForm()
data = {
'added': added,
'error': error,
'form': form,
'PartAllView': PartAllView,
}
return render(request, 'kross/parts.html', data)
My HTML:
{% if PartAllView %}
{% for el in PartAllView %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal fade" id="partEdit{{ el.id }}">
<div class="modal-dialog modal-dialog-centered text-center" role="document">
<div class="modal-content modal-content-demo">
<div class="modal-header">
<h6 class="modal-title">Добавление запчасти</h6><button aria-label="Close" class="btn-close"
data-bs-dismiss="modal"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="row row-sm">
<div class="col-lg-6">
<div class="form-group">
<input type="text" class="form-control" name="brand" value="{{ el.brand }}">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<input type="text" class="form-control" value="{{ el.number }}">
</div>
</div>
<div class="col-lg-12">
<div class="form-group">
<input type="text" class="form-control" value="{{ el.name }}"><br>
<input type="textarea" class="form-control" rows="2" value="{{ el.description }}">
</div>
</div>
</div>
{{ el.analog }}
...
You can use updateView to edit an existing data in your website by simply:
from django.views.generic.edit import UpdateView
From MyApp models import #Model
class editview(UpdateView):
model = #Your Model You want to edit
fields = [#Add the fields you want to edit]
template_name = 'edit.html'
success_url = ('Home')
In your edit Template add:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
I hope it help.

Django template context won't render

Hi I am trying to make a form submission app that just displays the entered information back to the user underneath the form they submitted. Unfortunately, I can't seem to load the context on the front end within the template.
Template:
You'll see under the form there is a for loop that is supposed to iterate the context, but nothing displays. I tried it with just email for now, but it does not work.
<!DOCTYPE html>
<html>
<head>
<title>Form Practice</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<form style="margin-top: 600px;" method="post" action="/form">
{% csrf_token %}
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label" >Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3" placeholder="Email" name="email">
</div>
</div>
<div class="form-group row">
<label for="inputPassword3" class="col-sm-2 col-form-label" >Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
<fieldset class="form-group">
<div class="row">
<legend class="col-form-label col-sm-2 pt-0">Radios</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked>
<label class="form-check-label" for="gridRadios1">
First radio
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2">
<label class="form-check-label" for="gridRadios2">
Second radio
</label>
</div>
</div>
</div>
</fieldset>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="customCheck1" name="check">
<label class="custom-control-label" for="customCheck1">Check this custom checkbox</label>
</div>
<select class="custom-select mr-sm-2 custom-select-lg mb-3" name="select" id="inlineFormCustomSelect">
<option selected>Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="custom-control custom-radio">
<input type="radio" id="customRadio1" name="customRadio" class="custom-control-input">
<label class="custom-control-label" for="customRadio1">Toggle this custom radio</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="customRadio2" name="customRadio" class="custom-control-input">
<label class="custom-control-label" for="customRadio2">Or toggle this other custom radio</label>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="customFile" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<button type="submit" class="btn-block btn btn-primary my-1">Submit</button>
</form>
{% for item in context %}
<h1>{{ item.email }}</h1>
{% endfor %}
</div>
<div class="col-md-2"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
views.py
def index(request):
try:
email = request.POST['email']
print(email)
password = request.POST['password']
print(password)
radio = request.POST['gridRadios']
print(radio)
select = request.POST['select']
print(select)
except:
print("error")
context = {'context': {'email': email, 'password': password, 'radio': radio, 'select': select}}
print(context)
return render(request, 'form.html', context)
Replace this:
{% for item in context %}
<h1>{{ item.email }}</h1>
{% endfor %}
To:
<h1>{{ context.email }}</h1>

Error message is not shown

An error message is not shown.I wrote in index.html
<main>
<div class="detailimg col-xs-8">
<div class="relative_ele">
<div class="container" id="photoform">
{% if form.errors %} 
<div class="alert alert-danger" role="alert">
 <p>At least 1 picture should be selected</p>  
</div>
{% endif %}
<form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="file_select btn-lg">
File Select1
<input type="file" name="image">
</span>
</label>
<input type="text" class="form-control" readonly="">  
</div>
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="btn-lg file_select">
File Select2
<input type="file" name="image2">
</span>
</label>
<input type="text" class="form-control" readonly="">  
</div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<div class="col-xs-offset-2">
<div class="form-group">
<input type="submit" value="SEND" class="form-control">
</div>
</div>
</form>
</div>
</div>
</div>
</main>
in views.py
#login_required
#csrf_exempt
def upload_save(request):
if request.method == "POST":
form = UserImageForm(request.POST, request.FILES)
if form.is_valid():
data = form.save(commit=False)
data.user = request.user
data.image = request.cleaned_data['image']
data.save()
else:
print(form.errors)
else:
form = UserImageForm()
return render(request, 'registration/photo.html', {'form': form})
In my current code, when I select no image and put "SEND" button & I select the 1~2 image and put "SEND" button,photo.html is shown.I wanna show error message
{% if form.errors %}
<div class="alert alert-danger" role="alert">
<p>At least 1 picture should be selected</p>
</div>
{% endif %}
when I select no image, but now my system is not an ideal one. Why can't I do it? I think if I select no image,{% if form.errors %} become true. Do I misunderstand it? How should I fix this?
<main>
<div class="detailimg col-xs-8">
<div class="relative_ele">
<div class="container" id="photoform">
{% if form.errors %} 
<div class="alert alert-danger" role="alert">
 <p>At least 1 picture should be selected</p>  
</div>
{% endif %}
<!--here change--><form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="file_select btn-lg">
File Select1
<!--here change--><input id="file1" type="file" name="image">
</span>
</label>
<input type="text" class="form-control" readonly="">  
</div>
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="btn-lg file_select">
File Select2
<!--here change--><input id="file2" type="file" name="image2">
</span>
</label>
<input type="text" class="form-control" readonly="">  
</div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<div class="col-xs-offset-2">
<div class="form-group">
<!--here channge --><input id="send" type="submit" value="SEND" class="form-control">
</div>
</div>
</form>
</div>
</div>
</div>
</main>
<script type="text/javascript" language="JavaScript">
window.onload = function () {
var a = document.getElementById("send");
var file1 = document.getElementById("file1");
var file2 = document.getElementById("file2");
a.onclick = function(){
if(file1.value=="" && file2.value==""){
alert ('You didn\'t choose any of the checkboxes!');
return false;
}
else {
return true;
}
}
}
</script>
Hope this will work

Regist form cannot be sent

Regist form cannot be sent.
I wrote in views.py
def login(request):
login_form = LoginForm(request.POST)
regist_form = RegisterForm(request.POST)
if login_form.is_valid():
user = login_form.save()
login(request, user)
context = {
'user': request.user,
'login_form': login_form,
'regist_form': regist_form,
}
return redirect('profile')
context = {
'login_form': login_form,
'regist_form': regist_form,
}
return render(request, 'registration/accounts/login.html', context)
in login.html
<body>
<ul class="top-menu">
<h3 class="login">Login</h3>
<div class="container">
<form action="{% url 'login' %}" method="post" role="form">
{% csrf_token %}
<div class="form-group">
<label class="email_form">Email</label>
<input for="id_email" name="email" type="text" value="" placeholder="Email" class="form-control"/>
</div>
<div class="form-group">
<label class="password_form">Password</label>
<input id="id_password" name="password" type="password" value="" minlength="8" maxlength="12" placeholder="Password" class="form-control"/>
</div>
<button type="submit" class="btn btn-primary btn-lg">Login</button>
<input name="next" type="hidden" value="{{ next }}"/>
</form>
</div>
</ul>
<div class="newaccount">
<h2>New Account registration</h2>
<form class="form-inline" action="{% url 'accounts:detail' %}" method="POST">
<div class="form-group">
<label for="id_username">Username</label>
{{ form.username }}
{{ form.username.errors }}
</div>
<div class="form-group">
<label for="id_email">Email</label>
{{ form.email }}
{{ form.email.errors }}
</div>
<div class="form-group">
<label for="id_password">Password</label>
{{ form.password1 }}
{{ form.password1.errors }}
</div>
<div class="form-group">
<label for="id_password">Password(conformation)</label>
{{ form.password2 }}
{{ form.password2.errors }}
<p class="help-block">{{ form.password2.help_text }}</p>
</div>
<button type="submit" class="btn btn-primary btn-lg">Regist</button>
<input name="next" type="hidden"/>
{% csrf_token %}
</form>
</div>
</body>
in forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['email'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password'].widget.attrs['classF'] = 'form-control'
in urls.py
urlpatterns = [
url(r'^login/$', views.login,name='login'),
]
No error happens in login form ,but in registration form all input field is not shown.I think RegisterForm cannot be sent, but I really cannot understand why all input field of LoginForm is ok although I send LoginForm by using same way of RegisterForm.
How should I fix this?What should I write it?
You're render HTML with login_form and register_form in your form HTML.
But you're trying to render with form var instead of register_form, so django doesn't know what to render.
If you try to render not-exist variable in django template engine, it just show Nothing at all. So there will be NO errors!
Change your HTML code like this:
<body>
<ul class="top-menu">
<h3 class="login">Login</h3>
<div class="container">
<form action="{% url 'login' %}" method="post" role="form">
{% csrf_token %}
<div class="form-group">
<label class="email_form">Email</label>
<input for="id_email" name="email" type="text" value="" placeholder="Email" class="form-control"/>
</div>
<div class="form-group">
<label class="password_form">Password</label>
<input id="id_password" name="password" type="password" value="" minlength="8" maxlength="12"
placeholder="Password" class="form-control"/>
</div>
<button type="submit" class="btn btn-primary btn-lg">Login</button>
<input name="next" type="hidden" value="{{ next }}"/>
</form>
</div>
</ul>
<div class="newaccount">
<h2>New Account registration</h2>
<form class="form-inline" action="{% url 'accounts:detail' %}" method="POST">
<div class="form-group">
<label for="id_username">Username</label>
{{ regist_form.username }}
{{ regist_form.username.errors }}
</div>
<div class="form-group">
<label for="id_email">Email</label>
{{ regist_form.email }}
{{ regist_form.email.errors }}
</div>
<div class="form-group">
<label for="id_password">Password</label>
{{ regist_form.password1 }}
{{ regist_form.password1.errors }}
</div>
<div class="form-group">
<label for="id_password">Password(conformation)</label>
{{ regist_form.password2 }}
{{ regist_form.password2.errors }}
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
<button type="submit" class="btn btn-primary btn-lg">Regist</button>
<input name="next" type="hidden"/>
{% csrf_token %}
</form>
</div>
</body>
This code will show your input tags.
And one thing more... Why don't you use login_form in your HTML?

Categories

Resources