[Django]-Django set multiply function for single url

4πŸ‘

My guess is you are using The built in now filter to print the current time and date and are mistaking it for the context variable.

You cannot have two views respond to a single request, that’s not how django works. You have to make a single view that pulls all the data the template needs and renders it to a response. You can still have separate functions to derive the context and then just collect them in the view.

πŸ‘€krs

1πŸ‘

Maybe you would do something with the date time, you can store the time in datebase in you cellphone function.

views.py

import datetime
from urllib.request import urlopen

import pymysql
from bs4 import BeautifulSoup

from django.shortcuts import render
from django.http import HttpResponseRedirect


def cellphone(request):
    url ='http://www.digikala.com/Product/DKP-95906/Huawei-Mate-S-Dual-SIM-64GB-Mobile-Phone/'
    data = urlopen(url)
    soup = BeautifulSoup(data, 'html.parser')
    price =  soup.body.find('span', attrs={'id':'frmLblPayablePriceAmount'}).text
    now = datetime.datetime.now()

    return render(request, 'system.html', {'price': price, 'now': now})

urls.py

from django.conf.urls import include, url
from system.views import cellphone

urlpatterns = [
    url(r'^system/$', cellphone),  # Django would only call the first match.
                                   # And the '$' at the end of regex is important.
]
πŸ‘€Ziya Tang

1πŸ‘

You can use ajax to load small parts of your webpage while using only one webpage.

You can use one URL per subset but you will need to use javascript/jQuery something like:

$(document).ready(function(){
    $("#datetime_content").load("/system/datetime");
});

with this in your datetime function (same template as in your question)

return render(request, 'datetime.html', {'now': now})

and this in the url.py

urlpatterns = [
    url(r'^system/', cellphone),
    url(r'^system/datetime', datetime),
]

you can of course do the same with the cellphone function/view

but I would still recommend class based views:
https://docs.djangoproject.com/en/1.8/topics/class-based-views/

more on ajax: https://stackoverflow.com/tags/ajax/info

πŸ‘€maazza

Leave a comment