Django Modals Validation Errors - python

Looked a lot into a solution of my issue but didn't get it right.
I want to show the errors in the Modal form and don't close until it is valid.
For now I am able to get the errors in the customer.html page after the Modal closes.
Forms.py
class CustomerForm(forms.ModelForm):
#...... Form Widget HERE ......
class Meta:
model = Customer
fields =['customername','customerlogo','emailaddress','addressLine1','membership','pobox','phonenumber','emailaddress']
Views.py
def customer(request):
context = {}
customers = Customer.objects.all()
context['customers'] = customers
if request.method == 'GET':
form = CustomerForm()
context['form'] = form
return render(request, 'Mainapp/customer.html', context)
if request.method == 'POST':
form = CustomerForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, 'New Client Added')
return redirect('customer')
else:
messages.error(request, form.errors)
return redirect('customer')
return render(request, 'Mainapp/customer.html', context)
HTML MODAL
<div id="create-modal" data-backdrop="static" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Customer Details</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-4" data-backdrop="static">
<div id="error">
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert-dismissible alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
</div>
<form action="#" action="Mainapp/customer.html" id="customerfrm" method="POST">
<!-- onsubmit="submitForm(event)"-->
{% csrf_token %}
<div class="row">
<div class="col-lg-9">
<div class="mb-3">
<label for="customername" class="form-label">Customer Name<span class="text-danger">*</span></label>
{{form.customername}}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-9">
<div class="mb-3">
<label for="emailaddress" class="form-label">Email Address<span class="text-danger">*</span></label>
{{form.emailaddress}}
</div>
</div>
<div class="col-lg-3">
<div class="mb-3">
<label for="customermembership" class="form-label">Membership<span class="text-danger">*</span></label>
{{form.membership}}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="mb-3">
<label for="customeraddress" class="form-label">Address<span class="text-danger">*</span></label>
{{form.addressLine1}}
</div>
</div>
<div class="col-lg-6">
<div class="mb-3">
<label for="customerlogo" class="form-label">Logo</label>
{{form.customerlogo}}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="mb-3">
<label for="POBox" class="form-label">POBox<span class="text-danger">*</span></label>
{{form.pobox}}
</div>
</div>
<div class="col-lg-6">
<div class="mb-3">
<label for="customernumber" class="form-label">Phone Number<span class="text-danger">*</span></label>
{{form.phonenumber}}
</div>
</div>
</div>
<div class="text-end">
<button type="submit" class="btn btn-primary waves-effect waves-light" >Submit</button>
<a type="reset" href= "{% url 'customer' %}" class="btn btn-secondary waves-effect">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div><!-- /.modal -->

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'))

The view function for 'authen.delete_tracker' did not return a valid response. The function either returned None or ended without a return statement [duplicate]

This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed 8 months ago.
flask code
#bp.route('/delete/<int:id>')
#login_required
def delete_tracker(id):
if Trackers.user_id == current_user.id:
trackers = Trackers.query.filter_by(id=id).first()
print(trackers)
db.session.delete(trackers)
db.session.commit()
return redirect(url_for("authen.dashboard"))
Html code- look for /delete url t bottom there is the error
{% extends "base.html" %}
{% block title %} Dashboard {% endblock %}
{% block content %}
<nav class="sidenav">
<div class="main-buttons">
<a class="nav-link active" id="trackers" aria-current="page" href="/dashboard">Trackers</a>
<a class="nav-link active" id="goals" aria-current="page" href="/goals">Goals</a>
<div>
</nav>
<div id="dashbar">
<nav class="navbar bg-light">
<div class="container-fluid">
<button type="button" class="btn btn-outline-dark" data-bs-toggle="modal" data-bs-target="#exampleModal">
Add Tracker
</button>
<form method="POST">
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add a Tracker</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<label for="tracker_name" class="col-form-label">Tracker Name:</label>
<input type="text" class="form-control" id="tracker_name" name="tracker_name"
placeholder="Enter a Tracker name">
<div class="from-fieldset" style="width:200px;">
<label for="tracker_type" class="form-label">Choose a Tracker type:</label>
<select id="tracker_type" name="tracker_type">
<option value="">choose Tracker type</option>
{% for t in data_trackers %}
<option value="{{t.name}}">{{t.name}}</option>
{% endfor %}
<label for="tracker_description " class="col-form-label">Description</label>
<input type="text" class="form-control" id="tracker_description" name="tracker_description"
placeholder="Enter Description">
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-light border-dark">Submit</button>
</div>
</div>
</div>
</div>
</form>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</nav>
</div>
<div class="wrapper">
<div class="container-tracker">
{% for track in user.trackers %}
<div class="tra">
<h3 id="trackername"> {{track.tracker_name}}</h3>
<div class="dropdown-container" tabindex="-1">
<form method="GET" action="/delete/{{track.id}}">
<button type="submit" class="btn btn-outline-light">Delete</button>
</form>
<div class="three-dots"></div>
<div class="dropdown">
<a href="#">
<div>Records and Graphs</div>
</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
( in form method=GET , the delete url is there and the flask code is at top for that endpoint
if I remove if condition in the delete_tracker() fucntion that is if user.id==current_user.id then I will get a different error that is , this is for session 2nd but this is 3rd session something like this, so my file I want to delete is different session )
can you try to change your line
#bp.route('/delete/<int:id>')
to
#bp.route('/delete/<track.id>')

How can I get this form to work and save the updated information?

I was successful at getting the form to appear on the modal which was an issue I had earlier, now I'm struggling to make this work. Any way to work my way around this?? Also I wanna check if method == 'POST' before checking if the form is valid but can't seem to find a solution..
views:
class ProfileDetailView(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'network/profile.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = User.objects.get(username__iexact=self.request.user)
profile = Profile.objects.get(user=user)
form = ProfileModelForm(instance=profile)
confirm = False
rel_r = Relationship.objects.filter(sender=profile)
rel_s = Relationship.objects.filter(receiver=profile)
rel_receiver = []
rel_sender = []
for item in rel_r:
rel_receiver.append(item.receiver.user)
for item in rel_s:
rel_sender.append(item.sender.user)
if form.is_valid():
form.save()
confirm = True
context["rel_receiver"] = rel_receiver
context["rel_sender"] = rel_sender
context["posts"] = self.get_object().get_all_authors_posts()
context["len_posts"] = True if len(self.get_object().get_all_authors_posts()) > 0 else False
context["form"] = form
context["confirm"] = confirm
context["profile"] = profile
return context
Form:
class ProfileModelForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'bio', 'avatar')
Model:
class Profile(models.Model):
first_name = models.CharField(max_length=64, blank=True)
last_name = models.CharField(max_length=64, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.CharField(max_length=64, blank=True)
avatar = models.ImageField(upload_to='avatars', default='avatar.png')
background = models.ImageField(upload_to='backgrounds', default='background.png')
following = models.ManyToManyField(User, related_name='following', blank=True)
bio = models.TextField(default="No Bio..")
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(unique=True, blank=True)
objects = ProfileManager()
def __str__(self):
return f"{self.user.username}"
def get_absolute_url(self):
return reverse("profile-view", kwargs={"slug": self.slug})
HTML:
{% extends "network/layout.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block title %}
My Profile
{% endblock title %}
{% block body %}
<!--Modal-->
<div class="modal fade" id="profileModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update Your Profile</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img width="100px" src="{{profile.avatar.url}}">
<form action="", method="POST", enctype="multipart/form-data" class="form">
{% csrf_token %}
{{form}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
</div>
</div>
</div>
<div>
{% if confirm %}
<div class="alert alert-info" role="alert">Your profile has been updated!</div>
{% endif %}
</div>
<div class="row py-5 px-4">
<div class="col-md-5 mx-auto">
<!-- Profile widget -->
<div class="bg-white shadow rounded overflow-hidden">
<div class="px-4 pt-0 pb-4 cover">
<div class="media align-items-end profile-head">
<div class="profile mr-3"><img src="{{object.avatar.url}}" width="130" class="rounded mb-2 img-thumbnail"></div>
<div class="media-body mb-5 text-white">
<h4 class="mt-0 mb-3">{{profile.first_name}} {{profile.last_name}}</h4>
<p style="color: black;" class="small mb-4"> <i class="fas fa-map-marker-alt mr-2"></i>{{profile.country}}</p>
</div>
</div>
</div>
<div class="bg-light p-5 d-flex justify-content-end text-center">
<ul class="list-inline mb-0">
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_posts_num}}</h5><small class="text-muted"> <i class="fas fa-image mr-1"></i>Posts</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_followers_num}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Followers</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">340</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Following</small>
</li>
<li class="list-inline-item">
<h5 class="font-weight-bold mb-0 d-block">{{object.get_liked}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Likes</small>
</li>
</ul>
</div>
<div class="ml-2">
{% if object.user and object.user not in rel_receiver and object.user not in rel_sender %}
<form action="{% url 'send-invite' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="profile_pk" value={{object.pk}}>
<button type="submit" class=" btn btn-sm btn-success w-btn"><i class="bi-plus-lg"></i> Follow</button>
</form>
{% endif %}
{% if object.user in rel_receiver and request.user not in object.following.all %}
<button class="btn btn-sm disabled "><i class="bi-three-dots"></i> Waiting aprroval</button>
{% endif %}
{% if request.user in object.following.all %}
<form action="{% url 'remove-friend' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="profile_pk" value={{object.pk}}>
<button type="submit" class=" btn btn-sm btn-dark w-btn"><i class="bi-dash-lg"></i> Unfollow</button>
</form>
{% endif %}
</div>
<div class="px-4 py-3">
<h5 class="mb-0">About</h5>
<button class="btn btn-sm btn-secondary float-right" id="modal-btn" data-toggle="modal" data-target="#profileModal">Edit Profile</button>
<div class="p-4 rounded shadow-sm bg-light">
<p class="font-italic mb-0">{{profile.bio}}</p>
</div>
</div>
<div class="py-4 px-4">
<div class="d-flex align-items-center justify-content-between mb-3">
<h5 class="mb-0">Recent posts</h5>Show all
</div>
{% if len_posts %}
<div class="row">
{% for post in posts %}
<div class="col-lg-6 mb-2 pr-lg-1 fluid">
{% if post.picture %}
<img class="card-img-profile" src="{{post.picture.url}}">
{% endif %}
{{post.content}}
</div>
{% endfor %}
{% else %}
<h1>This user didn't post anything yet..</h1>
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Not sure if you have tried this:
In your view you should write a function called post.
def post(self, request):
if request.method == 'POST':
form = self.form(request.POST)
if form.is_valid():
*whatever you need to do after you've validated the from*

How to Submit and Retrieve data in one view in Django?

I have a little confusion in my app.
I have an HTML page in which I have added one form (form data submitting) and one table (to display the submitted data).
For which I have a view that submit and retrieve the data at the same time but unfortunately, data is successfully storing in the table but in retrieving time, it gives me the error which is mentioned below.
Error
NoReverseMatch at /staff/add_staff_type
Reverse for 'student_profile' with keyword arguments '{'id': ''}' not
found. 1 pattern(s) tried: ['student/profile/(?P[0-9]+)$']
Views.py
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime)
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
return redirect('add_staff_type')
else:
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("student/Add_Student", views.Add_Student, name="Add_Student"),
path("student/display_students", views.Display_Student, name="display_students"),
path("student/edit/<int:id>", views.student_edit, name="student_edit"),
path("student/update/<int:id>", views.student_update, name="student_update"),
path("student/profile/<int:id>", views.student_profile, name="student_profile"),
path("student/delete/<int:id>", views.student_delete, name="student_delete"),
#below url is for staff_type on which i am currently workin
path("staff/add_staff_type", views.add_staff_type, name="add_staff_type"),
]
staff_type.html
<div class="card">
<div class="card-header">
<h3 class="card-title">Add Staff Type</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form
class="needs-validation"
action="add_staff_type"
method="POST"
enctype="multipart/form-data"
novalidate
>
{% csrf_token %}
<div class="card-body">
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">Designation</label>
<input
type="text"
class="form-control"
id="validationCustom01"
placeholder="Acountant, Librarian, Teacher"
name="designation"
required
/>
<div class="valid-feedback">Looks good!</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom04">Salary</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Rs.</span>
</div>
<input type="number" class="form-control" id="validationCustom04" name="salary" min="0">
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom03">Date and Time</label>
<input
type="datetime-local"
class="form-control"
id="validationCustom03"
placeholder="MM/DD/YYY"
name="datetime"
required
/>
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<!--
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustomUsername">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend">#</span>
</div>
<input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
-->
<button class="btn btn-primary" type="submit">Add Staff Type</button>
</div>
</form>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">Available Staff Types</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Designation</th>
<th>Salary</th>
<th>Entry Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for staff_type in display_staff_type %}
<tr>
<td>{{staff_type.designation}}</td>
<td>{{staff_type.salary}}</td>
<td>{{staff_type.datetime}}</td>
<td>
<a href="{% url 'student_profile' id=student.id %}">
<i class="far fa-eye"></i>
</a>
<a href="{% url 'student_edit' id=student.id %}">
<i class="far fa-edit"></i>
</a>
<a href="{% url 'student_delete' id=student.id %}">
<i class="far fa-trash-alt"></i>
</a>
</td>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
You can revise your view function to this:
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime)
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
# this can also be return redirect('staff:add_staff_type')
return redirect('add_staff_type')
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
Since you are calling the same view and serving data to the same form and view you can remove the action value of the form which goes like this:
<form
class="needs-validation"
action=""
method="POST"
enctype="multipart/form-data"
novalidate
>

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

Categories

Resources