I am not sure is the post function is error - python

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>

Related

Modal window not called after button click

I'm making my first website, using Django, python and bootstrap 5, I want a person to click the "submit" button after filling out the form and after that a modal window pops up in which it would say that "everything is OK, your application has been created"
<div class="row mt-5 mb-5 p-2">
<form action="{% url 'feedback_view' %}" method="POST">
{% csrf_token %}
<div class="col-md-6 mb-2">
<label for="exampleInputName" class="form-label">Ваше Имя</label>
<input name="name" class="form-control" id="exampleInputName" aria-describedby="NameHelp">
</div>
<div class="col-md-6 mb-2">
<label for="exampleInputphone" class="form-label">Ваш Телефон</label>
<input name="phone" class="form-control" id="exampleInputphone" aria-describedby="NameHelp" placeholder="+7 (918) 000-00-00">
</div>
<button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">send</button>
</form>
</div>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">send_btn</button>
but for some reason the "send" button does not work, but the "send_btn" button works, which I made to check the problem. all I understand at the moment is what bothers me, type="submit" because in the afternoon there is type="button". How can I solve this problem, given that this is a form submission button? this is the window code:
{% if messages %}
{% for message in messages %}
<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">
<p class="reviews">{{ message }}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}
it's views.py
class FeedBackView(View):
def post(self, request):
form = FeedBackForm(request.POST)
if form.is_valid():
form.save()
messages.add_message(request, settings.MY_INFO, 'now call you!')
else:
messages.add_message(request, settings.MY_INFO, 'something was wrong')
return redirect("/")

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

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

How to send data to view from form after asking for confirmation?

I created a simple form where I'm asking for user input and then posting that to the database. Now I would like the user to confirm the data in form is correct, and for that I'm using a Bootstrap modal.
How can I send the data from the form to the view when pressing the 'OK' button on the modal.
I'm new to the Django framework, and maybe there is another better way without using bootstrap modals.
Form:
class ReportForm(forms.Form):
report_title = forms.ChoiceField(choices=get_report_titles())
report_link = forms.CharField(widget=forms.Textarea, required=False)
Html file:
<form class="w-100" action="" method="post">
{% csrf_token %}
<label class="pl-0 mt-auto mr-2">Report Name</label>
<select name="report_title" class="form-control report-name">
<option selected>Select report</option>
{% for name in report_names %}
<option>{{ name }}</option>
{% endfor %}
</select>
<div class="my-1 col-lg-12 float-left pl-0">
<label>Report Link</label>
<input class="form-control bg-white" type="text" id="report" name="report_link">
</div>
<input id="confirm" value="Save" type="button" data-toggle="modal" data-target="#exampleModalCenter" class="btn btn-outline-success" />
</form>
<!-- Modal -->
<div class=" modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Make sure you have the right title and link.
</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</button>
</div>
</div>
</div>
</div>
View:
def report_view(request):
if request.method == 'POST':
form = ReportForm(request.POST)
if form.is_valid():
report_title = form.cleaned_data['report_title']
report_link = form.cleaned_data['report_link']
new_report = Report(title = report_title, link = report_link)
new_report.save()
Simply update your code with these lines, add id="exampleForm".
start form tag with
<form class="w-100" action="" id="exampleForm" method="post">
Replace Save button with (add id="save"):
<button type="button" id="save" class="btn btn-primary">Save</button>
and finally add this script at the bottom to submit your form when save is clicked:
<script>
$("#save").on("click", function(e) {
$("#exampleForm").submit();
});
</script>
also I feel your view is not written correctly. It should be something like this, I'm not sure what you're trying to do:
def report_view(request):
if request.method == 'POST' and form.is_valid():
form = ReportForm(request.POST)
report_title = form.cleaned_data['report_title']
report_link = form.cleaned_data['report_link']
new_report = Report(title = report_title, link = report_link)
new_report.save()
Let me know if you still need help
This needs changing because you're not giving any values.
<select name="report_title" class="form-control report-name">
<option selected>Select report</option>
{% for name in report_names %}
<option>{{ name }}</option>
{% endfor %}
</select>
Try:
<select name="report_title" class="form-control report-name">
<option selected>Select report</option>
{% for name in report_names %}
<option value="{{name.pk}}">{{ name }}</option>
{% endfor %}
</select>
where name.pk is the value relating to the choices.
Also, if you change your form to a ModelForm you can just do:
if form.is_valid():
new_report = form.save()

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