Why the form is not JSON serializable? - python

I am using Django and I am trying when a button is clicked to get data from the database and fill a form with them through AJAX.
I get the error TypeError: Object of type 'EditProductForm' is not JSON serializablefrom the edit_product_view in my views.py
Below is the code I am working with:
-urls.py
from django.conf.urls import url
from . import views
app_name = "products"
urlpatterns = [url(r'^products', views.ProductsView.as_view(), name="products"),
url(r"^product/new", views.add_new_product_view, name="add_new_product"),
url(r"^product/(?P<id>[0-9]+)/edit/", views.edit_product_view, name="edit_product")]
-views.py
from django.views.generic import DetailView, ListView, TemplateView
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from . import models
from products.forms import AddNewProductForm, EditProductForm
def index(request):
return render(request, 'products/products.html')
class ProductsView(ListView):
context_object_name = "products"
model = models.Product
template_name = "products/products.html"
form = AddNewProductForm()
def get_context_data(self, **kwargs):
context = super(ProductsView, self).get_context_data(**kwargs)
context["products"] = models.Product.objects.all().order_by("title")
context["form"] = self.form
return context
def add_new_product_view(request):
if request.method == "POST":
form = AddNewProductForm(request.POST)
if form.is_valid():
form.save(commit=True)
return JsonResponse({'msg': 'Data saved'})
else:
print("ERROR FORM INVALID")
return JsonResponse({'msg': 'ERROR FORM INVALID'})
else:
form = AddNewProductForm()
return JsonResponse({'form': form})
def edit_product_view(request, id):
print(request.method)
instance = get_object_or_404(models.Product, id=id)
form = EditProductForm(instance=instance)
if request.method == "POST":
form = EditProductForm(request.POST, instance=instance)
if form.is_valid():
form.save(commit=True)
return JsonResponse({'form': form})
else:
print("ERROR FORM INVALID")
return JsonResponse({'form': form})
-products.html
{% extends "products/base.html" %}
{% load static %}
{% block title %}My Products{% endblock %}
{% block content %}
<div class="container" id="my-products-table-container">
<h2 class="text-left caption">Add, view and edit products</h2>
<hr>
<table class="table table-striped table-sm table-bordered" id="my-products-table">
<thead class="thead-inverse">
<tr class="head-row">
<th>Title</th>
<th>Description</th>
<th>Year</th>
<th>Manufacturer</th>
</thead>
<tbody>
{% for product in products %}
<tr class="table-row">
<td>{{ product.title }}</td>
<td>{{ product.description }}</td>
<td>{{ product.year_manufactured }}</td>
<td>{{ product.manufacturer }}</td>
<td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addNewProductModalForm">Add New product</button></td>
<td><button onclick="findMyForm({{ product.pk }})">Update product</button></td>
{% endfor %}
</tbody>
</table>
</div>
<!-- Modal Add New Product-->
<div class="modal fade" id="addNewProductModalForm" tabindex="-1" role="dialog" aria-labelledby="addNewProductModalFormLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form class="form" id="add_new_product_form">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addNewProductModalFormLabel">Add New Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% csrf_token %}
{{ form.as_p }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" onclick="addNewProduct()">Submit</button>
</div>
</div>
</form>
</div>
</div>
<!-- Modal Edit-->
<div class="modal fade" id="editProductModalForm" tabindex="-1" role="dialog" aria-labelledby="editProductModalFormLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form class="form" id="edit_product_form" >
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editProductModalFormLabel">Edit Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% csrf_token %}
<div id='showForm'></div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Submit!">
</div>
</div>
</form>
</div>
</div>
<!-- JS Scripts -->
<script src="{% static "products/js/addProduct.js" %}"></script>
<script>
function findMyForm(productKey) {
$('#editProductModalForm').modal('show');
$.ajax({
type: 'GET',
url: '/product/' + productKey + '/edit/',
success: function(res) {
$("#showForm").html(res);
}
})}
</script>
{% endblock %}
-addProduct.js
function addNewProduct(e) {
var addNewProductForm = $("#add_new_product_form");
$.ajax({
type: 'POST',
url: '/product/new/',
data: addNewProductForm.serialize(),
success: function(res){
alert(res['msg'])
}
})
}
What happens is that when I click <button onclick="findMyForm({{ product.pk }})">Update product</button> the function findMyForm({{ product.pk }}) runs.
Then a get request is called on '/product/' + productKey + '/edit/' through AJAX, based on the urls.py and views.py, edit_product_view is called to pass the form which is filled with the appropriate data.
At this point, it says that TypeError: Object of type 'EditProductForm' is not JSON serializable. I can't figure it out.

The object 'EditProductForm' is not JSON serializable, what you need is to return the form as HTML str, change your views.py:
from
return JsonResponse({'form': form})
to
return HttpResponse(form.as_p()) # return form as html str

Related

Django UpdateView Bootstrap Modal - i've got empty form in modal window

I've got empty Bootstrap modal form with Django UpdateView(CBV)
The most important question without using js , I will not be able to display data in a modal window? (I only use bootstrap.bundle.min.js in base.html)
Modal window show fields of empty form
view.py
class HistoryPamentsByService(ListView):
model=Payments
form_class=PaymentsForm
template_name ='myflat/history_by_service.html'
context_object_name='flats'
slug_url_kwarg = 'slug'
def get_context_data(self, **kwargs):
context=super().get_context_data(**kwargs)
form=PaymentsForm()
payments=Payments.objects.filter(flats_id=self.kwargs['flats_id'])
context['form']=form
return context
def get_form(self,*args,**kwargs):
super().get_form(*args, **kwargs)
form=PaymentsForm()
return form
def get_queryset(self):
return Payments.objects.filter(slug=self.kwargs['slug'],flats_id=self.kwargs['flats_id'])
class UpdatePayments(UpdateView):
model=Payments
pk_url_kwarg='pk'
template_name='myflat/update_modal.html'
context_object_name='name_flat'
fields=['name_service','amount_of_bill',
'amount_of_real',
'date_of_bill',
'date_of_payment',
'status_payment',
'comments',
'bill_save_pdf']
def get_success_url(self):
return reverse('HistoryPamentsByService',
kwargs={'slug':self.object.slug,
'flats_id': self.object.flats_id})
urls.py
urlpatterns = [ path('history_by_service/<slug:slug>/<int:flats_id>/',
HistoryPamentsByService.as_view(),name='HistoryPamentsByService'),
path('UpdatePayments/<int:pk>/',UpdatePayments.as_view(),name='UpdatePayments'),
]
template
history_by_service.html (for ListView)
{%extends "base.html"%}
{%block content%}
{% for flat in flats %}
<tr>
<td scope="row">{{ forloop.counter }} </td>
<td>{{flat.name_service}}</td>
<td>{{flat.amount_of_bill}}</td>
<td>{{flat.amount_of_real}}</td>
<td>{{flat.date_of_bill}}</td>
<td>{{flat.date_of_payment}}</td>
<td>{{flat.get_status_payment_display}}</td>
<td>{{flat.comments}}</td>
<td>{{flat.bill_save_pdf}}</td>
<td>
<form method="post" action="{% url 'UpdatePayments' flat.pk %}" enctype="multipart/form-data">
{% csrf_token %}
<button type='button' class='btn btn-success btn-sm' id="update_modal"
data-bs-toggle="modal" data-bs-target="#update_modal{{flat.pk}}">
<i class="fa-regular fa-pen-to-square fa-fw"></i>Edit</button>
{% include "myflat/update_modal.html" %}
</form>
{% endfor %}
{% endblock content %}
template
update_modal.html
<div class="modal fade" id="update_modal{{flat.pk}}" data-bs-backdrop="static"
data-bs-keyboard="false" tabindex="-1" aria-labelledby="update_modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="width:auto">
<div class="modal-header">
<h5 class="modal-title " id="update_modalLabel">{{flat.name_flat}}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form method="post" action="{% url 'UpdatePayments' flat.pk %}" enctype="multipart/form-data">
<div class="modal-body">
{% csrf_token %}
{% for field in form %}
{{field}}
{% endfor %}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" >
<i class="fa-solid fa-trash fa-fw" ></i>Save</button>
<button type="button" class="btn btn-warning"
data-bs-dismiss="modal">
<i class="fa-regular fa-circle-xmark"></i>Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
I try add in UpdatePayments(UpdateView) next code:
class UpdatePayments(UpdateView):
model=Payments
pk_url_kwarg='pk'
form_class=PaymentsForm
template_name='myflat/update_modal.html'
context_object_name='name_flat'
def get_context_data(self, **kwargs):
context= super().get_context_data(**kwargs)
obj=Payments.objects.get(pk=self.kwargs['pk'])
form=PaymentsForm(self.request.POST or None ,instance=obj)
context['form']=form
return context
but still nothing in Modal is empty fields!!!
What's wrong, any helps,please!!!

I am not sure is the post function is error

When I press the button to post something, it will return me to the main page, not stay in the forum page and show me what I just post.
Here is the view.py
def forum(request):
profile = Profile.objects.all()
if request.method == "POST":
user = request.user
image = request.user.profile.image
content = request.POST.get('content','')
post = Post(user1=user, post_content=content, image=image)
post.save()
alert = True
return render(request, "forum.html", {'alert':alert})
posts = Post.objects.filter().order_by('-timestamp')
return render(request, "forum.html", {'posts':posts})
def discussion(request, myid):
post = Post.objects.filter(id=myid).first()
replies = Replie.objects.filter(post=post)
if request.method=="POST":
user = request.user
image = request.user.profile.image
desc = request.POST.get('desc','')
post_id =request.POST.get('post_id','')
reply = Replie(user = user, reply_content = desc, post=post, image=image)
reply.save()
alert = True
return render(request, "discussion.html", {'alert':alert})
return render(request, "discussion.html", {'post':post, 'replies':replies})
Here is the html5 code, I don't know why I cannot post the full html code, it tell me there is an error.
<div class="modal fade" id="questions" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% if user.is_authenticated %}
<div class="modal-body">
<form action="/" method="POST"> {% csrf_token %}
<div class="form-group">
<label for="exampleFormControlTextarea1">Post Your Question Here</label>
<textarea class="form-control" id="content" name="content" rows="3"></textarea>
</div>
</form>
</div>
{% else %}
<h3>Please Login to post</h3>
{% endif %}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Post</button>
</div>
</div>
</div>
</div>
Does your HTML include form tag with method="post" ? Example below
Make sure to include your button inside this form tag. All should work after that.
<form method="post">
</form>

How can I use two different functions in one HTML page Django

I wanted to create a website where I can List all created forms and also create forms in the same page. But I could'n figure it out. Firstly I tried it with two classes which linked to the same HTML file but then I read that this is wrong then I tried to write the two classes in one with the get post and get_queryset functions. However now I can only create forms and if I am deleting the get function the I can list the created forms.
Thank You very much and here are my views.py and HTML.
views.py
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from django.views import generic
from .models import PostModel
from .forms import PostForm
# Create your views here.
class PostList(generic.ListView):
template_name = 'home.html'
form_class=PostForm
def get_queryset(self):
return PostModel.objects.order_by('-created_on')
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self,request,*args, **kwargs):
form=self.form_class(request.POST)
if form.is_valid():
form.save()
return redirect('home')
return render(request,self.template_name,{'form':form})
class PostDetail(generic.DetailView):
model = PostModel
template_name = 'post_detail.html'
home.html
{% extends "base.html" %}
{%block content%}
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-6 mt-3 left mx-auto">
{% for post in postmodel_list %}
<div class="card mb-4 block">
<a class="overlay" href="{% url 'post_detail' post.slug %}"style="text-decoration:none"> </a>
<div class="card-body inner">
<p style="text-align:right;float:right;margin-top:10px;" class="card-text text-muted h6"><a style="text-decoration:none" href="https://google.com">#{{ post.author }}</a> </p>
<h2 class="card-title">{{ post.title }}</h2>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<div class="col-md-4 float-right ">
<button style= "position: fixed; bottom:50px;" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="#mdo">Open modal for #mdo</button>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
</div>
<div class="modal-body">
<form method="post" style="margin-top: 1.3em;">
{% csrf_token %}
{{ form }}
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="submit" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
<style>
.card{
box-shadow: 0 16px 48px #E3E7EB;
}
</style>
{%endblock content%}
If I understand the question properly you can use CreateView instead of ListView and return the post lists in the context from get_context_data.
class PostList(generic.CreateView):
template_name = 'home.html'
form_class=PostForm
model = Post
def get_context_data(self, **kwargs)
context = super().get_context_data(**kwargs)
context ['postmodel_list'] = PostModel.objects.order_by('-created_on')
return context

Accessing user details in django

I have a question. I have a blog where users can log in and post or comment something. When they are posting or commenting the text appears with their name as links on the right side(see picture). Now I want to have a userprofile page where the email name etc. are displayed. So I have to grab the name from the first template and use it. Now I can grab their name :) but I don't know how to use them. For example the users name is alex. I can display alex on the new template but what I need is something like that. alex.email or alex.name. Thank you very much.
view.py
#login_required
def user_profile(request,username):
return render(request, "user_profile.html",{'username':username})
home.html this is the template where I want to grab his name
{% extends "base.html" %}
{%block content%}
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8 mt-3 left mx-auto">
{% for posts in postmodel_list %}
<div class="card mb-4 block">
<a class="overlay" href="{% url 'post_detail' posts.slug %}"style="text-decoration:none"> </a>
<div class="card-body inner">
<h2 class="card-title">{{ posts.post }}</h2>
<p style="text-align:right;" class="card-text text-muted h6"><a style="text-decoration:none" href="{%url 'user_profile' posts.author %}">#{{ posts.author }}</a> </p>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<div class="col-md-4 float-right ">
<button style= "position: fixed; bottom:50px;" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="#mdo">Add New Post</button>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New Post</h5>
</div>
<div class="modal-body">
<form method="post" style="margin-top: 1.3em;">
{% csrf_token %}
{{ form|crispy }}
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="submit" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
<style>
.card{
box-shadow: 0 16px 48px #E3E7EB;
}
</style>
{%endblock content%}
and here I want to have his informations.
user_profile.html
{% extends "base.html" %}
{%block content%}
{%load static%}
<div class="card float-left">
<img src="{% static 'images/img.jpg' %}" alt="John" style="width:100%">
{%if user.is_authenticated%}
<h3>{{user.first_name}} {{user.last_name}}</h3>
<p>{{user.email}}</p>
{%endif%}
<p class="title">CEO & Founder, Beehive</p>
<p>Istanbul Technical University</p
<p><button>Contact</button></p>
</div>
of course now it displays the information of the logged in user but I want to change it depending on which user he clicks
EDIT
now I am trying to get two models and the data from the first template to display on the second template with a cbv. Here is my new view.
class UserProfile(ListView):
template_name = 'user_profile.html'
model=PostModel
user=User.objects.get(username=username)
def get_context_data(self, **kwargs):
context = super(UserProfile, self).get_context_data(**kwargs)
context['posts'] = PostModel.objects.filter(author=user).order_by('created_on')
context['comments'] = CommentModel.objects.filter(author=user).order_by('created_on')
context['profile']=user
return context
but here I got the error:
name 'username' is not defined
You'll have to look the user up, e.g.:
#login_required
def user_profile(request, username):
if request.user.username != username:
user = User.objects.get(username=username)
else:
user = request.user
return render(request, "user_profile.html", {'profile': user})
You'll need to use {{ profile.username }} etc. in your template (Django has reserved {{ user.xxx }} for itself and will overwrite it.
You should probably add some more permissions to the view. As presented above, any logged in user can view any other logged in user's profile, i.e. change the if to:
if request.user.username != username and can_view(request.user, username):
....
(then implement the can_view(userobject, username) function).
#login_required
def user_profile(request, username):
if request.user.username != username:
user = User.objects.get(username=username)
else:
user = request.user
posts=PostModel.objects.filter(author=user)
comments=CommentModel.objects.filter(author=user)
return render(request, "user_profile.html", {'profile': user,'posts':posts,'comments':comments})
I solved my problem so and I am happy :)

My Django website not showing any forms when I edit

I'm building a website using Django.
And for somereason, the dictionary using all the forms is not showing at all..
When I click my Edit button the modal is showing without the forms...
forms.server_id needs to contain all the forms using server_id...
the server_id I use to show the previous data when I edit.
But for some reason, it doesn't show any form at all...
index.html -
{% load static i18n util_filters %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/jq-3.2.1/jq-3.2.1/dt-1.10.16/af-2.2.2/b-1.4.2/fc-3.2.3/fh-3.1.3/kt-2.3.2/r-2.2.0/rg-1.0.2/rr-1.2.3/sc-1.4.3/sl-1.2.3/datatables.min.css"/>
<script src="https://use.fontawesome.com/3c2c6890cf.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jq-3.2.1/jq-3.2.1/dt-1.10.16/af-2.2.2/b-1.4.2/fc-3.2.3/fh-3.1.3/kt-2.3.2/r-2.2.0/rg-1.0.2/rr-1.2.3/sc-1.4.3/sl-1.2.3/datatables.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="{% url 'serverlist' %}">DevOps Map</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'serverlist' %}">Servers</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'serverlist' %}">Switches</a>
</li>
</ul>
</div>
</nav>
<style type="text/css">
.wrapper {
display:flex;
}
</style>
</head>
<body>
<div class="container">
<br>
<center><h1 class="display-4">DevOps Server List</h1></center>
<br>
<center><button type="button" class="save btn btn-outline-success btn-lg" data-toggle="modal" data-target=".AddServer">Add Server <i class="fa fa-server fa-lg" aria-hidden="true"></i></button></center>
<table class="table table-hover table-bordered table-condensed" cellspacing="0" width="1300" id="ServerTable">
<thead>
<tr>
<th><center> #</center></th>
<th><center> Server Name </center></th></center>
<th><center> Owner </center></th></center>
<th><center> Project </center></th></center>
<th><center> Description </center></th></center>
<th><center> IP Address </center></th></center>
<th><center> ILO </center></th></center>
<th><center> Rack </center></th></center>
<th><center> Status </center></th></center>
<th><center> Actions </center></th></center>
</tr>
</thead>
<tbody>
{% for server in posts %}
<tr>
<div class ="server">
<td></td>
<td><center>{{ server.ServerName }}</center></td>
<td><center>{{ server.Owner }}</center></td>
<td><center>{{ server.Project }}</center></td>
<td><center>{{ server.Description }}</center></td>
<td><center>{{ server.IP }}</center></td>
<td><center>{{ server.ILO }}</center></td>
<td><center>{{ server.Rack }}</center></td>
<td><h4><span class="badge badge-success">Online</span></h4></td></center>
<td>
<button type="button" class="btn btn-outline-danger" data-toggle="modal" href="#delete-server-{{server.id}}"
data-target="#Del{{server.id}}">Delete <i class="fa fa-trash-o"></i></button>
<button type="button" class="btn btn-outline-primary" data-toggle="modal" href="#edit-server-{{server.id}}"
data-target="#Edit{{server.id}}"> Edit <i class="fa fa-pencil"></i></button>
<div id ="Del{{server.id}}" class="modal fade" role="document">
<div class="modal-dialog" id="delete-server-{{server.id}}">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{% url 'delete_post' server.id %}" method="post">{% csrf_token %}
<h6>Are you sure you want to delete {{ server.ServerName }}?</h6>
<br>
<center><input type="submit" class="btn btn-danger btn-md" value="Confirm"/>
<button type="submit" class="btn btn-secondary" data-dismiss="modal">Cancel</button></center>
</form>
</div>
</div>
</div>
</div>
<div class="modal fade bd-example-modal-sm" id="Edit{{server.id}}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Server <strong>{{ server.ServerName }}</strong> </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% with server.id as server_id %}
{% with forms|get_by_key:server_id as edit_form %}
<form action="{% url 'edit_post' server_id %}" method="post"> {% csrf_token %}
<!--<center> {{ edit_form.as_p }} </center> -->
{% for field in forms.server_id %}
<div class="fieldWrapper">
{{ field.errors }}
<!-- {{ field.label_tag }} -->
<small><strong>{{ field.html_name }}<p align="left"></b> {{ field }}</small> </strong>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="wrapper">
<h2><button type="submit" class="save btn btn-success btn-lg">Confirm</button></h2>
<h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
</div>
</form>
{% endwith %}
{% endwith %}
</div>
</td>
</tr>
{% endfor %}
</tbody>
</h5>
</table>
<div class="modal fade AddServer" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Server</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" novalidate> {% csrf_token %}
<!--<center> {{ form.as_p }} </center> -->
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
<!-- {{ field.label_tag }} -->
<small><strong>{{ field.html_name }}</strong></small><p align="left"></b> {{ field }} </p>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="wrapper">
<h2><button type="submit" class="save btn btn-success btn-lg" >Confirm</button></h2>
<h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
</div>
</div>
</form>
</div>
</div>
</div>
views.py -
# Create your views here.
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.template import RequestContext
from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView
from DevOpsWeb.forms import HomeForm
from DevOpsWeb.models import serverlist
from django.core.urlresolvers import reverse_lazy
from simple_search import search_filter
from django.db.models import Q
class HomeView(TemplateView):
template_name = 'serverlist.html'
def get(self, request):
form = HomeForm()
query = request.GET.get("q")
posts = serverlist.objects.all()
forms = {}
if query:
posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query))
else:
posts = serverlist.objects.all()
#for post in posts:
# form = HomeForm(instance=post)
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form,'forms': forms, 'posts' : posts}
#args = {'form' : form, 'forms': forms, 'posts' : posts}
return render(request, self.template_name, args)
def post(self,request):
form = HomeForm(request.POST)
posts = serverlist.objects.all()
if form.is_valid(): # Checks if validation of the forms passed
post = form.save(commit=False)
post.save()
#form = HomeForm()
return redirect('serverlist')
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form, 'forms': forms, 'posts' : posts}
#args = {'form' : form,'forms': forms, 'posts' : posts}
return render(request, self.template_name,args)
class PostDelete(DeleteView):
model = serverlist
success_url = reverse_lazy('serverlist')
class PostEdit(UpdateView):
template_name = 'serverlist.html'
model = serverlist
form_class = HomeForm
#fields = ['ServerName','Owner','Project','Description','IP','ILO','Rack','Status']
success_url = reverse_lazy('serverlist')
#def get_object(self):
# obj = get_object_or_404(Calification, pk=self.request.POST.get('pk'))
# return obj
This :
{% with server.id as server_id %}
{# ... #}
{{ forms.server_id.as_p }}
just cannot work - it will look for forms["server_id"] (=> use the literal string "server_id" as key). You will need a custom template filter, such as the one described here. And as Daniel Roseman rightly mentions in a comment, you'll have to pass whatever server is supposed to be to your template's context too.
Also note that you're going to get a NameError in HomeView.post - you copy-pasted part of the code filling in your posts dict but not the part instanciating it. You should really factor this out instead of copy-pasting.

Categories