Django Error message displays behind text box - django

I have a custom error validation displayed, however, the message is displayed behind the next input box.
How can I change the error message to either be a popup, or the message display inside the text box, or some other way that I can see the text?
This is my forms.py
class ProductForm(ModelForm):
prod_code = forms.CharField(label=False,error_messages={'unique': 'This is unique'})
prod_descr = forms.CharField(label=False)
supplier = forms.ChoiceField(choices=suppliers, label=False, required=False)
list_price = forms.DecimalField(label=False, required=False)
serialsed_item = forms.ChoiceField(choices=YesNo, label=False, required=False)
category = forms.ChoiceField(choices=categories, label=False, required=False)
class Meta:
model = Product
fields = '__all__'
helper = FormHelper()
helper.layout = Layout(Field('text_input', css_class='form-control-lg'),)
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_show_labels = False
This is my template :
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block page_head %}Add Product{% endblock %}
{% block navbar %}
<navbar class="mr-auto">
<div class="container-fluid">
<ul class="nav navbar-expand">
<li>
<button type="submit" form="p-form" class="btn btn-outline-secondary">Add Product</button>
<button class="btn btn-outline-secondary" onclick="document.location='{% url 'prodlist' %}'">Close Without Saving</button>
</li>
</ul>
</div>
</navbar>
{% endblock %}
{% block content %}
<form id="p-form" action="{% url 'newproduct' %}" method="post">
<!--
{{form.prod_code|as_crispy_field}}
{{form.prod_descr|as_crispy_field}}
{{form.supplier|as_crispy_field}}
{{form.list_price|as_crispy_field}}
{{form.category|as_crispy_field}} -->
{% csrf_token %}
<div class="container-fluid ">
<div class="row">
<div class="col-6 ">
<div class="row">
<div class="col-3">Product Code</div>
<div class="col-8" >{{form.prod_code|as_crispy_field}}</div>
<div class="col-1"></div>
</div>
<div class="row">
<div class="col-3">Prod Descr</div>
<div class="col-8">{{form.prod_descr|as_crispy_field}}</div>
<div class="col-1"></div>
</div>
<div class="row">
<div class="col-3">Supplier</div>
<div class="col-8">{{form.supplier|as_crispy_field}}</div>
<div class="col-1"></div>
</div>
</div>
<div class="col-6 ">
<div class="row ">
<div class="col-4">List Price</div>
<div class="col-8">{{form.list_price|as_crispy_field}}</div>
</div>
<div class="row">
<div class="col-4">Serialsed Item</div>
<div class="col-8">{{form.serialsed_item|as_crispy_field}}</div>
</div>
<div class="row">
<div class="col-4">Category</div>
<div class="col-8">{{form.category|as_crispy_field}}</div>
</div>
</div>
</div>
</div>
</form>
{% endblock content %}
Error message :
Error message

Related

django crispy form does not work in the template

I'm trying to make my form-fields to be in a row like this html code down below, but it does not work, I want all the fields in the PrimryForm class to be in a row not in a column:
Html code:
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col">
<div class="form-group">
<input type="text" class="form-control">
</div>
</div>
<div class="col">
<div class="form-group">
<input type="text" class="form-control">
</div>
</div>
<div class="col">
<div class="form-group">
<input type="text" class="form-control">
</div>
</div>
</div>
</div>
Forms.py file:
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Row, Column
class PrimaryForms(forms.ModelForm):
signature_of_student = JSignatureField(
widget=JSignatureWidget(
jsignature_attrs={'color':'#e0b642', 'height':'200px'}
)
)
signature_of_guardian = JSignatureField(
widget=JSignatureWidget(
jsignature_attrs={'color':'#e0b642', 'height':'200px'}
)
)
date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
class Meta:
model = Primary
fields = ['admission_number', 'profile_picture', 'first_name',
'last_name', 'gender', 'address_of_student', 'class_Of_student',
'comment_of_student',
'year_of_graduation', 'date_of_birth', 'religion', 'mother_name', 'signature_of_student',
'relationship', 'signature_of_guardian']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-md-3'
self.helper.field_class = 'col-md-9'
My Form/template:
{% load crispy_forms_tags %}
<div class="container">
<div class="row justify-content-center">
<div class="col">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% crispy form %}
<br>
<button type="submit" class="btn btn-primary">Create Student</button>
</form>
</div>
</div>
</div>
How can I do this using django-crispy-form?
I solve my problem using boostrap-5 ROW and COLUMN in the template
from this template:
{% load crispy_forms_tags %}
<div class="container">
<div class="row justify-content-center">
<div class="col">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{% crispy form %}
<br>
<button type="submit" class="btn btn-primary">Create Student</button>
</form>
</div>
</div>
</div>
To This:
{% load crispy_forms_tags %}
<br>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
<div class="form-group row">
<div class="col">
{{form.admission_number|as_crispy_field}}
</div>
<div class="col">
{{form.profile_picture|as_crispy_field}}
</div>
<div class="col">
{{form.first_name|as_crispy_field}}
</div>
<div class="col">
{{form.last_name|as_crispy_field}}
</div>
</div>
<div class="tex-center">
<button type="submit" class="btn btn-primary btn-lg">Create Student</button>
</div>
</div>
</form>

how to put my form in line orientation (horizontal). django forms

I want to put my form in horizontal.I tried to do this, but it got unformatted and disorganized
MY HTML:
<div class="tab-pane fade container-fluid p-2" id="profile" role="tabpanel"
aria-labelledby="profile-tab">
<h6 class="m-0 font-weight-bold text-primary">Horas Adicionais</h6>
<div class="row mt-4">
<div class="col">
{{ form_funcionarioadicional.management_form }}
{% for fa in form_funcionarioadicional %}
<div class="faform row">
<div class="col">
{{fa}}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
currently it is like this, I wanted to leave it horizontal
How can I fix this in html, or in forms.py?
You can iterate form like this with col class of Bootstrap...
views.py
def Demoview(request):
form = DemoForm()
context = {'form':form}
return render(request,'index.html',context)
form.py
class DemoForm(forms.ModelForm):
class Meta:
model = DemoClass
fields = "__all__"
widgets = {
'field1':forms.TextInput(attrs={'class':'form-control','placeholder':'Field1'}),
'field2':forms.NumberInput(attrs={'class':'form-control','placeholder':'Field2'}),
'field3':forms.EmailInput(attrs={'class':'form-control','placeholder':'Field3'}),
'field4':forms.TextInput(attrs={'class':'form-control','placeholder':'Field4'}),
}
HTML Code
{% block body %}
<div class="container-fluid">
<div class="row">
{% for fm in form %}
<div class="col-6">
<label >{{fm.label}}</label>
{{fm}}
</div>
{% endfor %}
</div>
</div>
{% endblock body %}
Output

My for loop does not work as expected - Data does not show up in my django template

I am trying to use a for loop in my Django template to show the data stored in the models of a table but for some reason , the data does not show up in the template.
Views.py
def add_part(request):
parts = Parts.objects.all()
context = {
"parts": parts
}
return render(request, 'admintemplate/add_parts_template.html', context)
def add_part_save(request):
if request.method != "POST":
messages.error(request, "Method Not Allowed!")
return redirect('add_part')
else:
part_name = request.POST.get('part_name')
part_type = request.POST.get('part_type')
supplier_id = request.POST.get('suppliers')
suppliers = Suppliers.objects.get(id=supplier_id)
try:
part = Parts(part_name=part_name, part_type=part_type, supplier_id=supplier)
part.save()
messages.success(request, "Part Added Successfully!")
return redirect('add_part')
except:
messages.error(request, "Failed to Add Part!")
return redirect('add_part')
models.py
The parts and the services model are exactly the same with different column names, so I think the functionality for both should be the same.
Suppliers models
class Suppliers(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
Parts model
class Parts(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
part_type = models.CharField(max_length=20)
supplier_id = models.ForeignKey(Suppliers, on_delete=models.CASCADE)
Services model
class Services(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
service_type = models.CharField(max_length=20)
supplier_id = models.ForeignKey(Suppliers, on_delete=models.CASCADE)
Part template
{% extends 'admintemplate/base_template.html' %}
{% block page_title %}
Add Parts
{% endblock page_title %}
{% block main_content %}
{% load static %}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Add Parts</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form role="form" method="POST" action="{% url 'add_part_save' %}">
{% csrf_token %}
{% comment %} Display Messages {% endcomment %}
{% if messages %}
<div class="form-group">
<div class="col-12">
{% for message in messages %}
{% if message.tags == "error" %}
<div class="alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% elif message.tags == "success" %}
<div class="alert alert-success alert-dismissible fade show" role="alert" style="margin-top: 10px;">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
<div class="card-body">
<div class="form-group">
<label>Part Name </label>
<input type="text" class="form-control" name="part_name" placeholder="Part Name">
</div>
<div class="form-group">
<label>Part Type </label>
<input type="text" class="form-control" name="part_type" placeholder="Part Type">
</div>
<div class="form-group">
<label>Supplier Name</label>
<select class="form-control" name="suppliers">
{% for supplier in suppliers %}
<option value="{{ supplier.id }}">{{ supplier.name }}</option>
{% endfor %}
</select>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Add Part</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
</div>
</div><!-- /.container-fluid -->
</section>
{% endblock main_content %}
Now the services in parts template does not show up at all. There is no choices on the form. But, for the add services template, it does populate. I have no idea why this happens because I have used the exact same code for both templates.
Changing the view to this solved the issue
def add_part(request):
parts = Parts.objects.all()
context = {
"suppliers": suppliers
}
return render(request, 'admintemplate/add_parts_template.html', context)

My comment reply function is not working?

I am making a blog but I am stuck on a comment replies function. I don't know how to make a Reply function from which users can reply to the comments. I tried a lot but it's still displaying those comments like other comments not as replies to that specific comment.
Here,s the models.py
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments")
name = models.CharField(max_length = 200)
body = models.TextField(default = True)
pub_date = models.DateTimeField(auto_now_add = True)
reply = models.ForeignKey('Comment',null = True,blank = True,on_delete=models.CASCADE)
class Meta:
ordering = ['-pub_date']
def __str__(self):
return self.name
#property
def get_replies(self):
return self.replies.all()
class Reply(models.Model):
post = models.ForeignKey(Comment,on_delete=models.CASCADE,related_name = "replies")
name = models.CharField(max_length = 200)
body = models.TextField(default = True)
Here's the views.py
def BlogDetail(request,pk):
post = get_object_or_404(Post,pk = pk)
comment = CommentForm(request.POST or None)
subscribe = Subscribe()
reply = ReplyForm(request.POST or None)
if request.method == 'POST':
subscribe = Subscribe(request.POST)
comment = CommentForm(request.POST)
reply = ReplyForm(request.POST)
if comment.is_valid():
comment.instance.post = post
comment.save()
elif subscribe.is_valid():
subscribe = subscribe.save(commit = True)
return redirect('index')
elif reply.is_valid():
reply.instance.com = com
reply = reply.save(commit = True)
return redirect('index')
return render(request,'app/blog.html',{'blog_object':post,'comment':comment,
'subscribe':subscribe,'reply':reply,
})
Here,s the blog.html
<form method='POST' action=".">
{%csrf_token%}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-4">
<div class="col-inner ts-20 m-sm">
<input type="submit" value="Subscribe to my daily letter" class="btn btn-primary subscribe">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-8">
<div class="ts-20">
<div class="form-group form-group-with-icon comment-form-email">
{{subscribe.email}}
</form>
<div class="form-control-border"></div>
</div>
</div>
</div>
</div>
<h3 style="color: #ff714a; font-weight:300;">
Leave a comment
</h3>
{% if request.user.is_authenticated %}
<div class="comments">
<div class="row">
<div class="container">
</div>
<form action="." method="post" id="commentform" class="comment-form">
{% csrf_token %}
<div class="col">
<div class="form-group form-group-with-icon comment-form-email">
{{comment}}
<div class="form-control-border"></div>
</div>
</div>
<div class="col">
<p class="form-submit">
<input name="submit" type="submit" id="submit" class="submit" value="Post Comment">
</p>
</div>
</form>
</div>
{% endif %}
<div class="post-comments">
<h3 style="color: #ff714a; font-weight:300;">See the latest comments</h3>
{% for comment in blog_object.get_comments %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{comment.name}}</strong>
<div class="col comment_body">
<p>{{comment.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
</div>
<form action="." method='POST'>
{% csrf_token %} {{reply}}
<input type="submit" value="submit">
</form>
{% endfor %} {% for reply in com.get_replies %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{reply.name}}</strong>
<div class="col comment_body">
<p>{{reply.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
<div class="reply">
</div>
</div>
</form>
{% endfor %}
</div>

Django Form doesn't Get Correct Columns

I have struggled with this for about an hour and cannot seem to find a solution.
I have a django model that I have created form with using ModelForm. The form is inside a view and I want to manipulate the form variables before submitting to the database. The problem is that I cannot seem to get the correct columns to reference from the database for the form. Instead it looks like it is referencing the columns from another related table. Any suggestions?
Models
class RoutinePlans(models.Model):
routine = models.ForeignKey(Routines, on_delete='CASCADE')
exercise = models.ForeignKey(WeightExercises, on_delete='PROTECT')
set = models.IntegerField()
set_type = models.ForeignKey(SetType, on_delete='PROTECT')
reps = models.IntegerField()
day = models.IntegerField()
week = models.IntegerField()
def __str__(self):
return self.routine.name
class Routines(models.Model):
name = models.CharField(max_length=50)
level = models.ForeignKey(RoutineLevels, on_delete='PROTECT')
creator = models.ForeignKey(User, on_delete='CASCADE')
status = models.TextField(max_length=50)
description = models.TextField(max_length=255, null='TRUE', default=None)
def __str__(self):
return self.name
Forms
class PlanForm(forms.ModelForm):
DAY_CHOICES = (('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'))
day = forms.ChoiceField(widget=forms.Select, choices=DAY_CHOICES)
class Meta:
model = RoutinePlans
exclude = ['routine']
Views
#not sure if this view would have anything to do with the error but figured I would include it to give the full perspective
def createplan(request):
form = forms.CreatePlan()
if request.method == 'POST':
form = forms.CreatePlan(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.name = request.POST['name']
obj.creator_id = request.user.id
obj.status = "DRAFT"
obj.save()
return redirect('fitnessmanagement:editplan', id=obj.pk)
else:
print('error form invalid')
variables = {'form': form}
return render(request, template_name='createplan.html', context=variables)
def editplan(request, routine_id):
form = forms.PlanForm()
routine_name = Routines.objects.get(id=routine_id).name
if request.method == 'POST':
form = forms.PlanForm(data=request.POST)
if form.is_valid():
obj = form.save(commit=False)
#this is where I want to put obj.routine but the form will only pull fields from the Routines model and not the Routine Plans
obj.save()
return redirect('fitnessmanagement:editplan', routine_id=routine_id)
# variables to populate plan
plan = RoutinePlans.objects.filter(routine_id=routine_id)
plan_weeks = RoutinePlans.objects.filter(routine_id=routine_id).values('week').distinct()
plan_dayss = RoutinePlans.objects.filter(routine_id=routine_id).values('day', 'week').distinct()
plan_excercise_name = RoutinePlans.objects.filter(routine_id=routine_id).values('day', 'week', 'exercise_id', 'set_type_id').distinct()
plan_excercise = RoutinePlans.objects.filter(routine_id=routine_id).prefetch_related('exercise')
names = WeightExercises.objects.all()
setDetails = RoutinePlans.objects.filter(routine_id=routine_id).values('set', 'reps', 'day', 'week', 'exercise', 'set_type')
set_type = SetType.objects.all()
# end variables to populate plan
variables = {'form': form,
'id': routine_id,
'routine_name':routine_name,
'plan': plan,
'plan_weeks': plan_weeks,
'plan_exercises': plan_excercise,
'plan_exercise_name': plan_excercise_name,
'plan_days': plan_dayss,
'setDetails': setDetails,
'names': names,
'set_type': set_type,
}
return render(request, template_name='editplan.html',context=variables)
Templates
{% extends 'layout/master-layout.html' %}
{% load static %}
{% block content %}
<section id="content">
<!--start container-->
<div class="container">
<div class="row">
<div class="col s12 m6 l4">
<div class="card-panel">
<h4 class="header2">Add Workout</h4>
<div class="row">
<form class="col s12" method="POST">
{% csrf_token %}
<div class="row">
<div class="input-field col s12">
{{ form.week }}
<label for="weekNumber">Week Number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.day }}
<label for="dayNumber">Day Number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.exercise }}
<label for="exercise_name">Exercise Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.set_type }}
<label for="set_type">Set Type</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.set }}
<label for="set">Set Number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.reps }}
<label for="reps">Rep Number</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
{{ form.routine }}
<label for="routine">Routine</label>
</div>
</div>
<div class="row">
<div class="row">
<div class="input-field col s12">
<button class="btn waves-effect waves-light right trusique-red"
type="submit" name="submit">Add Workout
<i class="material-icons right">send</i>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col s12 m6 l8">
<div class="card-panel">
<h4>Editing: {{ routine_name }}</h4>
<ul class="collapsible" data-collapsible="expandable">
{% for plan_week in plan_weeks %}
<li>
<div class="collapsible-header"><i
class="material-icons">whatshot</i>{{ plan_week.week }}- Week
</div>
<div class="collapsible-body">
<ul class="collapsible" data-collapsible="expandable">
{% for plan_day in plan_days %}
{% if plan_day.week == plan_week.week %}
<li>
<div class="collapsible-header">{{ plan_day.day }}- day</div>
<!--collapsible workout name body -->
<div class="collapsible-body">
<ul class="collapsible" data-collapsible="expandable">
<!--begin workout name list-->
{% for plan_exercise in plan_exercise_name %}
{% for n in names %}
{% for s in set_type %}
{% if plan_day.day == plan_exercise.day and plan_week.week == plan_exercise.week and plan_exercise.exercise_id == n.id and plan_exercise.set_type_id == s.id%}
<li>
<div class="collapsible-header">{{ n.exercise_name }}-
Excercise {{ s.type }}
</div>
<div class="collapsible-body">
{% for setDetail in setDetails|dictsort:"set" %}
{# <p> setdetails exerceice {{ setDetail.exercise }}#}
{# plan excerice {{ plan_exercise.id }}</p>#}
{% if plan_day.day == setDetail.day and plan_week.week == setDetail.week and plan_exercise.exercise_id == setDetail.exercise and s.id == setDetail.set_type %}
<div class="row">
<div class="col s12 m4 l4">
Set {{ setDetail.set }}
</div>
<div class="col s12 m4 l4">
: {{ setDetail.reps }}Reps
</div>
</div>
{% endif %}
{% endfor %}
</div>
</li>
{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
</ul>
</div>
</li>
{% endif %}
{% endfor %}
</ul>
</div>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
<!--end container-->
</section>
<!-- END CONTENT -->
{% endblock %}