Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the check box data from front end in python?
i am using request.POST.getlist to read the data district = request.POST.getlist('district[]') but when i try to print it then it is printing empty list my json data is { "district":"krishna" } -
Django queries and joins
I read in the Django documentation that in principle Django queries are lazy, that is the database is not queried until absolutely necessary. Now, as a matter of efficiency, when I retreive data via FooModel.object.filter(...) and I have defined a relationship between FooModel and BarModel, is the info from BarModel automatically retreived as well? Or does this only happen when I later reference any of the BarModel fields? On a related note. I have been looking for a simple way to somehow just confirm this for myself by looking at logs or using a debugger but have not been able to. I'd be interested in tips on how to do this. -
importing .py file error
I am trying to import .py file and it gives the error. import thinkplot.py And the error : Traceback (most recent call last): File "", line 1, in import thinkplot ImportError: No module named thinkplotTraceback (most recent call last): File "", line 1, in import thinkplot ImportError: No module named thinkplot But when I open thinkplot.py file and then writing the code import thinkplot.py, it works well. But without opening the file, it dosn't work. There ara similar questions in the forum but none of them work for me. I am new to Python. How can I fix the problem ? Also, I am using python 2.7 in a unbuntu linux. Thank you... -
Deploy Django on Herloku
My python version is 3.5.2 Django version is 1.8.13 I made a django app and wanna dploy to heroku. when I type heroku open Then local server display application error. After googling. I fixed my wsgi.py but still error. .ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. "'DJANGO_SETTINGS_MODULE' environment variable must be set "django.core.exceptions.ImproperlyConfigured: 'DJANGO_SETTINGS_MODULE' environment variable must be set before importing 'whitenoise.django' File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 506, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> wsgi.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "weather_station.settings") from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(get_wsgi_application()) setting.py local_setting.py Is there any key concept i missed? -
Django: How can I pass AsyncResult from signal(pre_save..etc)?
I use Django 1.9 and celery 4.0. I run asynchronous task inside pre_save() signal like this: @receiver(pre_save, sender=Product, dispatch_uid="spacegraphy") def pre_save_product(sender, instance, **kwargs): recommend_precompute_task.delay() I know that task's delay() return AsyncResult but since delay() is called in signal, I can not get AsyncResult data outside of it (like at views.py etc) What I want to do is: 1. User rates product. (by ajax request) 2. When product.save() is called after rated, data analysis for Recommendation System run asynchronously through Celery 3. User access to mypage to see the result. 4. If AsyncResult of task were not completed, page shows "waiting", if not, it shows results. Maybe I can run task inside views.py or somewhere except signal, but if so, there would be a lot of duplicate codes. So I decided to run task inside signal. Is there any good way to implement this? Thanks. -
How to update last_changed field on many2many update in Django
Imagine I have the two models Pizza and Topping and the Pizza model has a last_changed field with auto_now=True and a many2many relationship to Topping. I now want the last_changed field to be updated whenever I add another Topping to the Pizza. Unfortunately this is not updated automatically since the Pizza model does not get saved in such a case. This is because the many2many relationship is held in a separate (auto created) model and table. So what would be the best approach to update the last_changed field? -
django-celery-results doesn't create any TASK db
I use django 1.9.7 and Celery 4.0. I installed django-celery-results and followed http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#django-celery-results-using-the-django-orm-cache-as-a-result-backend. When I access admin page, it shows But problem is when I run any asynchronous task, any of them doesn't create task result datas at all..even though all tasks worked really well(I checked it in flower and all task states are "success".) Here is my celery.py: # Using redis CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'django-db' Did I miss something? -
using dgango and postgress with eclipse instalation.
Im new to python, dgango, postgress and eclipse . I having a lot of trouble to instal and config dgango and postgress so i can use them in eclipse . I tries to folow the instructions from https://www.youtube.com/watch?v=o1STjuSTKcU&feature=youtu.be but when i typed ypolk -l i got: C:\Users\yaira\Documents\YASMIN\virtual_enviroments>yolk -l Traceback (most recent call last): File "C:\Users\yaira\AppData\Local\Programs\Python\Python36-32\Scripts\yolk-script.py", line 11, in load_entry_point('yolk==0.4.3', 'console_scripts', 'yolk')() File "c:\users\yaira\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources__init__.py", line 565, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "c:\users\yaira\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources__init__.py", line 2631, in load_entry_point return ep.load() File "c:\users\yaira\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources__init__.py", line 2291, in load return self.resolve() File "c:\users\yaira\appdata\local\programs\python\python36-32\lib\site-packages\pkg_resources__init__.py", line 2297, in resolve module = import(self.module_name, fromlist=['name'], level=0) File "c:\users\yaira\appdata\local\programs\python\python36-32\lib\site-packages\yolk\cli.py", line 262 print " %s %s (%s)" % (project_name, dist.version, ^ SyntaxError: invalid syntax I have no idea what does it mean , and what to do do with those results . Can someone explain it to me ? Thanku Yasmin -
browse server button, showing only thumbnails
I have applied the ckeditor to blog_description field with RichTextUploadingField. Below is the code: in models.py : class BlogModel(models.Model): blog_title = models.CharField(max_length=255) blog_image = models.ImageField(upload_to="images/") blog_description = RichTextUploadingField(null=True,blank=True) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) category = models.ForeignKey(BlogCategoryModel,to_field='category', default="--Select--") def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.blog_title In settings.py file I have mentioned almost all things as per https://github.com/django-ckeditor/django-ckeditor in settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'gez1%rj&tl&07gs^wak(hd=f1dip8xrzdz)2@15&#lk)5f(n*0' LOGIN_REDIRECT_URL = '/' # It means home view DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party 'crispy_forms', 'markdown_deux', 'pagedown', 'ckeditor', 'ckeditor_uploader', # local apps 'amcapp', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'amcsite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'amcsite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'amc_databasenew', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] … -
How to import xlx in django models?
i'm using django-excel to do this function. this is my view.py def import_data(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): request.FILES['file'].save_book_to_database( models=['contoh_upload'], initializers=[None,0], mapdicts=['id','nama','kelas'] ) message = "your upload has been uploaded " return render(request, 'kastransaksi/transaksi_formupload.html', {'message': message}) else: message = "Failed Upluad data" return render(request, 'kastransaksi/transaksi_formupload.html', {'form': form, 'message': message}) else: form = UploadFileForm() return render(request, 'kastransaksi/transaksi_formupload.html', {'form': form}) this is my models.py class contoh_upload(models.Model): nama = models.CharField(max_length=10, null=True, blank=True) kelas = models.CharField(max_length=10, null=True, blank=True) and this is my template.html <div class="alert-success">{{ message }}</div> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <!-- <input type="file" name="excel_file"> --> {{ form }} <input type="submit" name="input_button" value="UPLOAD" class="btn btn-primary"> </form> but i get this error Index out of range -
Django Convert server date to local date
Lets say i have a server date of format DD-MM-YYYY (got it from timezone) how can i change it to the corresponding date of the user? It should show the corresponding date with respect to the users time zone -
WSGI+DJANGO+Celery cannot import spec
I have set a right configurations for celery according documentation. And tested by using "run server", there is no problem. python2.7.12 celery 4.0.2 amqp 2.1.4 wsgi.py: import site site.addsitedir('/usr/local/lib/python2.7/site-packages/') import os import sys sys.path.append('opt/lampp/htdocs/dpcm/dpcm1') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dpcm1.settings") os.environ.setdefault("PYTHON_EGG_CACHE", "/home/inf/Documents/.python-eggs") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() However once start apache, it will generate an importerror: [Tue Feb 07 13:37:36.324620 2017] [:error] [pid 18099] [client 10.192.225.10:51555] Traceback (most recent call last): [Tue Feb 07 13:37:36.324718 2017] [:error] [pid 18099] [client 10.192.225.10:51555] File "/opt/lampp/htdocs/dpcm/dpcm1/wsgi.py", line 21, in <module> [Tue Feb 07 13:37:36.325041 2017] [:error] [pid 18099] [client 10.192.225.10:51555] application = get_wsgi_application() [Tue Feb 07 13:37:36.325115 2017] [:error] [pid 18099] [client 10.192.225.10:51555] File "/usr/local/lib/python2.7/site-packages/django/core/wsgi.py", line 13,in get_wsgi_application [Tue Feb 07 13:37:36.325353 2017] [:error] [pid 18099] [client 10.192.225.10:51555] django.setup(set_prefix=False) [Tue Feb 07 13:37:36.325420 2017] [:error] [pid 18099] [client 10.192.225.10:51555] File "/usr/local/lib/python2.7/site-packages/django/__init__.py", line 22,in setup [Tue Feb 07 13:37:36.325782 2017] [:error] [pid 18099] [client 10.192.225.10:51555] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Tue Feb 07 13:37:36.325859 2017] [:error] [pid 18099] [client 10.192.225.10:51555] File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ [Tue Feb 07 13:37:36.326306 2017] [:error] [pid 18099] [client 10.192.225.10:51555] self._setup(name) [Tue Feb 07 13:37:36.326366 2017] [:error] [pid 18099] [client 10.192.225.10:51555] File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup [Tue Feb 07 13:37:36.326488 2017] [:error] … -
Pass the Verbose Name of Django Choices Form Field to View Context
I am building a simple order form that have many choices fields. Each choices field has many options.. The form works great, it redirects to a thank you page, passing context, bills via Stripe and sends a notification email to admin. But when I get the email with the new order, I get a dollar amount for the different choice fields, but have no idea what it belongs to without the verbose label. Below is an example of one of my choice fields and the returned value on my thank you page. Heres a sample choices field MERCHANDISE_ORDER = ( ('10000', 'Flag with 5X7 Certificate'), ('2000', 'MSMA Hat'), ('500', 'Plaque Certificate'), ('500', 'Flag and Plaque Certificate'), ) The template tag ... <strong>Merchandise Order:</strong> ${{ merchandise_order }} <br> ... The returned value in my thank you page and email ... Merchandise Order: $5 ... As you can see, theres 4 choices so it would be great if I could get the returned value of Merchandise Order: Plaque Certificate - $5 or something similar and verbose. I am not using model forms and so I can control the styling, I am adding the form fields to my template manually with {{ form.merchandise_order … -
How to get data of a previous step in django FormWizard
Please recommend me the way how to get data, received in the first step of wizard, and use it in the form of second step: forms.py # First step form class W1_ParamForm(forms.Form): cities = forms.ModelChoiceField( label = 'City', queryset=City.objects.all().order_by('name') ) # Second step form class W1_SelectForm(forms.Form): oEstates = MyModelMultipleChoiceField( queryset = RealEstate.objects. filter(city_id__exact = ...). order_by('priceM'), widget = forms.CheckboxSelectMultiple, required = False) Herein ... - parameter, containing city id, selected in a first form W1_ParamForm. The problem - how to get it in the second form! views.py class W1_Estim(SessionWizardView): template_name = "w1_estim.html" def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] return render_to_response('w1_done.html', {'form_data': form_data}) urls.py urlpatterns = [ ... # Wizard start url(r'^doestim$', W1_Estim.as_view([W1_ParamForm,W1_SelectForm]), name='doestim'), ... Many thanks in advance! -
Counting the number of days between a certain day and now
I am a bit confused on a problem. I need your help to count the number of days between a certain date, e.g., 20-06-1991 (called birthday) and now. from datetime import datetime as dt days_between_two_date = '%s-%s' %(birthday, dt.now()).count() print(days_between_two_date) I know that code is probably very ugly, but it's been two days I program with Django. How could I correct that code to ask it counting the number of days between my birthday and now? -
how to create slack app automatically using python,django
I am using aws for which i am creating dynamic server with a domain name of each server. Now my problem is that i need to created slack for each separate sub-domain but can't do it. All the domains are connected to the single slack app only. I need to this programmatically can anyone help me in this -
Heroku error using collect static with Django 1.10
My app runs normally on my local and I can run python manage.py collectstatic --noinput without error. But when pushing to Heroku at the end of the build process I get the following error: $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle collected = self.collect() File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 112, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 399, in listdir for entry in os.listdir(path): OSError: [Errno 2] No such file or directory: '/tmp/build_732715d9b29ba88f9eb56ca3d7e722de/MY_REAL_APP_NAME/static' I looked at OSError: [Errno 2] No such file or directory: '/tmp/MakeCalls/Static' but when I remove my STATICFILES_DIRS, the app will deploy but all my static assets get a 404 error. I'm following the instructions on Heroku exactly, but it doesn't seem to work. Relevant parts of my settings.py file is as follows: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT … -
How do i logout the user in the following django code?
What i am trying to do: I am trying to logout the user whenever he/she clicks on the logout button. What problem do i get: I get the following problem when i click on logout button: My Code:- article.html: <div class="container"> <nav class="nav blog-nav"> <a class="nav-link" href="#">Library</a> {% if user.is_authenticated %} <a style="float: right;" class="nav-link" href="{% url 'librarysystem:Logout' %}">Logout</a> <a style="float: right;" class="nav-link" href="#">{{ request.user.username }}</a> {% if user.UserProfile.avatar == None %} <a style="float: right;" class="nav-link" href="#"><img class="img-thumbnail" src="/static/defaultPic/defaultPic.png" class="img-responsive" alt = "Generic placeholder thumbnail"/></a> {% else %} <a style="float: right;" class="nav-link" href="#" class="thumbnail"><img class="thumbnail" src="{{ request.user.UserProfile.avatar }}" class="img-responsive"/></a> {% endif %} {% endif %} </nav> </div> login View: def loginUser(request): data = {} if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') data['responseMessage'] = '' user = authenticate(username=username,password=password); if user is None: data['response'] = False else: if user.is_active: data['responseMessage'] = 'Already logged in.' else: login(request,user) data['redirectTo'] = "/librarysystem/article/" data['response'] = True return JsonResponse(data) logout View: def logoutUser(request): logout(request) template = 'librarysystem/Elib.html' return render(request, template) urls.py: from django.conf.urls import url from .import views urlpatterns = [ url(r'^register/$',views.registerUser), url(r'^$', views.index, name="Index"), url(r'^validateRegisterForm/$',views.validateRegisterForm), url(r'^validateLoginForm/$',views.validateLoginForm), url(r'^article/$', views.article, name="Article"), url(r'^Login/$',views.loginUser, name="Login"), url(r'^Logout/$',views.logoutUser, name="Logout"), ] -
Django: ValueError when saving an instance to a ForeignKey Field
I am trying to save an instance of a model but get a ValueError. ValueError: Cannot assign "<DataPointModel: DataPointModel object>": "Bike.data_point" must be a "DataPointModel" instance. The model has a very simple field: data_point = models.ForeignKey(DataPointModel, null=True, blank=True) And the method is as well. data_point = DataPointModel.objects.filter( object_id=bike.reference_model.id, ).last() watch.data_point = data_point watch.save() Why is this not saving? -
django onchange submit for entire form
I know this has been addressed before but I am having trouble making an on change submit work. Here is my forms.py nothing special in the model or the view. I relize I only selected this for one field but if it worked I would apply it to the others? #forms.py from django import forms from .models import rapidTill class RapidTillForm(forms.ModelForm): class Meta: widgets = {'linkArms': forms.RadioSelect(attrs={'onchange': 'RapidTillForm.submit();'}), 'shank':forms.RadioSelect, 'caddy':forms.RadioSelect, 'liftAssist': forms.RadioSelect, 'folding': forms.RadioSelect} fields = ['rows', 'space', 'folding', 'shank', 'caddy', 'linkArms', 'liftAssist','shank',] model = rapidTill and my form-template.html {% for field in form %} <span>{{field.errors}}</span> <label>{{field.label_tag}}</label> {{field}}</br> {%endfor%} -
Changed django model name, can I use the existing haystack index without rebuilding?
I have an existing haystack index (solr backend) with millions of items I'd prefer not to rebuild. However, the model name changed from "Event" to "Entry". For example: class EventIndex(indexes.SearchIndex, indexes.Indexable): class Meta: model = Entry .... [Custom Fields] .... def get_model(self): return Entry I had hoped using the same class name but adding the "class Meta" would indicate this was the same index and make previously indexed items available but this is not the case. When I index new items they show up in the search results, but all the previously indexed items do not. Can I somehow inform haystack of the updated name? From what I can tell solr itself is completely unaware of the model name so it feels like this should be possible just from the haystack end. Happy to provide further details if necessary. Thank you. -
Using a form as an alternative to a long list of URL links
I have a view set up so that the user will receive json data according to two variables they can select from (given the slugs 'url' and 'pollurl'). This will give approx. 100 different combinations. This is the view and the urlpattern: class site_pollutant_daily_means(APIView): def get(self, request, url, pollurl): means = DailyMean.objects.filter(url=url, pollurl=pollurl) serializer = DailySerializer(means, many=True) return Response(serializer.data) url(r'^json-api/daily-means/(?P<url>\w+)/(?P<pollurl>\w+)/$', views.site_pollutant_daily_means.as_view()), The only way I know how to generate links which would pass in 'url' and 'pollurl' is as follows: {% for value in object_list %} <ul><a href="/sites/{{value.url}}/">{{value.Site}}</a></ul> {% endfor %} I was hoping to have a more attractive and user-friendly layout than just displaying a long list of all the possible combinations of 'url' and 'pollurl'. I have searched for relevant Forms, looked in the docs and searched on this forum and am surpised that I have not found something I can use. I was thinking of perhaps two drop-down boxes or radio button forms. All the forms I have come across seem to be geared towards submitting data rather than simple GET requests. What are my best options for achieving what I want to achieve, or how should I go about this? -
Django how i can return Queryset to AJAX response?
Have a QuerySet object userorder = UserOrder.objects.filter( user_id=user_id, is_closed=0) response_data['uo'] = serializers.serialize('json', [ userorder, ]) But have Error Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\PhytonProgects\natarelochke\ordering\views.py", line 35, in ajax_check response_data = cfunc.check_cart(request, response_data) File "E:\PhytonProgects\natarelochke\ordering\cart_functions.py", line 96, in check_cart response_data['uo'] = serializers.serialize('json', [ userorder, ]) File "C:\Python27\lib\site-packages\django\core\serializers\__init__.py", line 129, in serialize s.serialize(queryset, **options) File "C:\Python27\lib\site-packages\django\core\serializers\base.py", line 83, in serialize concrete_model = obj._meta.concrete_model AttributeError: 'QuerySet' object has no attribute '_meta' [07/Feb/2017 05:13:02] "POST /ajax_response/ HTTP/1.1" 500 15833 Wanna get json object for work with him in client side -
How to solve TemplateDoesNotExist in Django?
settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] urls: urlpatterns = [ url(r'^hello/$', hello), url(r'^time/$', current_datetime), url(r'^time/plus/(\d{1,2})/$', hours_ahead), ] views: def current_datetime(request): now = datetime.datetime.now() t = get_template('current_datetime.html') html = t.render(Context({'current_date': now})) return HttpResponse(html) current_datetime.html: <html><body>It is now {{ current_date }}.</body></html> And I got this: TemplateDoesNotExist at /time/ current_datetime.html Request Method: GET Request URL: http://127.0.0.1:8000/time/ Django Version: 1.10.5 Exception Type: TemplateDoesNotExist Exception Value: current_datetime.html Exception Location: /Users/wonderful/anaconda/lib/python2.7/site-packages/django/template/loader.py in get_template, line 25 Python Executable: /Users/wonderful/anaconda/bin/python Python Version: 2.7.12 Python Path: ['/Users/wonderful/mysite', '/Users/wonderful/anaconda/lib/python27.zip', '/Users/wonderful/anaconda/lib/python2.7', '/Users/wonderful/anaconda/lib/python2.7/plat-darwin', '/Users/wonderful/anaconda/lib/python2.7/plat-mac', '/Users/wonderful/anaconda/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/wonderful/anaconda/lib/python2.7/lib-tk', '/Users/wonderful/anaconda/lib/python2.7/lib-old', '/Users/wonderful/anaconda/lib/python2.7/lib-dynload', '/Users/wonderful/anaconda/lib/python2.7/site-packages', '/Users/wonderful/anaconda/lib/python2.7/site-packages/Sphinx-1.4.6-py2.7.egg', '/Users/wonderful/anaconda/lib/python2.7/site-packages/aeosa', '/Users/wonderful/anaconda/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg'] Server time: Tue, 7 Feb 2017 10:42:42 +0800 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /Users/wonderful/mysite/mysite/templates/current_datetime.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/wonderful/anaconda/lib/python2.7/site-packages/django/contrib/admin/templates/current_datetime.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/wonderful/anaconda/lib/python2.7/site-packages/django/contrib/auth/templates/current_datetime.html (Source does not exist) How to solve it? -
_set in Django for a queryset
I'm a bit confused how to use _set in a queryset in Django. For example, a object Blog b, and the object Entry related by the attribute entry_set. What is the meaning of b.entry_set.all()?