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'),
]
Related
I try to look up my signup view as a bootstrap modal but when click form doesn't show
class SignUpView(CreateView):
form_class = UserCreationForm
template_name = 'avapp/signup.html'
success_message = 'Success: Sign up succeeded. You can now Log in.'
success_url = reverse_lazy('index')
views.py
{% extends 'base.html' %}
{% load static %}
{% block content %}
<h1 style="text-align: center;color: #568203 " > Avakado App</h1>
<center>
<a class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#exampleModal " >
<img style="text-align: center" src="{% static '1_org.jpg' %}" width="300" height="450" >
</a>
</center>
{% endblock %}
index.html
<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>
<form action="/signup" method="POST">
<div class="modal-body">
{% csrf_token %}
{{form}}
</div>
</form>
<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>
</div>
</div>
signup.html
this is the modal form looks like
Can I figure it out without using Ajax or something else or do I have to change my signup view from class based views to something else
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>
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
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' %}
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>