How to create callback URL in Django PuSH - python

I am using Django-PuSH (PubSubHubPub) for my Blogger's Blog.
Now, I read the documentation and could make simple code. However, the document never mentioned anywhere to enter a callback URL!
Here is the simple code.
# hubserver.py
#receiver(updated)
def listener(notification, **kwargs):
e = []
for entry in notification.entries:
e.append(entry.title)
for link in e:
db = entries( url = link )
db.save(force_insert=True)
from django.shortcuts import render_to_response
from django_push.subscriber.models import Subscription
from models import mydata
# views
def bloghub (request):
subscription = Subscription.objects.subscribe("http://myblog.blogspot.in//feeds/posts/default",
"http://pubsubhubbub.appspot.com")
db = mydata.objects.all()
lis = [i.url for i in db]
context = {"lis" : lis}
return render_to_response("home.html", context)
[1]: http://django-push.readthedocs.org
# urls.py
urlpatterns = patterns('',
url(r'^$', views.bloghub ),
url(r'^subscriber/', include('django_push.subscriber.urls')),
)

Related

is it possible to attach a string variable in return redirect() in django

I have a situation here where I am creating a record from a view
def index(request):
if request.method == "POST":
order_number = request.POST.get('order_number')
post_code = request.POST.get('post_code')
print(order_number)
print(post_code)
if order_number and post_code:
n = page1.objects.create(orderNumber=order_number, postCode=post_code)
n.save()
id = n.id
return redirect("page1:waiting")
return render(request,"page1/index.html")
And upon creating the record I am redirecting the user to another page with id.
127.0.0.1/page1/waiting/fb65-io98-.....
from django.urls import path
from . import views
app_name = 'page1'
urlpatterns = [
path('', views.index, name="amounts"),
path('waiting/<str:pk>', views.waitReply, name="waiting"),
]
View for Second URL
def waitReply(request,pk):
get_amount = page1.objects.get(id=pk)
context = {'get_amount':get_amount}
return render(request, "page1/payment-confirm.html", context)
But the problem is how do I attach/generate/get the id in index view and send it for the waitReply view
I can get the latest ID through n.id
Kindly help.
Use reverse with args in HttpResponseRender.
return HttpResponseRender(reverse('page1:waiting' args=[id]))

trying to get my views.py and urls.py to work properly

I am currently trying to get my database that I created to display on my Djnago server however I keep getting errors for my FruitModel saying that there are no objects however I have created objects for the FruitModel in my datbase using "record = FruitModel.objects.create(name='banana', price='4.00').
I am also getting an unable to display error for my urls when I loaded up my server.
Here is my code for
Views.py and for urls.py:
(views.py code)
from django.shortcuts import render, redirect
from catalog.models import FruitModel
from catalog.forms import FruitForm
from django.http import HttpResponse
# Create your views here.
def FruitView(request):
fruit = FruitModel.objects.all()
html = ''
for fruits in fruit:
var = f'<li> {fruits.name} </li><br>'
html = html + var
return HttpResponse(html,status = 200)
def FruitIDView(request,name):
fruits = FruitModel.objects.get(name = f'{fruits.name}')
html = f'<h2>{fruits.name}</h2><br>'
return HttpResponse(html, status=200)
(urls.py code)
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from catalog import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^FruitView/?$', views.FruitView),
]
You need this changes:
#urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^FruitView/?$', views.FruitView),
path('FruitIDView/<str:naam>', views.FruitIDView), #use path instead of url
]
#models.py (if not created)
class FruitModel(models.Model):
name = models.CharField(max_length=200,null=True,blank=True)
price = models.IntegerField()
#views.py
def FruitView(request):
fruit = FruitModel.objects.all()
html = ''
for fruits in fruit:
var = f'<li> {fruits.name} </li><br>'
html = html + var
return HttpResponse(html,status = 200)
def FruitIDView(request,naam):
fruits = FruitModel.objects.get(name = naam) #how can you use fruits.name here
html = f'<h2>{fruits.name}</h2><br>'
return HttpResponse(html, status=200)
#admin.py (if not created)
from .models import *
# Register your models here.
admin.site.register(FruitModel)

django rest framework detail_route not working in get method

I defined a viewset using ModelViewSet as follow
I tried to redefine the GET method to do something like getting something from celery . but this part of code just won't work , it acts just like a standard API and didn't do what I wrote in the get_job_detail function.
How should I correctly define the "detail_route" function.
views.py
class JobViewSet(viewsets.ModelViewSet):
queryset = job.objects.all()
serializer_class = JobSerializer
#detail_route(methods=['get'])
def get_job_detail(self, request, pk=None):
# print('these part wont proceed')
job_item = self.get_object()
if job_item.isReady or job_item.isSuccessful:
return Response(self.serializer_class(job_item).data)
celeryjob = sometask.AsyncResult(pk)
celeryjob.get()
if celeryjob.state == 'SUCCESS':
job_item.state = celeryjob.state
job_item.result = celeryjob.result
job_item.isReady = True
job_item.isSuccessful = True
job_item.save()
if celeryjob.state == 'FAILURE':
job_item.state = celeryjob.state
job_item.result = celeryjob.result
job_item.isReady = True
job_item.isSuccessful = False
job_item.save()
return Response(self.serializer_class(job_item).data)
urls.py
from django.conf.urls import url, include
from apply_api import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'job',views.JobViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
now your correct url is: /job/<pk>/get_job_detail if you want just: /job/<pk> you don need to use #detail_route just rename your method to the def retrieve(self, request, *args, **kwargs): more details retrievemodelmixin one of the part class of the modelviewset

Proper way to retrieve middleware values

I'm trying to retrieve some loading times per view and displaying it in the page. To do so I'm using a middleware and a context_processor setup but I can't find the way to retrieve this values to the context of the view.
Here is the example:
I've added the middleware and context_processor to the settings.
middlewares.py (from this answer):
from __future__ import unicode_literals, absolute_import
from django.db import connection
from time import time
from operator import add
import re
from functools import reduce
class StatsMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
# get number of db queries before we do anything
n = len(connection.queries)
# time the view
start = time()
response = view_func(request, *view_args, **view_kwargs)
total_time = time() - start
# compute the db time for the queries just run
db_queries = len(connection.queries) - n
if db_queries:
db_time = reduce(add, [float(q['time']) for q in connection.queries[n:]])
else:
db_time = 0.0
# and backout python time
python_time = total_time - db_time
stats = {
'total_time': total_time,
'python_time': python_time,
'db_time': db_time,
'db_queries': db_queries,
}
# this works fine
print(stats)
# replace the comment if found
if response:
try:
# detects TemplateResponse which are not yet rendered
if response.is_rendered:
rendered_content = response.content
else:
rendered_content = response.rendered_content
except AttributeError: # django < 1.5
rendered_content = response.content
if rendered_content:
s = rendered_content
# The following code is commented
# because it can't compile bytes and
# as long as I understand the values comes
# from the rendered template which are the ones I'm interested in getting
# regexp = re.compile(
# r'(?P<cmt><!--\s*STATS:(?P<fmt>.*?)ENDSTATS\s*-->)'
# )
# match = regexp.search(s)
# if match:
# s = (s[:match.start('cmt')] +
# match.group('fmt') % stats +
# s[match.end('cmt'):])
# response.content = s
return response
context_processors.py
#from django.template import RequestContext
def foo(request):
context_data = dict()
context_data["stats"] = "stats"
return context_data
views.py:
from django.shortcuts import render
from accounts.models import User
def myFunc(request):
users = User.objects.all()
return render(request, 'index.html, {'users_list': users})
index.html:
{{stats}}
<br>
{% for user in users_list %}
{{user}} <br>
{% endfor %}
What is the proper way to retrieve these values? The idea is to compare those values later against the cache framework.

View function not getting called in Django

Here's the view.py. show_checkout is called and runs all the way to return HttpResponseRedirect('/receipt/'), but for some reason, receipt view isn't being fired. none of the print statements are working:
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from ecomstore.checkout.forms import CheckoutForm
from ecomstore.checkout.models import Order, OrderItem
from ecomstore.checkout import checkout
from ecomstore.cart import cart
from django.core.context_processors import csrf
# Create your views here.
def show_checkout(request, template_name='checkout/checkout.html'):
c = {}
c.update(csrf(request))
if cart.is_empty(request):
cart_url = urlresolvers.reverse('show_cart')
return HttpResponseRedirect(cart_url)
if request.method == 'POST':
postdata = request.POST.copy()
form = CheckoutForm(postdata)
if form.is_valid():
response = checkout.process(request)
order_number = response.get('order_number',0)
print 'this is the order number: ' + str(order_number)
error_message = response.get('message','')
if order_number:
request.session['order_number'] = order_number
# receipt_url = urlresolvers.reverse('checkout_receipt')
print request.session['order_number']
return HttpResponseRedirect('/receipt/')
else:
error_message = 'Correct the errors below'
else:
form = CheckoutForm()
page_title = 'Checkout'
return render_to_response(template_name, locals(), context_instance= RequestContext(request))
##Currently this doesn't seem to be running
def receipt(request, template_name='checkout/receipt.html'):
order_number = request.session.get('order_number','')
print 'this is receipt order number: ' + str(order_number)
if order_number:
print 'in order_number'
order = Order.objects.filter(id=order_number)[0]
order_items = OrderItem.objects.filter(order=order)
del request.session['order_number']
else:
print 'not in order number'
cart_url = urlresolvers.reverse('show_cart')
return HttpResponseRedirect(cart_url)
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Here is the checkout.urls:
from django.conf.urls.defaults import *
from ecomstore import settings
urlpatterns = patterns('ecomstore.checkout.views',
(r'^$','show_checkout',{'template_name':'checkout/checkout.html','SSL':settings.ENABLE_SSL},'checkout'),
(r'^receipt/$','receipt',{'template_name':'checkout/receipt.html','SSL':settings.ENABLE_SSL},'checkout_receipt'),
)
and the urls.py:
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'ecomstore.views.home', name='home'),
# url(r'^ecomstore/', include('ecomstore.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
(r'^', include('catalog.urls')),
(r'^cart/$', include('cart.urls')),
(r'^checkout/$', include('checkout.urls')),
(r'^receipt/$', include('checkout.urls')),
)
IMPORTANT: Also it's currently being forwarded to localhost/cart
In your main urls.py, don't use "$" in the regex. That seems to have fixed it for me.
My guess would be that you mean /receipt/receipt

Categories

Resources