Web2py: Using a bootstrap modal for insert, update and delete - python

I would like to use a bootstrap modal to create new and update existing records.
It works for new records but I cannot get it to work for updating existing ones and also not to delete.
What am I doing wrong in the post.load views and in the comments.py.get_comment code?
I would appreciate any help or guidance.
models/tables.py
db.define_table('comment_post',
Field('title','string',label='Comment title', requires=IS_NOT_EMPTY()),
Field('body','text',label='Your comment', requires=IS_NOT_EMPTY()),
auth.signature)
controllers/default.py
def index():
return dict()
views/default/index.html
{{extend 'layout.html'}}
Comments
{{=LOAD('comments','post.load',ajax=True)}}
controllers/comments.py
#auth.requires_login()
def post():
form = SQLFORM(db.comment_post, formstyle='bootstrap3_stacked').process()
if form.accepted:
response.flash = 'You have successfully submitted the form'
elif form.errors:
response.flash = 'Please check your form for errors'
else:
response.flash = 'Please complete the form'
comments = db(db.comment_post).select(orderby=~db.comment_post.id, limitby=(0, 3))
return dict(form=form, comments=comments)
#auth.requires_login()
def get_comment():
r = db.auth_user(request.vars.id) or redirect(URL('post'))
form = SQLFORM(db.comment_post, r).process()
return form.xml
#auth.requires_login()
def delete_comment():
return db(db.comment_post.id == request.vars.id).delete()
views/comments/post.load
{{for post in comments:}}
<div class="post">{{=post.title}}: on <small>{{=post.created_on}}</small> {{=post.created_by.first_name}}
<small>said:</small> "<span class="post_body">{{=post.body}}</span>"
{{=A('Edit', callback=URL('welcome', 'comments', 'get_comment', vars={'id': post.id}), target="form_load")}}
{{=A('Delete', callback=URL('welcome', 'comments', 'delete_comment', vars={'id': post.id}))}}
</div>
{{pass}}
<hr>
<!-- Button trigger modal: http://getbootstrap.com/javascript/ -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div id="form_load" class="modal-body">
{{=form}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Related

Django form not displaying in Bootstrap 5 Modal pop-up window

Problem
I'm trying to transfer my current form on a new page to a Modal window that appears on the current page but I can't get the form fields to appear.
I have thoughts that it may be due to my urls or the view that worked previously doesn't work with a Modal pop-up.
Views
class AssetView(TemplateView):
template_name = 'coinprices/my-dashboard.html'
def get(self, request, **kwargs):
form_a = AssetForm(prefix='form_a')
return render(request, self.template_name, {
'form_a': form_a
})
def post(self, request):
form_a = AssetForm(request.POST, prefix='form_a')
if form_a.is_valid():
post = form_a.save(commit=False)
post.user = request.user
post.save()
return redirect('dashboard')
args = {
'form_a': form_a
}
return render(request, self.template_name, args)
HTML
<!-- Button trigger modal -->
<button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#exampleModal">
Add Asset
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form method="post">
{% csrf_token %}
{{ form_a.as_p }}
<button class="btn btn-outline-success btn-sm">Confirm</button>
</form>
<a href="/coinprices/my-dashboard">
<button class="btn btn btn-outline-dark btn-sm">Dashboard</button>
</a>
</div>
</div>
</div>
</div>
URLS
urlpatterns = [
path('my-dashboard/', get_asset_price, name='dashboard'),
path('my-dashboard/', AssetView.as_view(template_name='coinprices/my-dashboard.html'), name='asset'),
]

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>

Hello guys when i click on the button that is the title i got the same blog for each title

when i clikc on django title i get django post and when i click on javascript title i get django post ether am not using any frame_work and this my blog page i really try every solution i know but Unfortunately nothing happend
And here an image
blog.html
{% for blog in blogs %}
<div class="col-xl-12 col-md-6 col-xs-12 blog">
<div class="right-text-content">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
<h2 class="sub-heading">{{blog.title|title}}</h2>
</button>
<!-- Modal -->
<div class="modal fade align-self-end mr-3 " id="myModal" tabindex="1" role="dialog"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{blog.title|title}}</h5>
<h6 class="float-right">{{blog.created_at}}</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{{blog.content|linebreaks}}
</div>
<div class="modal-footer">
<h5>Created by {{blog.name}}</h5>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<p>
<br>
<a rel="nofollow noopener" href="{{blog.name_url}}" target="_parent">{{blog.name}}</a>
<br>
{{blog.content|linebreaks}}
</p>
{{blog.created_at}}
</div>
</div>
{% endfor %}
views.py
from django.shortcuts import render
from .models import DigitalTeam, Blog
def index(request):
pers = DigitalTeam.objects.all()
return render(request, 'index.html', {'pers':pers})
def blog(request):
pers = DigitalTeam.objects.all()
blogs = Blog.objects.all()
return render(request, 'blog.html', {'pers':pers, 'blogs':blogs})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('blog', views.blog, name='blog'),
]
So guys what am i missing
To get individual blog details in the modal you need to pass the blog id to the modal as a prop.
It can be done by adding blog.id in the button data-target prop and receive the blog.id in modal id prop.
the solution in given below,
{% for blog in blogs %}
<div class="col-xl-12 col-md-6 col-xs-12 blog">
<div class="right-text-content">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal{{blog.id}}">
<h2 class="sub-heading">{{blog.title|title}}</h2>
</button>
<!-- Modal -->
<div class="modal fade align-self-end mr-3 " id="myModal{{blog.id}}" tabindex="1" role="dialog"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{blog.title|title}}</h5>
<h6 class="float-right">{{blog.created_at}}</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{{blog.content|linebreaks}}
</div>
<div class="modal-footer">
<h5>Created by {{blog.name}}</h5>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<p>
<br>
<a rel="nofollow noopener" href="{{blog.name_url}}" target="_parent">{{blog.name}}</a>
<br>
{{blog.content|linebreaks}}
</p>
{{blog.created_at}}
</div>
</div>
{% endfor %}

How to display Date in popup Modal in Django?

I want to display data in the popup, I have a list on products but when a user clicks on the product id then it should be open in popup according to that product id.
here is my views.py file...
def myview(request):
datas=TestForm.objects.all
template_name='test.html'
context={'datas':datas}
return render(request, template_name, context)
def myview(request, id):
display=TestForm.objects.get(pk=id)
template_name='test.html'
context={'display':display}
return render(request, template_name, context)
here is my test.html file...
{% for a in datas %}
<button type="button" class="btn btn-primary" data-toggle="modal" data-
target="#exampleModal">
{{a.product_id}}
</button>
{% endfor %}
<!-- Modal -->
<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">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<tr>
<td>{{datas.name}}</td>
<td>{{datas.price}}</td>
<td>{{datas.category}}</td>
</tr>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
Currently, it's displaying the only popup fields on click all products id's, Please let me know how it can display product data according to click product id.
You can solve this issue by making the modal id attribute unique with the pk value.
{% for a in datas %}
<button type="button" class="btn btn-primary" data-toggle="modal" data-
target="#exampleModal{{a.pk}}">
{{a.product_id}}
</button>
{% endfor %}
Now in the modal
{% for a in datas %}
<div class="modal fade" id="exampleModal{{a.pk}}" tabindex="-1" role="dialog" aria-
labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
.......
{% endfor %}

Django CreateView messes up bootstrap-modal

Rather a curious problem: My modal works perfectly until I associate the template containing it with a CreateView! So for example if I change template_name in BrandCreateView to new_brand_form1.html, new_brand_form2.html will load perfectly in the modal. But as it stands now, when I click the button that triggers the modal, I get this.
views.py:
class BrandCreateView(SuccessMessageMixin ,generic.edit.CreateView):
template_name = 'new_brand_form2.html'
model = Brand
fields = ['name']
def get_success_url(self):
current_business = Business.objects.filter(owner=self.request.user).first()
current_business.brands.add(self.object.pk)
return reverse_lazy('index', kwargs={'pk': self.object.pk})
# pre assign-current business to the business field
def get_initial(self):
initial = super().get_initial()
initial['business'] = Business.objects.filter(owner=self.request.user).first()
self.business_name = initial['business']
return initial
def form_valid(self, form):
form.instance.user = self.request
form.instance.business = self.business_name
try:
return super(BrandCreateView, self).form_valid(form)
except IntegrityError:
form.add_error('name' ,'You already have a brand by that name')
return self.form_invalid(form)
new_brand_form2.html:
<div class="modal fade" tabindex="-1" role="dialog" id="createbrand">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
{{ form.as_p }}
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
EDIT:
Might this be the problem? The button that triggers the modal obviously points to the the URL that is associated with the CreateView in the urls.py (named 'createbrand`), maybe it's going in an un-ending cycle...?
Here's the button that triggers the modal
<button class="btn btn-default btn-sm" type="button" data-toggle="modal" href="{% url "createbrand" %}" data-target="#createbrand">
<span class="glyphiconglyphicon-plus">Add New</span>
</button>
You're trying to set href attr to HTML button tag?
Anyway, your button after your click tryin to act like a bootstrap-modal since you add all attributes need for it. That's why maybe you get some bootstrap-modal acting in your page. But in fact, it cannot find data-target="#createbrand" in your page, because your modal is somewhere else :)
Try these:
modal-snippet.html:
<div class="modal fade" tabindex="-1" role="dialog" id="createbrand">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<form method="POST" action="{% url 'createbrand' %}" class="form-horizontal" id="brandForm">
<div class="modal-body">
{% csrf_token %}
<input type="text" id="id_your_field_name" name="your_field_name" placeholder="Enter..."/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button> <!-- onclick="addBrand()" -->
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
{% block javascript %}
// You can use also AJAX request, but you
// need to change your view and add onclick for this method to button
function addBrand(e){
var brandForm = $("#brandForm");
$.ajax({
type: 'POST',
url: "{% url 'createbrand' %}",
data: brandForm.serialize(),
success: function(res){
if(res.msg !== "Error") {
// Do something if error
} else {
// Do something if success
}
}
})}
{% endblock javascript %}
views.py:
// I believe you can make it better
def add_brand(request):
if request.method == "POST":
form = BrandForm(request.POST)
if form.is_valid():
form.save(commit=True)
return reverse_lazy('your-page')
urls.py:
...
from .views import add_brand
url(r'^url/path/$', add_brand, name='createbrand'),
...
And in your main page where you want to place your modal add:
{% include 'app/snippets/modal-snippet.html' %}

Categories