I am trying to display data from database throw drop-down list and Use filter query to filter data and display
if i tried to select value of html and select but slot is not create. Debugging form and i see error. If i select anything but drop-down do't selected here is error
Here is my code: slot/views.py
def slot_create(request):
form = SlotForm(request.POST)
print(form)
station = Station.objects.filter(user_id=request.user)
print(station)
if form.is_valid():
slot = form.save(commit=False)
slot.user = request.user
slot.save()
messages.success(request, 'Your Slot is add successfully')
return redirect('view_slot')
return render(request, 'add_slot.html', {
'form': form,
'station': station
})
here is my add_slot.html
<form method="post" novalidate>
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-12 mb-0">
{{ form.slot_name|as_crispy_field }}
</div>
<div class="form-group col-md-12 mb-0">
{{ form.per_unit_price|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.current_status|as_crispy_field }}
</div>
{% comment %} <div class="form-group col-md-6 mb-0">
{{ form.station|as_crispy_field }}
</div> {% endcomment %}
<div class="form-group col-md-6 mb-0">
<label for="station" class="block font-semibold text-sm mb-1"> Choose Station </label>
<select name="station_name" id = "station">
{% for station in station %}
<option value="{{station}}"> {{station}} </option>
{% endfor %}
</select>
</div>
<button type="submit" class="w-full rounded-full bg-red-gradient p-3 text-white font-bold hover:ring">
Add Slot
</button>
</div>
</form>
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>
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
Good day, trying to improve my webs skill by building a small web-app that stores contact information. The delete function that allows users to delete contacts of the app shows a success message however the index page does not show the changes in the database.
Checking on an external DBReader (DB Browser) shows no changes made to the database. Based off lurking questions here the return type of request.form.get('affected_field_here') (what i use to get the value of the contact id) returns none. Likewise i tried with request.args / request.values both of which showed the same problem
so can another pair of eyes tell me where i goofed?
Below is the delete function
#app.route('/delete', methods=["GET", "POST"])
def delete():
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
#Get contact_id
contact_id = request.args.get('contact_id')
db.execute("DELETE FROM contacts WHERE id =?", (contact_id,))
conn.commit()
conn.close()
flash('Contacts removed', 'success')
return redirect('/')
index.html code here
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
{% extends "base.html" %}
{% block title%}Landing Page{% endblock %}
{% block body %}
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="jumbotron p-3">
<h1>My Contacts <button type="button" class="btn btn-success float-right" data-toggle="modal"
data-target="#addcontact"> Add Contact</button></h1>
<!--------------------Add Contact Modal placed inside same holder as modalit's for-->
<div id="addcontact" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Add Contact</h3>
</div>
<div class="modal-body">
<form action="/add" method="POST" autocomplete="off">
<div class="form-group">
<input autofocus class="form-control" autocomplete="off" required type="text" name="fname" placeholder="Enter first name">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="text" required name="lname" placeholder="Enter Surname">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="number" min="1" required name="age" placeholder="Enter Age">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="number" name="contact" required placeholder="Enter Contact Number">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="email" name="email" placeholder="Enter Email address">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Add Contact</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% with messages = get_flashed_messages(category_filter=["error"]) %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger alert-dismissible">
×
<strong>Message: </strong>{{message}}
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% with messages = get_flashed_messages(category_filter=["success"]) %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success alert-dismissible">
×
<strong>Success: </strong>{{message}}
</div>
{% endfor %}
{% endif %}
{% endwith %}
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>First Name</td>
<td>Surname</td>
<td>Age</td>
<td>Contact #</td>
<td>Email</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{% for row in contacts %}
<tr>
<td>{{row['id']}}</td>
<td>{{row['fname']}}</td>
<td>{{row["lname"]}}</td>
<td>{{row['age']}}</td>
<td>{{row['number']}}</td>
<td>{{row['email']}}</td>
<td><button type="button" class="btn btn-primary" data-toggle="modal"
data-target="#editcontact{{row['id']}}">Edit</button>
<form style='display:inline;' action="/delete" method="POST">
<button type="submit" class="btn btn-danger""
onclick="return confirm('Are you sure you want to remove contacts?')">Delete</button></form>
</td>
</tr>
</tbody>
<div class="modal fade" id="editcontact{{row['id']}}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Contact Information</h5>
</div>
<div class="modal-body">
<form action="/edit" method="POST" autocomplete="off">
<div class="form-group">
<input autofocus class="form-control" autocomplete="off" required type="hidden" name="contact_id" value="{{row['id']}}" >
</div>
<div class="form-group">
<input autofocus class="form-control" autocomplete="off" required type="text" name="fname_edit" value="{{row['fname']}}" >
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="text" required name="lname_edit" value="{{row["lname"]}}">
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="number" min="1" required name="age_edit" value="{{row['age']}}" >
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="number" name="contact_edit" required value="{{row['number']}}" >
</div>
<div class="form-group">
<input class="form-control" autocomplete="off" type="email" name="email_edit" value="{{row['email']}}">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save Contact</button>
</div>
</form>
</div>
</div>
</div>
</div>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
the rest off appplication.py here incase it may be useful to:
from flask import Flask, render_template, request, flash, redirect, app, url_for, get_flashed_messages
import sqlite3
app = Flask(__name__)
app.secret_key = "this_is_a_secret" #need a key to start app
#app.route('/', methods=["GET", "POST"])
def index():
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
contacts = db.execute("SELECT * FROM contacts")
directory = [] #to store values
for contact in contacts: #loop through query and append
directory.append({
"id": contact[0],
"fname": contact[1],
"lname": contact[2],
"age": contact[3],
"number": contact[4],
"email": contact[5]})
return render_template('index.html', contacts = directory) #load dic into html
#app.route('/add', methods=["POST"])
def add():
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
if request.method == "POST": #general back end error checking
if not request.form.get('fname') or not request.form.get('lname'):
flash('First name and Surname are required fields.', 'error')
return redirect('/')
contact_age = request.form.get('age')
if contact_age.isdigit() == False:
flash ('Invalid age value', 'error')
return redirect('/')
contact_number = request.form.get('contact')
if contact_number.isdigit() == False:
flash ('Invalid contact number', 'error')
return redirect('/')
email = request.form.get('email')
fname = request.form.get('fname')
lname =request.form.get('lname')
db.execute("INSERT INTO contacts (fname, lname, age, number, email) VALUES(?,?,?,?,?)", (fname, lname, contact_age, contact_number, email))
conn.commit()
flash ('Updated your contact list', 'success')
return redirect('/')
#app.route('/edit', methods=["POST"])
def edit():
if request.method == "POST":
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
contact_id = request.form.get('contact_id')
fname_n = request.form.get('fname_edit')
lname_n = request.form.get('lname_edit')
age_n = request.form.get('age_edit')
num_n = request.form.get('contact_edit')
email_n = request.form.get('email_edit')
db.execute("""UPDATE contacts SET fname = ? ,lname = ?,age = ?,number = ?, email = ? WHERE id= ?
""",
(fname_n,lname_n,age_n,num_n,email_n,contact_id ))
conn.commit()
flash('Contacts updated', 'success')
return redirect('/')
#app.route('/delete', methods=["GET", "POST"])
def delete():
conn = sqlite3.connect('contacts.db')
db = conn.cursor()
#Get contact_id
contact_id = request.args.get('contact_id')
db.execute("DELETE FROM contacts WHERE id =?", (contact_id,))
conn.commit()
conn.close()
flash('Contacts removed', 'success')
return redirect('/')
if __name__ == "__main__":
app.run(debug=True)
finally base.html which index.html reference
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>{% block title %} {% endblock %} </title>
</head>
<body>
<div class="jumbotron p-3">
<div class="well text-center">
<h1>PRACTICE WEB APPLICATION</h1>
</div>
</div>
{% block body %}
{% endblock %}
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</html>
EDIT: Figured out answer. answer in post below.
In delete function, i was referencing the wrong id, to solve thus i added a name attribute to the delete button and reference that in the request.form function which allowed the function to work properly and reflect changes.
Hopefully this helps anyone stuck in a similar rut.
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!