django crispy form does not work in the template - django

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>

Related

Problems with a backend part of search line in Django

who can explain me why my SearchView doesn't work. I have some code like this.It doesn't show me any mistakes, but it doesn't work. The page is clear. Seems like it doesn't see the input.
search.html
<div class="justify-content-center mb-3">
<div class="row">
<div class="col-md-8 offset-2">
<form action="{% url 'search' %}" method="get">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search..." />
<div class="input-group-append">
<button class="btn btn-dark" type="submit" id="button-addon2">Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
search/urls.py
path('search/', SearchView.as_view(), name='search')
search/views.py
class SearchView(ListView):
model = Question
template_name = 'forum/question_list.html'
def get_queryset(self):
query = self.request.GET.get("q")
object_list = Question.objects.filter(
Q(title__icontains=query) | Q(detail__icontains=query)
)
return object_list
forum/question_list.html
{% extends 'main/base.html' %}
{% block content %}
{% for question in object_list %}
<div class="card mb-3">
<div class="card-body">
<h4 class="card-title">{{ question.title }}</h4>
<p class="card-text">{{ question.detail }}</p>
<p>
{{ question.user.username }}
5 answers
10 comments
</p>
</div>
</div>
{% endfor %}
{% endblock %}

Manually rendered form fields do not save data

I really wanted to figure this out myself and I spent over 4 hours on the subject but I give up now.
I have a form that is supposed to save data, and if I lay out the form with the {{ form }} tag everything works great. If I put in to form with individual tags like {{ form.client_email }}, the form data is not saved to the database.
I need to render these fields manually for front end purposes but I just couldn't figure out how to do it.
I appreciate your help a lot.
Here is my code.
views.py
def client_list_view(request):
if request.method == 'POST':
form = ClientModelForm(request.POST)
if form.is_valid():
client_title = form.cleaned_data["client_title"]
client_email = form.cleaned_data["client_email"]
client_turkishid_no = form.cleaned_data["client_turkishid_no"]
client_tax_no = form.cleaned_data["client_tax_no"]
client_tax_office = form.cleaned_data["client_tax_office"]
client_contactperson = form.cleaned_data["client_contactperson"]
client_phone_number = form.cleaned_data["client_phone_number"]
Client.objects.create(
client_title=client_title,
client_email=client_email,
client_turkishid_no=client_turkishid_no,
client_tax_no=client_tax_no,
client_tax_office=client_tax_office,
client_contactperson=client_contactperson,
client_phone_number=client_phone_number
).save()
return redirect("books:client-list")
else:
form = ClientModelForm()
client_list = Client.objects.all().order_by("client_title")
context = {'client_list' : client_list, "form": ClientModelForm}
return render(request, 'clients/client_list.html', context=context)
Working template
<div id="clientModal" class="modal bottom-sheet">
<div class="modal-content">
<form method="POST">
{% csrf_token %}
{{form}}
<button class="btn">Ekle</button>
</form>
</div>
</div>
Not Working Template
<div id="clientModal" class="modal bottom-sheet">
<div class="modal-content">
<div class="row">
<div class="col s12">
<ul class="tabs">
<li class="tab col m6"><a class="active" href="#gercek">Gerçek Kişi</a></li>
<li class="tab col m6"><a class="active" href="#tuzel">Tüzel Kişi</a></li>
</ul>
</div>
<div id="gercek" class="col s12">
<div class="col s12 m12 l12">
<div id="inline-form" class="scrollspy">
<div class="card-content">
<form method="POST">
{% csrf_token %}
<div class="row">
<div class="input-field col m4 s12">
<i class="material-icons prefix">email_outline</i>
{{form.client_email}}
<label for="{{ form.client_email.id_for_label }}">Müvekkilin E-Posta Adresi</label>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="tuzel" class="col s12">
<div class="col s12 m12 l12">
<div id="inline-form" class="scrollspy">
<div class="card-content">
<form method="POST">
{% csrf_token %}
<div class="row">
<div class="input-field col m4 s12">
<i class="material-icons prefix">account_circle</i>
{{form.client_title}}
<label for="{{ form.client_title.id_for_label }}">Müvekkilin Unvanı</label>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
In your "not working" template you wrap each of individually rendered field with a form tag. That's not the correct way to do what you need. Just keep one form tag like you do in the working template and render all fields inside:
<div id="clientModal" class="modal bottom-sheet">
<div class="modal-content">
<form method="POST">
{% csrf_token %}
<!-- put your fields here with any additional markup you need -->
{{ form.client_email }}
<label for="{{ form.client_email.id_for_label }}">Müvekkilin E-Posta Adresi</label>
{{ form.client_title }}
<label for="{{ form.client_title.id_for_label }}">Müvekkilin Unvanı</label>
<!-- by the way you can use form.<field>.label_tag -->
{{ form.client_phone_number }}
{{ form.client_phone_number.label_tag }}
<!-- and maybe you'd also like to render errors -->
{{ form.client_phone_number.errors }}
<button class="btn">Ekle</button>
</form>
</div>
</div>
Also, the ClientModelForm seems to be an instance of ModelForm, so you do not need to deal with form.cleaned_data manually. For new objects you can just call form.save(commit=True):
if form.is_valid():
form.save(commit=True)

Django Error message displays behind text box

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

How to combine any fields in one in Django filters

I wonder how you combine search from multiple fields into one. The fields would be textoQuestao, perguntaQuestao, aOpcao, bOpcao, cOpcao, eOpcao, eOpcao.
I would like all of these fields to be combined into one called texto and to search all selected fields.
filters.py
class FiltroQuestoes(django_filters.FilterSet):
texto =
class Meta:
model = Questao
fields = ['textoQuestao','perguntaQuestao','aOpcao','bOpcao','cOpcao','dOpcao','eOpcao','idProva','idQuestao','idCategoria']
views.py
def FiltroDeQuestoesView(request):
qs = filter(request)
context = {
'queryset': qs,
'categorias': Categoria.objects.all(),
'provas': Prova.objects.all()
}
return render(request, "polls/pesquisa.html", context)
def filter(request):
qs = Questao.objects.all()
categorias = Categoria.objects.all()
prova = request.GET.get('prova')
provas = Prova.objects.all()
questao = request.GET.get('questao')
categoria = request.GET.get('categoria')
return qs
search.html
{% block content %}
<form method="get">
<div class="well">
<h4 style="margin-top: 0">Filter</h4>
<div class="row">
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.texto.label_tag }}
{% render_field filter.form.texto class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.idProva.label_tag }}
{% render_field filter.form.idProva class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.idQuestao.label_tag }}
{% render_field filter.form.idQuestao class="form-control" %}
</div>
<div class="form-group col-sm-4 col-md-3">
{{ filter.form.idCategoria.label_tag }}
{% render_field filter.form.idCategoria class="form-control" %}
</div>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</form>
{% endblock %}
I would suggest you should go with elasticsearch for this.
But you can use django Q objects to do OR query
qs = Questao.objects.filter(Q(textoQuestao__icontains=query_string)| Q(perguntaQuestao__icontains=query_string)|...

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>