On the main page I have a text box. When I type text into it, after clicking the button I want to display that text below.
With ajax I get the text entered and pass it to views.py.
When rendering, the result I need is displayed on /localhost:8000/vk_u/
How do I display the result on the current page (localhost: 8000/)?
Thanks
//forms.py
from django import forms
from .models import *
class VK_LINK_Form(forms.Form):
enter_link = forms.CharField(widget = forms.TextInput(attrs={'id':'link_vk_enter'}))
//urls.py
from django.urls import path, include
from . import views
from django.http import HttpResponse
urlpatterns = [
path('', views.index, name = 'index'),
path('vk_u/', views.vk_u, name = 'vk_u'),
]
//js
$(document).on('submit','#vkht_form', function(e){
e.preventDefault();
var link_post_input = $(document.getElementById("link_vk_enter")).val()
$.ajax({
type: 'POST',
url: '/vk_u/',
data:{
link_post_input: link_post_input,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
});
});
]
//views.py
def vk_u(request):
link_post_input = request.POST.get('link_post_input')
return render(request, "mainApp/homePage.html", {"link_post_input": link_post_input,})
<!-- html -->
<body>
<div>
<form action="" method="GET" id="vkht_form">
{% csrf_token %}
{{ form }}
text: {{ text_post_input }}
<input type="submit" value="CLICK">
</form>
</div>
</body>
Related
so im doing cs50x web development and the assignment is creating a wikipedia page. I created a views function where I can click on edit page to edit the content. However I keep running into this problem.enter image description here
This is my code from views.py
class EditForm(forms.Form):
body = forms.CharField(label= "Body")
def edit_page(request):
title = request.POST.get("edit")
body = util.get_entry(title)
form = EditForm(initial={'body': body})
if request.method == "POST":
form = EditForm(request.POST)
if form.is_valid():
content = form.cleaned_data["body"]
util.save_entry(title, content)
return render(request, "encyclopedia/title.html", {
"title": title, "content": util.get_entry(title)
})
else:
return render(request, "encyclopedia/edit.html", {
"form": EditForm()
})
urls.py:
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:title>", views.title, name="title"),
path("search", views.search, name="search"),
path("new_page", views.new_page, name="new_page"),
path("random", views.randomizer, name="random"),
path("edit", views.edit_page, name="edit")
]
title.html:
<form action= "{% url 'edit' %}", method= "POST">
{% csrf_token %}
<button type="submit" name="edit" value="{{title}}" id="edit">Edit Page</button>
</form>
and finally edit.html
<form action="{% url 'edit' %}" method="POST">
{% csrf_token %}
{{form}}
<input type="submit">
</form>
Someone please help me to solve this issue thanks!
form = EditForm(request.POST or None ,initial={'body': body})
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.
I have a Django Project I am currently working on where I want to be able to add a product to a database. I have a few fields where the user enters the details of the product and this is then sent to the create function and should save it to the Database. Unfortunately this isnt happening. This is my first use of Django so I'm not sure whats going wrong here. Here is the code I have so far:
My Index.html page:
<!DOCTYPE html>
<html>
<body>
<h2>Create product here</h2>
<div>
<form id="new_user_form" method="post">
{% csrf_token %}
<div>
<label for="name" > Name:<br></label>
<input type="text" id="name"/>
</div>
<br/>
<div>
<label for="description"> description:<br></label>
<input type="text" id="description"/>
</div>
<div>
<label for="price" > price:<br></label>
<input type="text" id="price"/>
</div>
<div>
<input type="submit" value="submit"/>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type = "text/text/javascript">
$(document).on('submit', '#new_user_form', function(e)){
e.preventDefault()
$.ajax({
type: 'POST',
url:'/user/create',
data:{
name:$('#name').val(),
description:$('#description').val(),
price:$('#price').val(),
}
success.function(){
console.log('created')
}
})
}
</script>
</html>
Here is my urls.py code:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from testapp import views
admin.autodiscover()
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
path('user/create', views.create_product, name='create_user')
]
My views.py code:
from django.shortcuts import render
from testapp.models import User
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
def index(request):
return render(request, 'index.html')
#csrf_exempt
def create_product(request):
if request.method == 'POST':
name = request.POST['name']
description = request.POST['description']
price = request.POST['price']
User.objects.create(
name = name,
description = description,
price = price
)
return HttpResponse('')
And the models.py code:
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length = 32)
desscription = models.TextField()
price = models.CharField(max_length = 128)
The problem with this is the POST request is sent when run, but the data is not saved to the database and I can't figure out why. I have followed a couple tutorials and documentation to get to this stage but can't work out what it is that's not working correctly here. Can someone have a look and let me know please?
Hello i can't make my form work. The button is displayed but the charfield never shows up. I tried to use a if statement with the "sent" parameter and it worked. I just followed the django doc. I did not find a solution in other posts.
Here is my forms.py:
from django import forms
class CharacterForm(forms.Form):
character_name = forms.CharField(label='Search', max_length=30)
views.py:
from django.shortcuts import render
from .forms import CharacterForm
def index(request):
return render(request, 'perso/pages/index.html')
def get_character(request):
character_name = ''
sent = False
if request.method == 'POST':
form = CharacterForm(request.POST)
if form.is_valid():
character_name = form.cleaned_data['character_name']
sent = True
else:
form = CharacterForm()
return render(request, 'perso/pages/index.html', {
'form': form,
'character_name': character_name,
'sent': sent
})
Perso is the name of the app, Urls.py in perso:
from django.conf.urls import url
from . import views
app_name = 'perso'
urlpatterns = [
url(r'^$', views.index, name="index"),
]
My form in template index of perso:
<form action="{% url "perso:index" %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Here is what appears in the browser:
<form action="/perso/" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='IWmBEknyibHw4LpvjnyfLWKcUOXLbw27RdHgR7GjhTDelCLGZ51QeF3y9wRyC0Mg' />
<input type="submit" value="Submit" />
</form>
The charfield is missing. No error in the console.
You have some anomaly in your code you missed out the template name argument in your render function. Provide the template name of your corresponding HTML file in the render function. You also missed providing default arguments of character_name and sent variable. See docs here
from django.shortcuts import render
from .forms import CharacterForm
def get_character(request):
character_name = ''
sent = False
if request.method == 'POST':
form = CharacterForm(request.POST)
if form.is_valid():
character_name = form.cleaned_data['character_name']
sent = True
else:
form = CharacterForm()
return render(request, 'template_name.html', {
'form': form,
'character_name': character_name,
'sent': sent
})
You have made mistake to not make urls.py pattern for the function in views.py that is setting the form in the template
from django.conf.urls import url
from . import views
app_name = 'perso'
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^character$', views.get_character, name="character"),
]
Also you need correction in your template in your post request URL link
<form action="{% url "perso:character" %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Now your form will be avaliable at http://localhost:8000/character
I've been trying to send extra parameters when submiting the stripe button, which is integrated in my Django application, but I cannot make it work.
So far, I have this:
views.py
stripe.api_key = "XXXX"
class StripeApi(View):
#staticmethod
def post(request):
a = request.body
event_json = json.dumps(a)
print a
return HttpResponse(
event_json, content_type="application/x-javascript-config")
urls.py
urlpatterns = [
url(r'^stripe/', ApiViews.StripeApi.as_view()),
]
index.html
<form action="" method="POST">
<input type="text" name="extraParam2" value="55555fghjkldfgdgfasdfghhjjj"> <!-- here, I tried to add extraParam2 -->
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="XXXX"
data-amount="2000"
data-name="Demo Site"
data-description="2 widgets ($20.00)"
data-image="/128x128.png"
data-locale="auto">
</script>
</form>
Any hints on this, please ?
//EDIT:
I tried to integrate what Ywain gave me into my app and I get "POST /stripe/ HTTP/1.1" 405 0 in console after completing and sending the form. What do I do wrong ?
views.py
class StripeApi(View):
#staticmethod
def index(request):
return HttpResponse(request, 'index.html', {
'stripe_pub_key': settings.STRIPE_PUBLISHABLE_KEY},
content_type="application/x-javascript-config")
#staticmethod
def charge(request):
charge = stripe.Charge.create(
amount=2000,
currency='usd',
source=request.POST['stripeToken'],
description='Charge for {}'.format(request.POST['stripeEmail'])
)
return HttpResponse(request, 'stripe.html', {'charge_id': charge.id,
'extra_param': request.POST['extraParam2']},
content_type="application/x-javascript-config")
settings.py:
'''stripe'''
STRIPE_SECRET_KEY = 'sk_test_secret',
STRIPE_PUBLISHABLE_KEY = 'pk_test_secret'
stripe.api_key = STRIPE_SECRET_KEY
urls.py
...
url(r'^stripe/', ApiViews.StripeApi.as_view()),
index.html
<form action="/stripe/" method="POST">
<input type="text" name="extraParam2" value="Test extraParam">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_secret"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-name="Stripe.com"
data-description="2 widgets"
data-amount="2000"
data-locale="auto">
</script>
</form>
stripe.html
{% extends "base_site.html" %}
{% block content %}
<pre>
Charge ID: {{ charge_id }}
Extra param: {{ extra_param }}
</pre>
{% endblock %}
Here is a minimal Django app that illustrates how to use Stripe Checkout and use the resulting token to create a charge, as well as pass an extra parameter along:
django-stripe.py
import sys
from django.conf import settings
from django.conf.urls import url
from django.core.management import execute_from_command_line
from django.shortcuts import render
from django.views.generic import View
import stripe
settings.configure(
DEBUG=True,
ROOT_URLCONF=sys.modules[__name__],
TEMPLATE_DIRS=['.'],
STRIPE_SECRET_KEY='sk_test_...',
STRIPE_PUBLISHABLE_KEY='pk_test_...'
)
stripe.api_key = settings.STRIPE_SECRET_KEY
class StripeView(View):
#staticmethod
def get(request):
return render(request, 'index.html',
{
'stripe_pub_key': settings.STRIPE_PUBLISHABLE_KEY
})
#staticmethod
def post(request):
charge = stripe.Charge.create(
amount=2000,
currency="usd",
source=request.POST['stripeToken'],
description="Charge for {}".format(request.POST['stripeEmail'])
)
return render(request, 'charge.html',
{
'charge_id': charge.id,
'extra_param': request.POST['extraParam2']
})
urlpatterns = [
url(r'^stripe/', StripeView.as_view()),
]
if __name__ == "__main__":
execute_from_command_line(sys.argv)
index.html
<form action="" method="POST">
{% csrf_token %}
<input type="text" name="extraParam2" value="55555fghjkldfgdgfasdfghhjjj">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_pub_key }}"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-name="Stripe.com"
data-description="2 widgets"
data-amount="2000"
data-locale="auto">
</script>
</form>
charge.html
<pre>
Charge ID: {{ charge_id }}
Extra param: {{ extra_param }}
</pre>
You can test it by pasting your Stripe API keys (in the STRIPE_SECRET_KEY and STRIPE_PUBLISHABLE_KEY arguments of the settings.configure() function call), starting the app with python django-stripe.py runserver, and pointing your web browser to http://localhost:8000/stripe.
Basically, index.html contains the Checkout form as well as your extra parameter. The form is submitted to the same page (the action attribute of the <form> tag is empty), and is handled by the post() method of the StripeView class. The method creates an actual charge with Stripe's API, and passes the resulting charge ID along with your extra parameter to the charge.html template.
The stripe page mentions a 'custom' option for using a stripe button, this is probably what you want, you can add extra values to your button:
https://stripe.com/docs/checkout#integration-custom
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Purchase</button>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
image: '/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
}
});
$('#customButton').on('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'Stripe.com',
description: '2 widgets',
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation
$(window).on('popstate', function() {
handler.close();
});
</script>