how to remove a newletter popup when someone sucscribes in django - python

when someone subscribes to the newsletter i automatically want to remove the popup for the user that just subscribed, i tried create a subscribed = False then change it to subscribed = True when a user subscribes. but it doesnt work. i can easily achieve this is a user is logged i, but in this case even unauthenticated users can also subscribe to the newsletter so that is where the issue comes in.
views.py
subscribed = False
if request.method == "POST":
form = NewsLetterForm(request.POST)
if form.is_valid:
form.save()
messages.success(request, f"Subscription Successfull, Thank you!! - Now check your mail")
subscribed = True
return redirect('/')
else:
form = NewsLetterForm()
templates.html
{% if subscribed != True %}
<p class="mb-0">Subscribe to our <b>NewsLetter</b></p>
<form class="form-inline" method="POST">
{% csrf_token %}
{{form.email}}
<button type="submit" class="btn btn-success-soft btn-sm" type="submit">Get Now</button>
{% endif %}

Django Close Bootstrap Modal On Submit
this solved my question for me, i had to do was close it when a user submits the form

Related

Django restricting users from updating/deleting other users posts

views.py
#login_required(login_url='/login')
def updatepost(request,pk):
post = Post.objects.get(id=pk)
form = PostForm(instance=post)
if request.method =='POST':
form = PostForm(request.POST, request.FILES, instance=post)
if form.is_valid():
form.save()
return redirect ('mainpage')
context = {'form':form}
return render( request, 'postform.html', context )
postform.html
{% include 'main.html'%}
{% block content %}
{%if user.is_authenticated%}
{% if user.id == post.user.id%}
<div>
<form method="POST" action ="">
{% csrf_token %}
{{form.as_p}}
<input type="Submit" value ="Submit"/>
</form>
</div>
{%endif%}
{%endif%}
{% endblock content %}
I am trying to restrict user who is logged in - from updating , deleting other users posts.
However when I Try to use {% if user.id == post.user.id%} , the page becomes blank even for the user who is editing his own post. The same goes for deleting.
It works on mainpages - where posts are displayed (it hides edit and delete buttons).
What is the reason that the post is not showing inside the template ?
I don't understand that even {{post.user}} in postform.html does not appear , neither on deleteform etc. - why this data of objects of a post is not being sent to postform.html ?
You should change the context to access the post instance from your template.
context = {'form': form, 'post': post}
You can only access the context values from the templates. So pass the ones you want to use while you are returning a response.

Button not sending POST request to update object django

I have a scheduling app with Event objects and I'm trying to create a form that will allow the user to update an Event that already exists by the press of the button. However, when the user presses the button it doesn't seem to do anything. It just refreshes the page.
{% for a in availability %}
<form method='POST'>
<li><a class="btn btn-primary" href="{% url 'updateevent' a.id %}" type="submit" role="button">{{a.day}}: {{a.start_time}} - {{a.end_time}}</a></li>
</form>
{% endfor %}
view.py:
def updateevent(request, pk):
if request.method == 'POST':
try:
form = EventForm(data=request.POST, instance=post)
updatedEvent = form.save(commit=False)
updatedEvent.requester_user = request.user
updatedEvent.notes = None
updatedEvent.save()
return redirect('/')
except ValueError:
print(form.errors)
return render(request, 'events/createevent.html', {'form':EventForm(), 'error':'There was an error. Please make sure you entered everything correctly!'})
else:
return redirect('/')
I want the user that presses the button to become the "requester_user", a blank field in my Event object. How can I make this happen?
Anchor tag triggers GET request. You should use <button type="submit"></button> or <input type="submit"> for POST request.

Cancel the POST when the page is refreshed

My problem is: when an user refresh a form, the data in the Form is sent.
I have a Form with a POST request.
The user writes his name, mail and a message. If the mail is correct, the message is sent.
In my view, if the Form is valid, I add the message in my model Message.
After that I disable the "Send" button. But if the user refreshes the page, my view is called, and another row is added in my model.
I would like, when the user refreshes the page, to block the POST.
My View:
def contact(request):
form = MessageForm(request.POST or None)
if form.is_valid():
name = form.cleaned_data['name']
message = form.cleaned_data['message']
mail = form.cleaned_data['mail']
new_message = Message()
new_message.name = name
new_message.message = message
new_message.mail = mail
new_message.save()
envoi = True
return render(request, 'vautmieux/contact.html', locals())
My URL:
path('contact/', views.contact, name='contact'),
My HTML:
<form action="{% url "contact" %}" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
{{ form.name }}
{{ form.mail }}
</div>
<div class="col-md-6" >
{{ form.message }}
</div>
<button id="sendMessageButton" type="submit">ENVOYER LE MESSAGE !</button>
</div>
{% if envoi %}Votre message a bien été envoyé !{% endif %}
</form>
This is the main reason why people implement the Post/Redirect/Get pattern [wiki]. In case of a successful POST request, you should return a redirect to a URL. As a result the browser will perform a GET, and in case the browser thus performs a refresh later, it will make a GET again.
def contact(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
form.save()
return redirect('some-message-successful-view')
else:
form = MessageForm()
return render(request, 'vautmieux/contact.html', {'form': form})
Here 'some-message-successful-view' needs to be replaced with the name of a view you trigger when sending a message was succesful. This can be the same view as the one defined here. I advice to use Django's message framework [Django-doc] to send a message to the user that the message has been submitted successfully.

Redirect to Bootstrap modal instead of error404, Django request.user

I am struggling with an request.user statement in Django.
Through those all hours what I wanted to achieve is:
Only the "user" (author) of the ShiftReport (simply a post) should be able to edit the ShiftReport.
So far I have managed to do that, and when I am logged in as another user I receive an error 404, whereas logged in as a post creator I am able to edit the post - Great!.
However, instead of that 404 Error I would just like to throw a Bootstrap modal saying access denied.
My 'views.py':
def update(request, shiftreport_id=None):
title = 'Edit Shift Report by'
instance = get_object_or_404(ShiftReport, pk=shiftreport_id, user=request.user)
form = shiftreportForm(request.POST or None, request.FILES or None, instance=instance)
confirm_message = None
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
title = "Thanks"
confirm_message = "Shift Report has been updated!"
form = None
context = {
"title": title,
"instance": instance,
"form": form,
"confirm_message": confirm_message,
}
return render(request, 'shift/edit.html', context)
My 'detail.html':
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-center">
<li>New Shift Report</li>
<li>All Shift Reports</li>
{% if not request.user %}
with above statement I can edit my own post and I get Error404 when I
want to edit a post from another user.
When I change it to {% if request.user %}, my modal works but then I cannot edit any of the posts, neither mine neither from another user.
<li>Edit Shift Report Nr.{{ shiftreport.id }}</li>
<li>Delete Shift Report</li>
{% else %}
<li>Edit Shift Report Nr.{{ shiftreport.id }}</li>
<li>Delete Shift Report</li>
{% endif %}
</ul>
<form class="navbar-form navbar-right" method="GET" action="">
<input type="text" class="form-control" name="q" placeholder="Search..." value="{{ request.GET.q }}">
</form>
</div>
Hope construction of my question make sense a little, the issue on the other hand doesn't make any sense to me... would appreciate any help.
Thanks.

In Django registration, if username already exists do something

this is a very basic and quick question in Django.
So in my views, where I am handling the registration, if a user tries to register
with a username that already exists I want to just give a message, like a span next to the
form, saying, "wrong username".
How do I print that message?
Thank you.
This is my part of code:
def register(request):
if request.method == 'POST':
if User.objects.filter(username = request.POST['username']).exists():
#I want to show next to the username textfield in registration form,
#a span for example that says "Wrong Username"
As suggested in a comment above, you should do it in form's clean method which would make things easier. But if you must do it in a view, here's an example:
if request.method == 'POST':
try:
user_exists = User.objects.get(username=request.POST['username'])
return HttpResponse("Username already taken")
except User.DoesNotExist:
# Username doesn't exist
# Do other validation ...
Then show the response in a span using jQuery, or something else.
To get HTTPResponse message, you have to use ajax instead form submit.
Here i am assuming you are using following like html page code.
<input type="text" name="username" id="username"/> <p id="error"></p>
<input type="button" value="Register" id="register">
Now, You have to make an ajax call on button's click event like:
(i assume that you have knowledge of ajax call.)
$("#register").on('click', function(){
var username=$("#username").val();
$.ajax({
.
.
.
success: fuinction(data){
if(data=="error occured"){
$("error").append("wrong username");
}
}
})
});
and views.py code is like this:
def register(request):
if request.method == 'POST':
if User.objects.filter(username = request.POST['username']).exists():
return HTTPResponse("error occured")
I want to modify an answer from above which can be more easier.... i think :) haha:
def register(request):
alert = {
"username": request.GET.get('username', ''),
}
if request.method == 'POST':
username = request.POST.get('username', '')
if User.objects.filter(username = request.POST['username']).exists():
alert['username'] = "Username already exists"
return render(request, 'interface/signup.html', alert)
and in your html: lets just say -->
<form method="POST"> {% csrf_token %}
<h3>Sign Up</h3>
<label class="label">Username:</label><input type="text" name="username" class="form-control" /><br>
{% if username %}
<div class="alert alert-danger alert-dismissible">
×
{{ username }}
</div>
<br>
{% endif %}
</form>
def register(request):
form = UserCreationForm(request.POST)
if form.is_valid():
else:
# Form is invalid, this includes the user already existing
I know it's 2 years late but none of the answers had it and django has a built in way of solving it.

Categories

Resources