django-ckeditor {{ form.media }} not working in html - html

I am trying to get ck-editor look from forms.py .
After reading docs and even on YouTube, I didn't get my desired result.
I am sharing my different file.
Please solve this.
HTML FILE
<form method="post" enctype="multipart/form-data">
<div class="col me-2">
{% csrf_token %}
{{ notes_form.media }}
{{ notes_form.as_p }}
</div>
<div class="col-auto">
<button class="btn btn-outline-success btn-sm border rounded-pill border-success float-end todo-submit" type="button">
<i class="fas fa-check"></i>
</button>
</div>
</form>
Form.py
class NotesForm(ModelForm):
class Meta:
model = Notes
fields = ['description']
def __init__(self, *args, **kwargs):
super(NotesForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
views.py
def index(request):
if request.user.is_authenticated:
params = {
"notes_form": NotesForm()
}
return render(request, 'dashboard.html', params)
else:
return render(request, 'home.html')
output (html file)
output image

Actually I got the solution.
when you call {{ notes_form.media }}, it load script files i.e. <script src="/assets/ckeditor/ckeditor-init.js"></script><script src="/assets/ckeditor/ckeditor/ckeditor.js"></script>. Due to this JavaScript load first and it didn't get the textarea which appear (due to) {{ notes_form.as_p }} after this.
HTML file
<form method="post" enctype="multipart/form-data">
<div class="col me-2">
{% csrf_token %}
{{ notes_form.media }}
{{ notes_form.as_p }}
</div>
<div class="col-auto">
<button class="btn btn-outline-success btn-sm border rounded-pill border-success float-end todo-submit" type="button">
<i class="fas fa-check"></i>
</button>
</div>
</form>
updated HTML file
<form method="post" enctype="multipart/form-data">
<div class="col me-2">
{% csrf_token %}
{{ notes_form.as_p }}
{{ notes_form.media }}
</div>
<div class="col-auto">
<button class="btn btn-outline-success btn-sm border rounded-pill border-success float-end todo-submit" type="button">
<i class="fas fa-check"></i>
</button>
</div>
</form>

Related

How to prevent Modal from hiding when submitting if there is an error in the form?

when I click the Add User button the modal is hiding even if the form has errors. If I reopen the modal the error messaged are there, I need to show the error messaged and not close the modal if the there is an error message.
I think I can use the {{form.errors}} to verify if there is an error message. But I don’t know how?
<div class="card-body d-flex justify-content-between">
<h4 class="box-title">Users</h4>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#add_user" data-whatever="" >Add a user</button>
<div class="modal fade" id="add_user" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h1 class="h3 mb-3 fw-normal text-center" id="exampleModalLabel">Create Account</h1>
</div>
<div class="modal-body">
<form action="" method="POST">
{% csrf_token %}
<div class="form-floating">
{{ form.username }}
<span class="text-danger">{{ form.errors.username }}</span>
</div>
<div class="form-floating">
{{ form.email }}
<span class="text-danger">{{ form.errors.email }}</span>
</div>
<div class="form-floating">
{{ form.password1 }}
<span class="text-danger">{{ form.errors.password1 }}</span>
</div>
<div class="form-floating">
{{ form.password2 }}
<span class="text-danger ">{{ form.errors.password2 }}</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button class=" btn btn-primary" type="submit" >Add User</button>
</div>
</div>
</form>
</div>
</div>
</div>
I used to the Django form for validation and error messages.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username','class': 'form-control mb-3',}))
email = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email','class': 'form-control mb-3',}))
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password','class': 'form-control mb-3',}))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password','class': 'form-control mb-3',}))
my function in views.py looks like this
#login_required(login_url= 'login')
#staff_member_required(login_url='home')
def dashboard(request):
User = get_user_model()
users = User.objects.all()
form = CustomUserCreationForm()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('dashboard')
context = {
'users' : users,
'form': form
}
return render(request, 'dashboard.html', context)
is there any solutions for this?
Simplest way to do it is to add if statement in modal div class:
<div class="modal fade {% if form.errors %}show{% endif %}" ...>
Sorry this is wrong! I did it withouth thinking. Sorry.
Correct answer:
Add this to your template (on bottom or top):
{% if form.errors %}
<script>
$(document).on('ready', function(){
$('#add_user').modal('show');
});
</script>
{% endif %}
This will invoke show on your modal at page load.
Another way to do it is somekind of validation with ajax or maby htmx(without reloading page)

Django ask for fill a form not required

I've a strange bug with my forms.
In a page I must hande 2 separate forms,
the 1st one have no problem at all and I can add the record in DB ,
the 2nd one raise me an error asking to fill a required data of 1st form.
The POST dictionary looks ok
Here the log:
<QueryDict: {'csrfmiddlewaretoken': ['lvt5Ph2SA1xxFK4LMotdHOWk2JuZzYDo0OKWc77rKICYKYmemy3gl0dBphnRNcFb'], 'pk_atto': ['1.1'], 'pk_persona': ['1'], 'capacita': ['11'], 'Aggiungi_persona': ['persona'], 'tipo': ['fondo']}>
<ul class="errorlist"><li>pk_particella<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
the views:
if request.method == 'POST':
if("Aggiungi_particella" in request.POST):
save_atto = AttiPartenzeParticelleForm(request.POST)
else:
save_atto = AttiPartenzePersoneForm(request.POST)
print(request.POST)
print(save_atto.errors)
if save_atto.is_valid():
save_atto.save()
return redirect('/aggiungi_atto_partenza' + '/' + str(save_atto['pk_atto'].value()))
the forms:
class AttiPartenzeParticelleForm(ModelForm):
pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
pk_particella = forms.ModelChoiceField(queryset=Particelle.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
capacita = forms.CharField(max_length=30,
widget=forms.NumberInput
(attrs={'class': 'form-control'}))
tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'}))
class Meta:
model = Acquisizioni_Cessioni_particella
fields = '__all__'
class AttiPartenzePersoneForm(ModelForm):
pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
pk_persona = forms.ModelChoiceField(queryset=Persone.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
capacita = forms.CharField(max_length=30,
widget=forms.NumberInput
(attrs={'class': 'form-control'}))
tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'}))
class Meta:
model = Acquisizioni_Cessioni_particella
fields = '__all__'
and the HTML
<div id="particella" class="content-section d-flex justify-content-center mt-5">
<form action="" method="POST" id="particella_f">
{% csrf_token %}
<fieldset class="form-group">
<div style="visibility:hidden">
{{ form.pk_atto|as_crispy_field }}
</div>
<div class="row">
<div class="col-8">
{{ form.pk_particella|as_crispy_field }}
</div>
<div class="col-2">
{{ form.capacita|as_crispy_field }}
</div>
<div class="col-4 d-flex justify-content-center">
<button form="particella_f" class="btn btn-outline-primary btn-lg mt-5" type="submit" name="Aggiungi_particella" value="particella">
AGGIUNGI PARTICELLA
</button>
</div>
<div style="visibility:hidden">
{{ form.tipo|as_crispy_field }}
</div>
</div>
</fieldset>
</form>
</div>
<div id="persona" class="content-section d-flex justify-content-center mt-5">
<form action="" method="POST" id="persona_f">
{% csrf_token %}
<fieldset class="form-group">
<div style="visibility:hidden">
{{ persona.pk_atto|as_crispy_field }}
</div>
<div class="row">
<div class="col-8">
{{ persona.pk_persona|as_crispy_field }}
</div>
<div class="col-2">
{{ persona.capacita|as_crispy_field }}
</div>
<div class="col-4 d-flex justify-content-center">
<button class="btn btn-outline-primary btn-lg mt-5" form="persona_f" type="submit" name="Aggiungi_persona" value="persona">
AGGIUNGI PERSONA
</button>
</div>
<div style="visibility:hidden">
{{ form.tipo|as_crispy_field }}
</div>
</div>
</fieldset>
</form>
</div>
soneone have any idea?
thx

How to Create search function in Flask using Sqlite3

This is my form for search function
<form class="form-inline ml-auto" action="{{ url_for('search') }}" method="POST">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id="search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
Now I wan to display it if its match so this is my html
{% for articles in data %}
<div class="card m-3">
<input type="hidden" value="{{ data[0] }}" id="id" name="id">
<h5 class="card-header">{{ data[0] }}</h5>
<div class="card-body">
<h5 class="card-title">{{ data[2] }} - {{ data[3] }}</h5>
<p class="card-text">{{ data[4] }}</p>
</div>
<div class="row m-3 ml-auto">
<div class="btn-group mr-2">
Update Article
</div>
<div class="btn-group">
Delete Article
</div>
</div>
</div>
{% endfor %}
And also this is my query filter
#app.route('/search',methods = ['POST', 'GET'])
def search_route():
if request.method == 'POST':
q= request.args.get('search')
with sqlite3.connect("blogdb.db") as con:
cur = con.cursor()
cur.execute('SELECT * FROM articles WHERE title = ?', (q))
art = cur.fetchall()
cur.close()
print(art[0])
con.commit()
return render_template('search.html', data = art[0])
So far what I got is that it doesnt return anything I also tried to print(art[0]) so that I can see what did i get but i aint getting anything.

Can I match the height of a formset input with a button?

I'm currently making a todo list using Django model formsets. I came across a problem when trying to list each form in the formset with a delete button next to it. Here's a picture of what it looks like now:
When looked at closely, the spacing and height for each form are slightly different than the spacing and height for each delete button. The buttons are slightly larger and more spaced out than the forms. Here's my views.py:
def dashboard(request):
user = request.user
todo_list = Todo.objects.filter(user=user).all()
UpdateFormSet = modelformset_factory(Todo, fields=('item',))
if request.method == 'POST':
formset = UpdateFormSet(request.POST, queryset=todo_list)
if 'delete' in request.POST:
items_to_delete = request.POST.getlist('delete')
deleted_items = Todo.objects.filter(pk__in=items_to_delete).delete()
if 'update' in request.POST:
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances:
instance.user = user
instance.save()
return redirect('dashboard')
formset = UpdateFormSet(queryset=todo_list)
if not formset:
formset = UpdateFormSet()
context = {
'current_user': request.user,
'formset':formset,
'items':todo_list,
}
return render(request, 'users/dashboard.html', context)
Template:
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4 pt-3">ToDo Items</legend>
{{ formset.management_form }}
<div class="row">
<div class="col-6">
{% for form in formset reversed %}
{{ form.id }}
<div class="py-3">
{{ form.item }}
</div>
{% endfor %}
</div>
<div class="col-6">
<div class="input-group">
<div class="input-group-append">
<button type="submit" class="btn btn-sm btn-success my-3" name="update"><i class="fas fa-plus"></i>
</button>
</div>
</div>
{% for item in items reversed %}
<div class="input-group">
<div class="input-group-append">
<button type="submit" class="btn btn-sm btn-danger my-3" name="delete" value="{{ item.pk }}">
<i class="far fa-trash-alt"></i>
</button>
</div>
</div>
{% endfor %}
</div>
</div>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit" name="update">Save</button>
</div>
</form>
I can't seem to align each form with its delete button. I'm guessing the two for loops are interfering with that. Any help would be much appreciated!

Display an html div block differently depending on the extended page using django templatin

I'm building a webpage using the extend templating feature of django. I thus have a base.html where I have search fields that I want to display differently depending on the webpage that is extending base.html. Here are the fields that I want to show:
The corresponding code is:
<div class="row">
<div class="container-fluid col-md-offset-9 col-md-3">
<a href="../posts/newpost/" class="btn btn-info" role="button">
<span class="glyphicon glyphicon-education" aria-hidden="true"></span> Buton
</a>
</div>
</div>
<div class="container-fluid">
<h1 id="Titre" align="center">Title </h1><br>
</div>
<div class="col-md-12" style="height:100px;"></div>
<form class="form-inline text-center" action="{% url 'posts:postsearch' %}" id="form-searchLessons">
<div class="form-group">
<input type="text" class="form-control input-lg" id="typeCours" list="matieres" placeholder="Keyword" name="discipline" autocomplete="off">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg" id="Localisation" placeholder="Lieu."
name="localisation" onFocus="geolocate()">
</div>
<button type="submit" class="btn btn-default btn-lg" id="btn-getLessons">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span> Trouver !
</button>
</form>
</div>
In case of page1, I want the fields to appear like the image above.
Then if I extend base.html from page2, this should like this:
Which currently I write a complete different page:
<div class="container-fluid">
<div class="row reduced_search-bar">
<div class="col-lg-9">
<form class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="typeCours" placeholder="Keyword">
</div>
<div class="form-group">
<input type="text" class="form-control" id="Localisation" placeholder="Lieu">
</div>
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span> Trouver !
</button>
</form>
</div>
<div class="col-lg-3">
<a href="{% url 'posts:add' %}" class="btn btn-info" role="button">
<span class="glyphicon glyphicon-education" aria-hidden="true"></span> Buton ?
</a>
</div>
</div>
</div>
What I want, is to have all this code in one single base.html. That I print differently depending whether I'm extending from page1, or page2.
If I understood it correctly, you can pass an extra context from your view which will determine which code to show:
# views.py
from django.shortcuts import render
def page1(request):
return render(request, 'page1.html')
def page2(request):
return render(request, 'page2.html', {'page2': True})
# base.html
{% if page2 %}
# Necessary code for page 2
{% else %}
# Necessary code for other pages
{% endif %}
# page1.html
{% extends 'base.html' %}
# page2.html
{% extends 'base.html' %}