Django Form POST problem in a Bootstrap Modal - python

I'm searching for this issue for days... And, unfortunately, couldn't find the answer.
I have a view (Buildings) and I want to add/edit a Building with a modal. With my current code, I can add new Building. However, because I can't pass the id (pk) of an existing Building, I can't update it.
I've two views: one for the table, other for the form. I noticed that, when I POST, my Building view posts, not the newBuilding view.
I tried to get pk from kwargs in newBuilding view, but I can't get it in the post method.
The only thing left is to update..
Let me share my code.
Thanks in advance!
urls.py
path('app/buildings/', login_required(views.Buildings.as_view()), name='buildings'),
path('app/buildings/<int:pk>', login_required(views.NewBuilding.as_view()), name='buildings-pk'),
models.py
class Buildings(TemplateView):
template_name = 'main_app/buildings.html'
model = models.Building
def get_context_data(self, **kwargs):
context = super(Buildings, self).get_context_data(**kwargs)
# Get selected site from cache
active_site = models.Site.objects.filter(id=self.request.session.get('active_site')).get()
context['active_site'] = active_site
filtered_buildings = models.Building.objects
context['buildings'] = filtered_buildings.all()
return context
def get_form_kwargs(self):
kwargs = super(Buildings, self).get_form_kwargs()
kwargs.update({'active_site': self.request.session.get('active_site'), 'edited_building_id': None})
return kwargs
def post(self, request, *args, **kwargs):
if request.method == 'POST':
NewBuilding.post(self, request=request, slug=None)
return HttpResponseRedirect(reverse_lazy('main_app:buildings'))
else:
print("error")
...
class NewBuilding(FormView):
template_name = 'main_app/new/new_building.html'
form_class = forms.NewBuildingForm
active_site = None
def get_context_data(self, **kwargs):
context = super(NewBuilding, self).get_context_data(**kwargs)
# Get selected site from cache
self.active_site = models.Site.objects.filter(id=self.request.session.get('active_site')).get()
context['active_site'] = self.active_site
context['edited_building_id'] = self.kwargs['pk']
return context
def get_form_kwargs(self):
kwargs = super(NewBuilding, self).get_form_kwargs()
kwargs.update({'active_site': self.request.session.get('active_site'),
'edited_building_id': self.kwargs['pk']})
return kwargs
def post(self, request, slug=None, *args, **kwargs):
if request.method == 'POST':
# HERE, I need to assign the building to be edited.
# if kwargs['edited_building_id']:
# new_building = models.Building.objects.get(id=self.kwargs['edited_building'])
# else:
new_building = models.Building()
new_building.site = models.Site.objects.filter(id=self.request.session.get('active_site')).get()
if new_building.name != request.POST.get('name'):
new_building.name = request.POST.get('name')
if new_building.address != request.POST.get('address'):
new_building.address = request.POST.get('address')
new_building.save()
else:
print("error")
buildings.html
<div class="portlet box blue">
<div class="portlet-title">
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
</div>
</div>
<div class="portlet-body">
<div class="table-toolbar">
<div class="row">
<div class="col-md-12">
<div class="btn-group pull-right">
<button id="sample_editable_1_new" class="btn green" data-target="#full-width" data-toggle="modal" href="{% url "main_app:buildings-pk" pk=0%}">
Add New <i class="fa fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
{# modal for new and edited entry#}
<div id="full-width" class="modal container fade" tabindex="-1">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Add Building</h4>
</div>
<div class="modal-body">
{# modal body#}
</div>
</div>
<table class="table table-striped table-hover table-bordered" id="sample_editable_1">
<thead>
<tr>
<th class="text-center">
Name
</th>
<th class="text-center">
Address
</th>
<th class="text-center">
Type
</th>
<th class="text-center">
Edit
</th>
</tr>
</thead>
<tbody>
{% for building in buildings %}
<tr>
<td>
{{ building.name }}
</td>
<td>
{{ building.address }}
</td>
<td>
{{ building.type | default_if_none:"-" }}
</td>
<td>
<a class="edit" data-target="#full-width" data-toggle="modal" href="{% url "main_app:buildings-pk" pk=building.id%}">
Edit </a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
new_building.html
<form class="form-horizontal" method="POST">
{% csrf_token %}
<div class="form-body">
<div class="form-group last">
<label class="col-md-3 control-label">Site</label>
<div class="col-md-4">
<span class="form-control-static">{{ active_site.name }}</span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Name</label>
<div class="col-md-4">
{{ form.name }}
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn blue">Submit</button>
<button type="button" class="btn default" data-dismiss="modal">Cancel</button>
</div>
</form>
forms.py
class NewBuildingForm(forms.ModelForm):
active_site = None
edited_building_id = 0
class Meta:
model = models.Building
fields = ["name", "address", "type", "site", "public_area",
"electricity_utility_meter", "water_utility_meter", "gas_utility_meter", "hot_water_utility_meter"]
def __init__(self, *args, **kwargs):
self.active_site = kwargs.pop('active_site')
self.edited_building_id = kwargs.pop('edited_building_id')
super(NewBuildingForm, self).__init__(*args, **kwargs)
edited_building = models.Building.objects.filter(id=self.edited_building_id)
self.fields['name'] = forms.CharField(
widget=forms.TextInput(attrs={'placeholder': 'Name', 'class': 'form-control input-circle'}))
self.fields['address'] = forms.CharField(
widget=forms.TextInput(attrs={'placeholder': 'Address', 'class': 'form-control input-circle'}),
required=False)
if edited_building:
self.fields['name'].initial = edited_building.get().name
self.fields['address'].initial = edited_building.get().address
I try to update kwargs on FormView (because I can get edited_building_id there), but I can't access kwargs on POST https://imgur.com/G7UcmLo

Related

Edit Data in Django Unable to show the data

I'm using Django to build a website. Modal bootstrap is what I'm utilizing. All works good for add, and delete data. However, In the Django form, I am unable to appear the data stored in the database for the update. Appreciate your help maybe I did something wrong with my code. I am not sure if my html or modal is correct. Thank you
-->> HTML <<--
<!-- Table Header -->
<thead>
<tr>
<th>User ID</th>
<th>Username</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Role</th>
<th>Created Date</th>
<th>Modified Date</th>
<th>Status</th>
<th>Settings</th>
</tr>
</thead>
<!-- Table Body -->
<tbody>
{% for members in member %}
<tr>
<td>{{members.id}}</td>
<td>{{members.username}}</td>
<td>{{members.first_name}}</td>
<td>{{members.middle_name}}</td>
<td>{{members.last_name}}</td>
<td>{% if members.role %}{{members.get_role}}{% endif %}</td>
<td>{{members.created_date}}</td>
<td>{{members.modified_date}}</td>
<td>
{% if members.status == 1 %}
<button type="button"
class="btn btn-success rounded-pill">{{members.get_status}}</button>
{% elif members.status == 2 %}
<button type="button"
class="btn btn-danger rounded-pill">{{members.get_status}}</button>
{% elif members.status == 3 %}
<button type="button"
class="btn btn-secondary rounded-pill">{{members.get_status}}</button>
{% endif %}
</td>
<td>
<a href="#" data-toggle="modal" data-target="#viewUserModal{{ members.id }}"><i class='bx bxs-folder-open'
data-toggle="tooltip" title="View"></i></a>
<a href="#" data-toggle="modal" data-target="#editUserModal{{ members.id }}"><i class='bx bxs-edit'
data-toggle="tooltip" title="Edit"></i></a>
<a href="#" data-toggle="modal" data-target="#deleteModal{{ members.id }}"><i class='bx bx-trash'
data-toggle="tooltip" title="Delete" ></i></a>
</td>
</tr>
{% include 'includes/modals.html' %}
{% endfor %}
</tbody>
<!-- End of Table Body -->
</table>
</div>
-->> Edit Modal <<--
<div class="modal fade" id="editUserModal{{ members.id }}" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit User Account</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
<div class="modal-body">
<form action="" method="POST">
{% csrf_token %}
<div class="form-group ">
<label>First Name</label>
{{form.first_name}}
</div>
<div class="form-group">
<label>Middle Name</label>
{{form.middle_name}}
</div>
<div class="form-group">
<label>Last Name</label>
{{form.last_name}}
</div>
<div class="form-group">
<label>Email</label>
{{form.email}}
</div>
<div class="form-group">
<label>Mobile Number</label>
{{form.mobile_number}}
</div>
<div class="form-group">
<label>Username</label>
{{form.username}}
</div>
<div class="form-group">
<label>Role</label>
<select class="form-control" id="inputGroupSelect01" name="role" value="{% if members.role %}{{members.get_role}}{% endif %}" required>
<option>Select Role</option>
<option value="2" {% if members.role == 1 %}{{members.get_role}} selected {% endif %} >Member</option>
<option value="2" {% if members.role == 2 %}{{members.get_role}} selected {% endif %} >Admin</option>
<option value="3" {% if members.role == 3 %}{{members.get_role}} selected {% endif %}>Super Admin</option>
</select>
</div>
<div class="form-group">
<label>Status</label>
<select class="form-control" id="inputGroupSelect01" name="role" value="{% if members.status %}{{members.get_status}}{% endif %}" required>
<option>Select Status</option>
<option value="1" {% if members.status == 1 %}{{members.get_status}} selected {% endif %} >Active</option>
<option value="2" {% if members.status == 2 %}{{members.get_status}} selected {% endif %}>Deactive</option>
</select>
</div>
<hr>
<input type="button" class="btn btn-secondary" data-dismiss="modal" value="Cancel">
<input type="submit" class="btn btn-primary" href="{% url 'edit_user' members.id %}" value="Save">
</form>
</div>
</div>
</div>
</div>
-->> urls.py <<--
urlpatterns = [
path('userAccounts/edit_user/<user_id>', views.edit_user, name='edit_user'),
]
-->> forms.py <<--
class UserFormAdmin(forms.ModelForm):
class Meta:
model = User
fields = ['first_name', 'middle_name', 'last_name', 'username', 'email', 'mobile_number', 'password']
labels = {
'first_name': '',
'middle_name': '',
'last_name': '',
'mobile_number': '',
'email': '',
'username': '',
'password': '',
'confirm_password': '',
}
first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Jones', 'class': 'form-control', }))
middle_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'A', 'class': 'form-control', }))
last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Smith', 'class': 'form-control',}))
mobile_number = forms.CharField(max_length=15, validators=[RegexValidator(
'^\+[0-9]{1,3}\.?\s?\d{8,13}', message="Phone number must not consist of space and requires country code. eg : +639171234567")],widget=forms.TextInput(attrs={'placeholder': '09123456789', 'class': 'form-control',}),
error_messages={'unique': ("Mobile Number already exists.")})
email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'jonesmith#gmail.com', 'class': 'form-control',}),
error_messages={'unique': ("Email already exists.")},)
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Jones_Smith31', 'class': 'form-control',}),
error_messages={'unique': ("Username already exists.")},)
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': '********', 'class': 'form-control',}))
#password = forms.CharField(validators=[MinLengthValidator(8),RegexValidator('^(?=.*[A-Z])(?=.*[!##$&*])(?=.*[0-9])(?=.*[a-z])$', message="Password should be a combination of Alphabets and Numbers")], widget=forms.PasswordInput(attrs={'placeholder': '********', 'style': 'width: 460px; '}))
confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': '********', 'class': 'form-control', }))
-->> views.py <<--
def sa_userAccount_admin(request):
member = User.objects.filter(role = 2)
form = UserFormAdmin(request.POST)
context = {
'form': form,
'member': member,
}
print(context)
return render(request, 'pages/sa_userAccount.html', context)
def edit_user(request, user_id):
member = User.objects.get(pk=user_id)
form = UserFormAdmin(request.POST or None, instance=member)
if form.is_valid():
form.save()
return redirect('sa_userAccount')
return render(request, 'pages/sa_userAccount.html',
{'members': member,
'form':form})
You can do this using the following steps:
get user input to update an object in HTML Modal
send data using the POST method with object pk
fetch object using received pk
update object in views using setattr(object,field name,value) from POST data
call object.save() method
These steps will update your objects in the database using the partial update technique.

The modal appears but the profile edit form don't appear on it, any idea why?

On my social app that I'm working on, there's still one issue. On my ProfileDetailView, to click on "Edit Profile" the modal form appear but there's no form. It was working before but when I fixed the close button and I don't know what happened.. I copied the modal html from bootstrap so i probably deleted/changed something and forgot to re-do it..
Form:
from django import forms
from .models import Profile, Post, Comment
class ProfileModelForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'bio', 'avatar')
class PostModelForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea(attrs={'rows':2, 'cols': 30}))
class Meta:
model = Post
fields = ('content', 'picture')
class CommentModelForm(forms.ModelForm):
body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...', 'class':'comment'}))
class Meta:
model = Comment
fields = ('body',)
Views:
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.http.response import JsonResponse
from django.shortcuts import render, redirect, resolve_url, get_object_or_404
from django.urls import reverse, reverse_lazy
from django.core import serializers
from django.core.paginator import Paginator
from django.contrib import messages
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from itertools import chain
from .models import Relationship, Post, Profile, Like
from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView
from .forms import ProfileModelForm, PostModelForm, CommentModelForm
def search_view(request):
if request.method == "POST":
searched = request.POST['searched']
profiles = Profile.objects.filter(slug__contains=searched)
return render(request, 'network/search.html',
{'searched':searched,
'profiles':profiles})
else:
return render(request, 'network/search.html',
{})
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)
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)
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
return context
#login_required
def profile_view(request):
profile = Profile.objects.get(user=request.user)
form = ProfileModelForm(request.POST or None, request.FILES or None, instance=profile)
confirm = False
if request.method == 'POST':
if form.is_valid():
form.save()
confirm = True
context = {
'profile': profile,
'form': form,
'confirm': confirm,
}
return render(request, 'network/profile.html', context)
profile.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="{{object.avatar.url}}">
<form action="", method="POST", enctype="multipart/form-data" class="form-horizontal">
{% 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.like_count}}</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 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 %}
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})
__initial_first_name = None
__initial_last_name = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__initial_first_name = self.first_name
self.__initial_last_name = self.last_name
def save(self, *args, **kwargs):
ex = False
to_slug = self.slug
if self.first_name != self.__initial_first_name or self.last_name != self.__initial_last_name or self.slug=="":
if self.first_name and self.last_name:
to_slug = slugify(str(self.first_name) + " " + str(self.last_name))
ex = Profile.objects.filter(slug=to_slug).exists()
while ex:
to_slug = slugify(to_slug + " " + str(get_random_code()))
ex = Profile.objects.filter(slug=to_slug).exists()
else:
to_slug = str(self.user)
self.slug = to_slug
super().save(*args, **kwargs)
def get_followers(self):
return self.following.all()
def get_followers_num(self):
return self.following.all().count()
def get_my_posts(self):
return self.post_set.all()
def get_country(self):
return self.post_set.all()
def get_following_users(self):
following_list = [p for p in self.get_following()]
return following_list
def get_all_posts(self):
users = [user for user in self.get_following()]
posts = []
qs = None
for u in users:
p = Profile.objects.get(user=u)
p_posts = p.post_set.all()
posts.append(p_posts)
my_posts = self.post_set.all()
posts.append(my_posts)
if len(posts) > 0:
qs = sorted(chain(*posts), reverse=True, key=lambda obj: obj.created)
return qs
def get_posts_num(self):
return self.post_set.all().count()
def get_all_authors_posts(self):
return self.post_set.all()
def get_likes_given_num(self):
likes = self.like_set.all()
total_liked = 0
for item in likes:
if item.value == 'Like':
total_liked += 1
return total_liked
def get_likes_received_num(self):
posts = self.post_set.all()
total_liked = 0
for item in posts:
total_liked += item.all().count()
return total_liked
def get_proposals_for_following(self):
profiles = Profile.objects.all().exclude(user=self.user)
followers_list = [p for p in self.get_following()]
available = [p.user for p in profiles if p.user not in followers_list]
random.shuffle(available)
return available[:3]
STATUS_CHOICES = (
('send', 'send'),
('accepted', 'accepted')
)
Update posts html:
{% extends "network/layout.html" %}
{% block title %}
Update Post
{% endblock title %}
{% block body %}
<div class="card center" style="width: 30rem;">
<h3>Update post</h3>
<form action="" method="POST" enctype="multipart/form-data" class="form-group">
{% csrf_token %}
{{form}}
<button type='submit' class="btn float-right btn-sm btn-primary mt-5">Update</button>
</form>
</div>
{% endblock body %}
URLs:
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
from .views import (
posts_of_following_profiles,
like_unlike_post,
invites_received_view,
invite_profiles_list_view,
send_invitation,
remove_friends,
accept_invitation,
reject_invitation,
search_view,
post_comment_create_view,
login_view,
logout_view,
register,
ProfileDetailView,
PostDeleteView,
PostUpdateView,
ProfileListView,
)
urlpatterns = [
path("", ProfileListView.as_view(), name="all-profiles-view"),
path("posts/", views.post_comment_create_view, name="posts"),
path("posts-follow/", posts_of_following_profiles, name="posts-follow"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("liked/", like_unlike_post, name="like-post-view"),
path("<pk>/delete", PostDeleteView.as_view(), name="post-delete"),
path("<pk>/update", PostUpdateView.as_view(), name="post-update"),
path("invites/", invites_received_view, name="invites-view"),
path("send-invite/", send_invitation, name="send-invite"),
path("remove-friend/", remove_friends, name="remove-friend"),
path("invites/accept/", accept_invitation, name="accept-invite"),
path("invites/reject/", reject_invitation, name="reject-invite"),
path("to-invite/", invite_profiles_list_view, name='invite-profiles-view'),
path("search/", views.search_view, name='search-view'),
path("<slug>", ProfileDetailView.as_view(), name="profile-view"),
]
screenchot
Code snippet:
<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 src="/media/avatars/11892013_911718608883264_3848632245418610369_n.jpg" width="100px">
<form action="" ,="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="P2vu2WI916PGSbMOrXD14c9EFmfMVEk3T1vkf9rqsZC7hXD94Dq2Cjo4MVCIiEEp">
</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>
</div>

Django form errors are not showing in template

no form errors are showing up in my HTML template when the form is invalid. The form is placed within a carousel incase that's relevant.
I'm calling out individual form elements instead of rendering as {{form.as_p}}, errors where showing when this was the case.
The last item in the carousel is the password and if I leave this blank it will show a pop out that says "please fill in this field" but nothing more than that and only for that one field.
Views.py
def collapsecard(request):
if request.method == 'POST':
create_user_form = CreateUserForm(request.POST)
safezone_form = SafezoneForm(request.POST)
if create_user_form.is_valid() and safezone_form.is_valid():
user = create_user_form.save()
safezone = safezone_form.save(commit=False)
safezone.userid = user
safezone.useremail = user.email
safezone.save()
user = authenticate(username=create_user_form.cleaned_data['username'],
password=create_user_form.cleaned_data['password1'],
)
login(request,user)
api_key = 'XYZ'
api_secret = 'XYZ'
id = 'XYZ'
mailjet = Client(auth=(api_key, api_secret))
data = {
'Email': safezone.useremail,
'Action': "addnoforce"
}
result = mailjet.contactslist_managecontact.create(id=id, data=data)
print
result.status_code
print
result.json()
return redirect('safezoneaddedpage')
return render(request, 'V2maparonno_create_safe_zoneV2.html',
{'create_user_form': create_user_form, 'safezone_form': safezone_form})
else:
create_user_form = CreateUserForm()
safezone_form = SafezoneForm()
print(create_user_form.errors)
print(safezone_form.errors)
return render(request, 'V2maparonno_create_safe_zoneV2.html',
{'create_user_form': create_user_form, 'safezone_form': safezone_form})
Extract from HTML
<form action="" method="POST" class="form-control">
{% csrf_token %}
<div id="carouselExampleIndicators" class="carousel slide" data-interval="false" style="width: 100%">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="4"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<div class="carousel-caption">
<h5>Drag the marker over your home</h5>
<div class="longlatinput">
{{ safezone_form.latitudecentre }}{{ safezone_form.longitudecentre }}
</div>
<button class="btn btn-sm btn-outline-primary" type="button" data-slide-to="1" data-target="#carouselExampleIndicators">Next</button>
</div>
</div>
<div class="carousel-item">
<div class="carousel-caption">
<h5>Give your safezone a name</h5>
<div class="form-inputs">
{{ safezone_form.name }}
</div>
<div class="name_space">
<button class="btn btn-sm btn-outline-primary" type="button" data-slide-to="2" data-target="#carouselExampleIndicators">Next</button>
</div>
</div>
</div>
<div class="carousel-item">
<div class="carousel-caption">
<h5>What email address should we send an alert to?</h5>
<div class="form-inputs">
{{create_user_form.email}}
</div>
<button class="btn btn-sm btn-outline-primary" type="button" data-slide-to="3" data-target="#carouselExampleIndicators">Next</button>
</div>
</div>
<div class="carousel-item">
<img src="https://pupaprojectawsbucket.s3.eu-west-2.amazonaws.com/Screenshot+2021-05-04+at+20.36.09.png" alt="..." style="width: 100%; height: 200px;">
<div class="carousel-caption">
<h5>Create your username</h5>
<div class="form-inputs">
{{create_user_form.username}}
</div>
<button class="btn btn-sm btn-outline-primary" type="button" data-slide-to="4" data-target="#carouselExampleIndicators">Next</button>
</div>
</div>
<div class="carousel-item">
<div class="carousel-caption">
<h5>Finally, set a password</h5>
<div class="form-inputs">
{{create_user_form.password1}}
</div>
<input class="btn btn-success" type="submit" name="Submit" id="reset-btn">
<div class="disclaimer"><p>By clicking submit you agree to receiving email alerts.</p></div>
</div>
</div>
</div>
</div>
</form>
**<div class = card>
Errors
{{safezone_form.errors.name}}
{{create_user_form.errors.email}}
{{create_user_form.errors.username}}
{{create_user_form.errors.password1}}
</div>**
Forms.py
password2 = None
email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder": "michael#gmail.com"}))
username = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "JohnSmith078"}))
password1 = forms.CharField(widget=forms.PasswordInput(attrs={"placeholder": "8+ characters"}))
class Meta:
model = User
fields = ['username', 'email', 'password1']
def clean_password1(self):
password1 = self.cleaned_data.get('password1')
try:
password_validation.validate_password(password1, self.instance)
except forms.ValidationError as error:
self.add_error('password1', error)
return password1
class SafezoneForm(forms.ModelForm, admin.ModelAdmin):
name = forms.CharField(label='Safezone name',widget=forms.TextInput
(attrs={'id': 'name', 'label': 'Name of Safezone', 'class': 'form-inputs',"placeholder": "Mum's house"}))
latitudecentre = forms.FloatField(label='Safezone Latitude',widget=forms.TextInput
(attrs={'id': 'latitudecentre','class': 'form-inputs',"placeholder": "Latitude"}))
longitudecentre = forms.FloatField(label='Safezone Longitude',widget=forms.TextInput
(attrs={'id': 'longitudecentre','class': 'form-inputs',"placeholder": "Longitude"}))
class Meta:
model = Safezone
fields = ['name', 'longitudecentre', 'latitudecentre']
Your errors don't show because you're redirecting to another page if your forms are not valid.
if create_user_form.is_valid() and safezone_form.is_valid():
...
return redirect('safezoneaddedpage')
return redirect('safezoneaddedpage') # detelete this, here you must not redirect to another page, but render the same template.
and add this:
return render(request, 'V2maparonno_create_safe_zoneV2.html',
{'create_user_form': create_user_form, 'safezone_form': safezone_form})

Add User Functionality at custom admin side - Django

I am working on a project in Python Djnago 3.1.2, and developing a custom admin side, where admin can perform different functionalities.
At the admin site I want to add functionality to add user and I have created a function but there is some error but I could not get it.
Here is My models.
models.py
class User(AbstractUser):
GENDER = (
(True, 'Male'),
(False, 'Female'),
)
USER_TYPE = (
('Admin', 'Admin'),
('Designer', 'Designer'),
('Customer', 'Customer'),
)
user_id = models.AutoField("User ID", primary_key=True, auto_created=True)
avatar = models.ImageField("User Avatar", null=True, blank=True)
gender = models.BooleanField("Gender", choices=GENDER, default=True)
role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer')
def __str__(self):
return "{}".format(self.user_id)
This is the function I have created and I think error is in my views.
views.py
def addUser(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/admin1/addUser')
else:
addUser_show = User.objects.all()
# start paginator logic
paginator = Paginator(addUser_show, 3)
page = request.GET.get('page')
try:
addUser_show = paginator.page(page)
except PageNotAnInteger:
addUser_show = paginator.page(1)
except EmptyPage:
addUser_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/addUser.html',
{'addUser_show': addUser_show, "form":form})
urls.py
path('addUser/', views.addUser, name="admin-add-user"),
Form I am using to get the create user form.
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'avatar', 'email', 'password1', 'password2', 'gender', 'role']
addUser.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Add User{% endblock %}
{% block main %}
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
User
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add User</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-add-user'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
{{form.as_p}}
<div class="modal-footer justify-content-right">
<input type="Submit" name="Submit" value="Submit"
class="btn btn-outline-success">
<button type="button" class="btn btn-outline-danger" data-dismiss="modal">Close
</button>
</div>
</table>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<br>
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Product Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>User Id</th>
<th>User Name</th>
<th>User First Name</th>
<th>User Last Name</th>
<th>User Email</th>
<th>User Gender</th>
<th>User Avatar</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in addUser_show %}
<tr>
<td>{{x.user_id}}</td>
<td>{{x.username}}</td>
<td>{{x.first_name}}</td>
<td>{{x.last_name}}</td>
<td>{{x.email}}</td>
<td>{{x.gender}}</td>
<td><img src="{{x.avatar.url}}" alt="{{x.avatar}}" height="100" width="100">
</td>
<td>{{x.role}}</td>
<td><a href="#"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="#"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
<a href="#"
class="btn btn-outline-warning mt-2"><i
class="fa fa-eye" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if addUser_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{product_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in addUser_show.paginator.page_range %}
{% if addUser_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if addUser_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{addUser_show.next_page_number}}"> Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Here I want to make admin able to create new user. but I am getting error shown below while submission of
form. My form works proper till it display the form , but when I fill up details and submit the form it shows the following error.
If possible please write the answer.
I have tried something and its working for me but I don't know that it is right way to do it or not.
view.py
def addUser(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/admin1/addUser')
addUser_show = User.objects.all()
# start paginator logic
paginator = Paginator(addUser_show, 3)
page = request.GET.get('page')
try:
addUser_show = paginator.page(page)
except PageNotAnInteger:
addUser_show = paginator.page(1)
except EmptyPage:
addUser_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/addUser.html',
{'addUser_show': addUser_show,"form":form})

Django Ajax get request - load model instance into a form

I have a table in a HTML template that displays all instances of a django model. on each row of the template I have an edit button that looks up the primary key of each instance, and by clicking that button I want all the fields in the model instance to be populated in a modal by using ajax. After that I want to be able to edit the data and use ajax to send the edited data back to the database.
I have been searching all over the web and found this post that is exactly what I need, but I still can't get it to work. Any help would be greatly appreciated.
jQuery code
var modalDiv = $("#modal-div");
$(".open-modal").on("click", function() {
console.log("button clicked");
var url = $(this).attr('data-url').replace('/', '');
console.log("url:",url); // this returns my customer number but is not used in the code below
$.ajax({
url: $(this).attr("data-url"),
type: 'get',
success: function(data) {
console.log("success");
modalDiv.html(data);
$("#myEdit").modal(); //#myEdit is the ID of the modal
},
error : function() {
console.log("Error: this did not work"); // provide a bit more info about the error to the console
}
});
});
a tag in form
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
Needless to say, I keep receiving the error console.log message.
Below is the complete codebase.
Model:
class Kunde(models.Model):
avd = [('610','610'), ('615', '615'), ('620', '620'), ('625', '625'), '630', '630'), ('635', '635'),('640', '640'),('645', '645'), ('650', '650'), ('655', '655')]
avdeling = models.CharField(max_length=3, choices=avd)
selskap = models.CharField(max_length=50, unique=True)
kundenr = models.CharField('Kundenummer', max_length=15, unique=True, primary_key=True)
gatenavn = models.CharField(max_length=50,)
postnr = models.CharField('Postnummer', max_length=4)
poststed = models.CharField(max_length=30)
kommune = models.CharField(max_length=30)
timestamp = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
def get_absolute_url(self):
return reverse("dashboard:index")
def __str__(self):
return self.selskap
class Meta:
ordering = ['selskap']
Urls
app_name = "dashboard"
urlpatterns = [
path('', views.dashboard, name='index'),
path('', views.customer_list, name='customer_list'),
url(r'^(?P<kundenummer>[0-9]+)$', views.customer_update, name='customer_update'),
]
Views:
main view to display the table
def dashboard(request):
template = 'dashboard/index.html'
if request.user.groups.filter(name__in=['Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='630') | Q(avdeling='635')).all()
elif request.user.groups.filter(name__in=['Nord']).exists():
queryset = Kunde.objects.filter(Q(avdeling='610') | Q(avdeling='615') | Q(avdeling='620')).all()
elif request.user.groups.filter(name__in=['Øst']).exists():
queryset = Kunde.objects.filter(Q(avdeling='660') | Q(avdeling='655') | Q(avdeling='650')).all()
elif request.user.groups.filter(name__in=['Sør']).exists():
queryset = Kunde.objects.filter(Q(avdeling='640') | Q(avdeling='645')).all()
elif request.user.groups.filter(name__in=['Nord-Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='625')).all()
else:
queryset = Kunde.objects.all()
context = {
"object_list": queryset,
}
return render(request, template, context)
view to display the modal with
def customer_update(request, kundenr=None):
template = 'dashboard/index.html'
instance = get_object_or_404(Kunde, kundenr=kundenr)
context={
'selskap': instance.selskap,
'instance': instance,
}
return render(request, template, context)
HTML table
<div class"container-table" style="overflow-x:auto;">
<table class="display table table-bordered table-condensed" id="table_kundeliste">
<thead class="thead-inverse">
<tr>
<th>Avdeling</th>
<th>Selskap</th>
<th>Kundenr.</th>
<th>Poststed</th>
<th>Kommune</th>
<th>Rediger</th>
</tr>
</thead>
<tbody>
{% for kunde in object_list %}
<tr>
<td> {{ kunde.avdeling }} </td>
<td> {{ kunde.selskap }} </td>
<td> {{ kunde.kundenr }} </td>
<td> {{ kunde.poststed }} </td>
<td> {{ kunde.kommune }} </td>
<td>
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
this part include modal in html
<div id="modal-div" class="modal-div">
{% include 'dashboard/customer-modal.html' %}
</div>
this is the modal template itself
<div class="modal fade" id="myEdit" role="dialog">
<div class="modal-dialog">
<form class="well contact-form" method="post" action="{% url dashboard:'customer_update'}">
{% csrf_token %}
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<label for="avdeling">Avdeling:</label>
<input type="text" class="form-control" required="" name="avdeling" value="{{ instance.avdeling }}" id="avdeling">
<label for="selskap">Selskap:</label>
<input type="text" class="form-control" required="" name="selskap" value="{{ instance.selskap }}" id="selskap">
<label for="kundenummer">Kundenummer:</label>
<input type="text" class="form-control" required="" name="kundenummer" value="{{ instance.kundenr }}" id="kundenummer">
<label for="gatenavn">Gatenavn:</label>
<input type="text" class="form-control" required="" name="gatenavn" value="{{ instance.gatenavn }}" id="gatenavn">
<label for="postnummer">Postnummer:</label>
<input type="text" class="form-control" required="" value="{{ instance.postnr }}" name="postnummer" id="postnummer" >
<label for="poststed">Poststed:</label>
<input type="text" class="form-control" required="" value="{{ instance.poststed }}" name="poststed" id="poststed" >
<label for="kommune">Kommune:</label>
<input type="text" class="form-control" required="" value="{{ instance.kommune }}" name="kommune" id="kommune" >
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Valider</button>
<button value="" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>

Categories