Form post request running wrong view method on Django - python

I'm trying to clone the Instagram web page using Django(version-3.1).
My Django project has an app called 'post'.
One of its template I have a form which is posting a comment to a post. The form post request should call the path('add_comment/',views.add_comment,name='add_comment'), but It's calling path('<slug:slug>/',views.post_details,name='post_details'), instead. And raising DoesNotExist at /post/add_comment error. I added print() statement at the beginning of both add_comment() and post_details() methods to find out which is running when the request is made. I have no idea what I have done wrong.
The project GitHub link - https://github.com/mirasel/Instagram_Clone
the post_details.html template is -
{% extends 'base.html' %}
{% load static %}
{% block title %} post {% endblock %}
{% block profilephoto %} {{ propic.url }} {% endblock %}
{% block body %}
<div>
<div>
<img src="{{post.image.url}}" alt="post" height="250px" width="250px">
</div>
<div>
<a href="{% url 'instagram:profile' post.uploader %}">
<img src="{{uploader.profile_pic.url}}" alt="{{uploader}}" style="border-radius: 50%;" height="24px" width="24px">
{{ post.uploader }}
</a><br>
<p>{{ post.date_published.date }}</p>
</div>
<div>
<p>{{ post.caption }}</p>
</div>
<div>
<form action="{% url 'post:add_comment' %}" id="comment_form" method="POST">
{% csrf_token %}
<textarea name="comment" id="comment" cols="30" rows="1" placeholder="Write a comment..."></textarea>
<input type="hidden" name="slug" id="slug" value="{{post.slug}}">
<!-- <input type="submit" style="display: none;" name="submit"> -->
</form>
<script>
$(function(){
$("#comment").keypress(function (e) {
if(e.which == 13 && !e.shiftKey) {
$(this).closest("form").submit();
e.preventDefault();
}
});
});
</script>
{% endblock %}
the views.py -
from django.shortcuts import render,redirect
from instagram.views import get_nav_propic,get_profile_details
from .models import UserPost,PostComment,PostLike
from django.http import JsonResponse
def get_post_likes(post):
likes = PostLike.objects.filter(post=post)
total_likes = len(likes)
likers = []
for l in likes:
likers.append(get_profile_details(l.liker))
return {'likers':likers,'total_likes':total_likes}
def get_post_comments(post):
comments = PostComment.objects.filter(post=post)
total_comments = len(comments)
commenter = []
comment = []
for c in comments:
commenter.append(get_profile_details(c.commenter))
comment.append(c.comment)
postcomment = zip(commenter,comment)
return {'post_comment':postcomment,'total_comments':total_comments}
def upload_post(request):
if request.method == 'POST':
image = request.FILES['post_img']
caption = request.POST['caption']
uploader = request.user
UserPost.objects.create(uploader=uploader,image=image,caption=caption)
return redirect('instagram:feed')
else:
context = {
'propic' : get_nav_propic(request.user)
}
return render(request,'post/upload_post.html',context)
def post_details(request,slug):
print('I am here in post details')
post = UserPost.objects.get(slug=slug)
context = {
'propic' : get_nav_propic(request.user),
'post' : post,
'uploader' : get_profile_details(post.uploader),
'LIKES' : get_post_likes(post),
'COMMENTS' : get_post_comments(post),
}
return render(request,'post/post_details.html',context)
def add_comment(request):
print('I am here in add comment')
if request.method == 'POST':
post_slug = request.POST.get('slug')
post = UserPost.objects.get(slug=post_slug)
user = request.user
comment = request.POST.get('comment')
PostComment.objects.create(post=post,commenter=user,comment=comment)
return redirect('post:post_details',slug=post_slug)
the urls.py -
from django.urls import path
from . import views
app_name='post'
urlpatterns = [
path('upload_post/',views.upload_post,name='upload_post'),
path('<slug:slug>/',views.post_details,name='post_details'),
path('add_comment/',views.add_comment,name='add_comment'),
]
The error - Error page
Solved
I had to make the URL path of add_comment as following-
#previous one
path('add_comment/',views.add_comment,name='add_comment'),
#modified one
path('comment/add_comment/',views.add_comment,name='add_comment'),
This is because the pattern for the slug URL and add comment URL were similar.

Because Django will process the urlpatterns sequentially, from docs:
Django runs through each URL pattern, in order, and stops at the first
one that matches the requested URL, matching against path_info.
And '/add_comment' is a valid slug <slug:slug>, so post_details will be called.
So you should keep the definition of the most generic url patterns at last:
urlpatterns = [
path('upload_post/',views.upload_post,name='upload_post'),
path('add_comment/',views.add_comment,name='add_comment'),
path('<slug:slug>/',views.post_details,name='post_details'),
]
Hopefully this will work for you.

Related

Notification when a certain point in time is exceeded (Python)

I would like to create a To-Do list in which I can schedule date and time of each task. My goal is to get some sort of response whenever the supplied datetime is equal to the current time. For example I scheduled Do laundry for Monday at 6pm on a Saturday evening. Two days later (on Monday at 6pm) I would like to get a notification that I should Do laundry.
Notice that the key idea can be found in the index() function in views.py in the first rows including the if-statement.
Here is my code:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("<int:aufgabenzettel_id>", views.details, name="details"),
path("add/", views.add, name="add"),
path("delete/<int:aufgabenzettel_id>", views.delete, name="delete"),
path("edit/<int:aufgabenzettel_id>", views.edit, name="edit"),
path("update/<int:aufgabenzettel_id>", views.update, name="update")
]
models.py
from django.db import models
# Create your models here.
class Aufgabenzettel(models.Model):
Aufgabeselbst = models.CharField(max_length=64)
Datum = models.DateTimeField(auto_now_add=True)
Geplant = models.DateTimeField(auto_now_add=False, auto_now=False)
def __str__(self):
return f"{self.Aufgabeselbst}"
views.py (the important part can be found in the index function in the first rows including the if-statement)
from django.db.models.fields import DateTimeField
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from datetime import datetime
from .models import Aufgabenzettel
# Create your views here.
def index(request):
now = datetime.now()
Aufgaben_items = Aufgabenzettel.objects.all().order_by("-Geplant") #arrange objects in the correct order
for Aufgabenzettel.Geplant in Aufgaben_items: #run through the loop and...
if Aufgabenzettel.Geplant == now: #...search for items in the database where the scheduled time ("Geplant") is equal to the current time
return render (request, "aufgabenzettel/add.html") #response in any way e.g. by returning the add.html
return render(request, "aufgabenzettel/index.html", {
"Aufgabenliste":Aufgabenzettel.objects.all(), #currently not used
"Aufgaben_items":Aufgaben_items
})
def details(request, aufgabenzettel_id):
aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
creationDate = aufgabenzettel.Datum
dueDate = aufgabenzettel.Geplant
return render(request, "aufgabenzettel/details.html", {
"details":aufgabenzettel,
"creationDate": creationDate,
"dueDate":dueDate
})
def add(request):
addDatum = timezone.now()
if request.method == "POST":
Aufgabe = request.POST["Hinzufügen"]
geplantes_datum = request.POST["DatumFeld"]
Aufgabenzettel.objects.create(Aufgabeselbst=Aufgabe , Datum=addDatum, Geplant=geplantes_datum) #Aufgabenname und Aufgabendatum erstellen
return HttpResponseRedirect(reverse("index"))
return render(request, "aufgabenzettel/add.html")
def delete(request, aufgabenzettel_id):
aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
aufgabenzettel.delete()
return HttpResponseRedirect(reverse("index"))
def edit(request, aufgabenzettel_id):
aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
return render(request, "aufgabenzettel/edit.html", {
"details":aufgabenzettel
})
def update(request, aufgabenzettel_id):
if request.method == "POST":
Aufgabe = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
Aufgabe.Aufgabeselbst = request.POST["Bearbeiten"]
Aufgabe.save()
return HttpResponseRedirect(reverse("index"))
return render(request, "aufgabenzettel/edit.html")
index.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1 id="MeineAufgaben">Meine Aufgaben</h1>
<table>
{% for Aufgabeselbst in Aufgaben_items %}
<tr>
<td>
<a href="{% url 'details' Aufgabeselbst.id %}">
{{ Aufgabeselbst }}
</a>
</td>
<td>
<form action="{% url 'delete' Aufgabeselbst.id %}" method="post">
{% csrf_token %}
<button type="submit" id="löschenbtn">Löschen</button>
</form>
</td>
<td>
<form action="{% url 'edit' Aufgabeselbst.id %}" method="post">
{% csrf_token %}
<button type="submit" value="{{ details }}" class="bearbeitenbtn">Bearbeiten</button>
</form>
</td>
</tr>
{% endfor %}
</table>
<h2>
Neue Aufgabe erstellen
</h2>
{% endblock %}
add.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1>Füge eine neue Aufgabe hinzu!</h1>
<form action="{% url 'add' %}" method="post">
{% csrf_token %}
<input type="text" name="Hinzufügen" placeholder="Neue Aufgabe">
<input type="datetime-local" name="DatumFeld">
<button type="submit" id="Hinzufügen">Hinzufügen</button>
</form>
{% endblock %}
details.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1>{{ details }}</h1>
<h3>Erstellt: {{ creationDate }}</h3>
<h2>Geplant: {{ dueDate }}</h2>
Zurück zu Aufgabe
{% endblock %}
edit.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h2>Bearbeite deine Aufgabe "{{ details }}"</h2>
<form action="{% url 'update' details.id %}" method="post">
{% csrf_token %}
<input type="text" name="Bearbeiten" value="{{details}}">
<button type="submit" class="bearbeitenbtn">Bearbeiten</button>
</form>
Zurück zu Aufgabe
{% endblock %}
layout.html
{% load static %}
<!DOCTYPE html>
<html lang="de">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Aufgabenzettel</title>
<link rel="stylesheet" href="{% static '/css/main.css' %}">
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
I don't get an Error or anything but the code is not running as expected. I just want the index function to loop through each element in the database Aufgabenzettel in models.py and if it detects an element where the scheduled time corresponds with the current time some sort of action (in this case a redirect to add.html is ecpected) should happen. However I don't get any such response...
Like always, I appreciate every kind of solution or help!
You're comparing datetimes the wrong way and that is why your if condition is failing (Aufgabenzettel.Geplant == now) .
Try comparing them like this:
In [1]: from datetime import datetime
In [2]: past = datetime.now()
In [3]: present = datetime.now()
In [4]: present.strftime('%Y-%m-%d %H:%M:%S') == past.strftime('%Y-%m-%d
%H:%M:%S')
Out[17]: False
In [5]: present.strftime('%Y-%m-%d %H:%M') == past.strftime('%Y-%m-%d %H:%M')
Out[2]: True
Usually datetimes are compared after converting them to iso format. You can also use the function .isoformat() from timezone.
Picked it up from here: How to compare two Datetime field in Django

Django - Stripe. You did not set a valid publishable key. Error that comes up when trying to incorprate stripe payments on a django website

I'm working on a django bookstore website and there seems to be an error with stripe integration. I have an orders page that asks for payment information (I'm using the test API for now). I get the same error "You did not set a valid publishable key. Call Stripe.setPublishableKey() with your publishable key."
orders/views.py
from django.conf import settings
from django.views.generic.base import TemplateView
class OrdersPageView(TemplateView):
template_name = 'orders/purchase.html'
def get_context_data(self, **kwargs):
##Stripe.setPublishableKey('PUBLISHABLE_KEY')
context = super().get_context_data(**kwargs)
context['stripe_key'] = settings.STRIPE_TEST_PUBLISHABLE_KEY
return context
templates/orders/purchase.html
{% extends '_base.html' %}
{% block title %}Orders{% endblock title %}
{% block content %}
<h1>Orders page</h1>
<p>Buy for $39.00</p>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_key }}"
data-description="All Books"
data-amount="3900"
data-locale="auto">
</script>
{% endblock content %}
In your forms you need a {% csrf_token %} and form action that takes you to the charge page.
<form action="{% url 'charge' %}" method="post">
{% csrf_token %}
<h1>Orders page</h1>
<p>Buy for $39.00</p>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_key }}"
data-description="All Books"
data-amount="3900"
data-locale="auto">
</script>
</form>
Also unless never set your pricing in your templates, this is asking for trouble. Set them in your view.

URL Displaying Wrong Form and View in Django

I am attempting to render a form where the only field is a dropdown. I have the form, view, .html, url all set up. But when I access this url, it shows a different form and view and I suppose also a different .html. I am so confused on why this is happening as it had been working fine for quite some time so I obviously changed something.
forms.py
#this is the form for the dropdown
class ManifestDropDown(forms.Form):
References = forms.ModelChoiceField(queryset=Orders.objects.values_list('reference', flat=True).distinct(),
empty_label=None)
manifest_references.html
<!--html for dropdown-->
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST" action="manifest">
{% csrf_token %}
{{ reference_list }}
<button type="submit" class="btn btn-primary" name="button">Submit</button>
</form>
</div>
{% endblock %}
views.py
#view for dropdown
def manifest_references(request):
if request.method == 'POST':
if form.is_valid():
reference_id = form.cleaned_data.get('References')
form.save()
query_results = Orders.objects.all()
reference_list = ManifestDropDown()
context = {
'query_results': query_results,
'reference_list': reference_list,
}
return render(request, 'manifest_references.html', context)
urls.py
url(r'^manifest_references', manifest_references, name='manifest_references'),
base.html
<!--showing the link to this url-->
...
<a class="dropdown-item" href="{% url 'manifest_references' %}">Edit Manifests</a>
When I access the url above - instead of showing the manifest_references view with the dropdown, it immediately jumps to a different view manifest which is referenced as the action in the manifest_references.html. Please someone help me determine why this is happening.

how can i access a context of function view with a separate page in base page?

i created newsletters app with below code after that i have a URL : subscribe that perfectly work and save my email after that i want to add this ability in base page for example a user don't go to subscribe page and subscribed i want directly have access in base template and subscribe .
i want to know this because i want add login form to base page and have this problem with that .
this my code and this is my template
tnx for help.
views.py
from django.shortcuts import render
def Subscribe(request):
form = SiqnupNewslettersForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
if SignupNewsletters.objects.filter(email=instance.email).exists():
print("this email already taken ")
else :
instance.save()
context = {
'form':form
}
template_name = "subscribe.html"
return render(request,template_name,context)
def Unsubcribe(request):
form = SiqnupNewslettersForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
if SignupNewsletters.objects.filter(email= instance.email).exists():
SiqnupNewslettersForm.objects.filter(email = instance).delete()
else:
print("your email is not here")
context = {
'form' : form
}
template_name = "unsubscribe.html"
return render(request,template_name,context)
subscribe.html
{% block content %}
<div class="container">
<div class="row">
<form method="POST" action="">
{% csrf_token %}
<div class="form-group">
{{ form }}
</div>
<input type='submit' class="btn btn-primary"
value="submit">
</form>
</div>
</div>
{% endblock %}
urls.py
urlpatterns = [
path('subscribe/',views.Subscribe,name="subscribe"),
path('unsubscribe/',views.Unsubcribe,name= "unsubscribe"),
]
and finally what i have to do for add newsletter form in base page ?
base.html

Tango with Django - Chapter 8 - Exercise

I need some help getting the add_page function to work properly. I am very new to HTML and even newer to Django. The chapter I am working on can be found here: http://www.tangowithdjango.com/book17/chapters/forms.html. Currently my relevent files look like this:
Forms.py
from django import forms
from rango.models import Page, Category
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter the category name.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
# An inline class to provide additional information on the form.
class Meta:
# Provide an association between the ModelForm and a model
model = Category
fields = ('name',)
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
# Provide an association between the ModelForm and a model
model = Page
# What fields do we want to include in our form?
# This way we don't need every field in the model present.
# Some fields may allow NULL values, so we may not want to include them...
# Here, we are hiding the foreign key.
# we can either exclude the category field from the form,
exclude = ('category',)
#or specify the fields to include (i.e. not include the category field)
#fields = ('title', 'url', 'views')
def clean(self):
cleaned_data = self.cleaned_data
url = cleaned_data.get('url')
# If url is not empty and doesn't start with 'http://', prepend 'http://'.
if url and not url.startswith('http://'):
url = 'http://' + url
cleaned_data['url'] = url
return cleaned_data
Views.py:
from django.shortcuts import render
from django.http import HttpResponse
from rango.models import Category, Page
from rango.forms import CategoryForm, PageForm
def index(request):
# Query the database for a list of ALL categories currently stored.
# Order the categories by no. likes in descending order.
# Retrieve the top 5 only - or all if less than 5.
# Place the list in our context_dict dictionary which will be passed to the template engine.
category_list = Category.objects.order_by('-likes')[:5]
page_list = Page.objects.order_by('-view')[:5]
context_dict = {'categories': category_list,
'pages': page_list}
# Render the response and send it back!
return render(request, 'rango/index.html', context_dict)
def category(request, category_name_slug):
# Create a context dictionary which we can pass to the template rendering engine.
context_dict = {}
try:
# Can we find a category name slug with the given name?
# If we can't, the .get() method raises a DoesNotExist exception.
# So the .get() method returns one model instance or raises an exception.
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
context_dict['category_name_slug'] = category_name_slug
# Retrieve all of the associated pages.
# Note that filter returns >= 1 model instance.
pages = Page.objects.filter(category=category)
# Adds our results list to the template context under name pages.
context_dict['pages'] = pages
# We also add the category object from the database to the context dictionary.
# We'll use this in the template to verify that the category exists.
context_dict['category'] = category
except Category.DoesNotExist:
# We get here if we didn't find the specified category.
# Don't do anything - the template displays the "no category" message for us.
pass
# Go render the response and return it to the client.
print context_dict
return render(request, 'rango/category.html', context_dict)
def add_category(request):
# A HTTP POST?
if request.method == 'POST':
form = CategoryForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
form.save(commit=True)
# Now call the index() view.
# The user will be shown the homepage.
return index(request)
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = CategoryForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request, 'rango/add_category.html', {'form': form})
def add_page(request, category_name_slug):
try:
cat = Category.objects.get(slug=category_name_slug)
except Category.DoesNotExist:
cat = None
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
if cat:
page = form.save(commit=False)
page.category = cat
page.views = 0
page.save()
# probably better to use a redirect here.
return category(request, category_name_slug)
else:
print form.errors
else:
form = PageForm()
context_dict = {'form':form, 'category': cat}
return render(request, 'rango/add_page.html', context_dict)
urls.py
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
# url(r'^about/$', views.about, name='about'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/add_page/$', views.add_page, name='add_page'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),)
I think this ^ is where I am encountering the issue. I manage to get to the "add a page" screen, but when I try to submit something, I receive an error that states I am only supplying 1 argument and add_page() requires 2. I think I may need an additional url that is similar to the "add_category" URL, but that must mean by other URL is pointing to the wrong place?
category.html
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<body>
<h1>{{ category_name }}</h1>
{% if category %}
{% if pages %}
<ul>
{% for page in pages %}
<li>{{ page.title }}</li>
{% endfor %}
</ul>
{% else %}
<strong>No pages currently in category.</strong>
{% endif %}
<li>Add a New Page</li>
{% else %}
The specified category {{ category_name }} does not exist!
{% endif %}
</body>
</html>
add_page.html:
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<body>
<h1>Add a Page</h1>
<form id="page_form" method="post" action="/rango/add_page/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Page" />
</form>
</body>
</html>
I edited the add_page function to include category_name_slug:
def add_page(request, category_name_slug):
try:
cat = Category.objects.get(slug=category_name_slug)
except Category.DoesNotExist:
cat = None
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
if cat:
page = form.save(commit=False)
page.category = cat
page.views = 0
page.save()
# probably better to use a redirect here.
return category(request, category_name_slug)
else:
print form.errors
else:
form = PageForm()
# made the change here
context_dict = {'form':form, 'category': cat, 'category_name_slug': category_name_slug}
return render(request, 'rango/add_page.html', context_dict)
Then I edited the add_page.html to look like this:
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<body>
<h1>Add a Page</h1>
<form id="page_form" method="post" action="/rango/category/{{ category_name_slug }}/add_page/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Page" />
</form>
</body>
</html>
if you dont wanna edit your views.py
just doit
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<body>
<h1>Add a Page</h1>
<form id="page_form" method="post" action="/rango/category/{{ category }}/add_page/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Page" />
</form>
</body>
</html>
but i have problem to it still cannot be save on database.

Categories

Resources