Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
qr scanner update django database
I am relatively new to django and python. I want to make an app in django which records the amount of times I scan a specific QR code. I have no idea how to connect the Qr scanner on my phone to the online django database. Could anybody give me a pointer. -
Django - is it possible to filter a Queryset on a calculated field?
I have a database table which stores a users push notification time preferences, with local_push_time, and local_time_zone fields. I have an automated job that runs on our servers (in UTC time) every 10 minutes, and I’m looking to find users who are due to get a push notification in the next 10 minutes. Since we’re using Django, almost all of our data access takes places through the Django QuerySet API, which mostly does what we need. But for the use case described above, I’ve not seen a way that the QuerySet API could help here. What I’ve ended up doing is writing raw SQL, which looks something like this: SELECT * FROM user_push_preferences WHERE CAST(CAST(CAST(NOW() AS DATE) + CAST(local_push_time AS TIME) AS TIMESTAMP) AT TIME ZONE local_time_zone AS TIME) >= CAST(NOW() AS TIME) AND CAST(CAST(CAST(NOW() AS DATE) + CAST(local_push_time AS TIME) AS TIMESTAMP) AT TIME ZONE local_time_zone AS TIME) < CAST(NOW() AS TIME) + interval '10 minute’; We did consider storing a utc_push_time field on the DB table, but this was a non-starter, as it would need to update itself as the local_time_zone moves in or out of daylight savings time. So what I really want is to be able … -
Cannot import ASGI_APPLICATION module 'booktimes.routing'
I make chatting application, stuck since installed channel, I'm getting an error while ./manage.py runserver: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 08, 2020 - 11:11:30 Django version 3.0, using settings 'booktimes.settings' Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/channels/routing.py", line 29, in get_default_application module = importlib.import_module(path) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'booktimes.routing' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/channels/management/commands/runserver.py", line 101, in inner_run application=self.get_application(options), File "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/channels/management/commands/runserver.py", line 126, in get_application return StaticFilesWrapper(get_default_application()) File "/home/kash/.local/share/virtualenvs/booktimes-7D7i9gyr/lib/python3.7/site- packages/channels/routing.py", line 31, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'booktimes.routing' here is setting.py ALLOWED_HOSTS = [] CHANNEL_LAYERS = { 'default': { 'BACKEND': "channels_redis.core.RedisChannelLayer", 'CONFIG': … -
Django, including one template in another results TemplateDoesNotExist at /
I'm using Django 3.0.4, Python, 3.8, VS Code and Windows 10. I want to include the post_list.html and post_new.html templates in my base.html file. I need to show them all on the main website. I just want to have one page comprising these templates. I think this would allow me to have an audio file playing consistently even when I submit a post - page would not reload I believe (but I haven't achieved this phase of project yet). I started achieving my goal by including my template post_new.html in the base.html. However, I spinned up the server, visited main site and I encountered a problem: TemplateDoesNotExist at / post_new.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: post_new.html Exception Location: C:\Users\marecki\Desktop\mareknasz_projekt\evviva_larte\venv\lib\site-packages\django\template\backends\django.py in reraise, line 84 Python Executable: C:\Users\marecki\Desktop\mareknasz_projekt\evviva_larte\venv\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\\Users\\marecki\\Desktop\\mareknasz_projekt\\evviva_larte\\ewiwa', 'C:\\Program Files (x86)\\Python38-32\\python38.zip', 'C:\\Program Files (x86)\\Python38-32\\DLLs', 'C:\\Program Files (x86)\\Python38-32\\lib', 'C:\\Program Files (x86)\\Python38-32', 'C:\\Users\\marecki\\Desktop\\mareknasz_projekt\\evviva_larte\\venv', 'C:\\Users\\marecki\\Desktop\\mareknasz_projekt\\evviva_larte\\venv\\lib\\site-packages'] Server time: Wed, 8 Apr 2020 12:57:51 +0200 In settings.py I have included the following: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], This is a base.html: {% load static %} {% include "post_new.html" %} <html> <head> <link rel="shortcut icon" href="{% static '/assets/favicon-32x32.png' %}" /> … -
Is there any way to get Domain name in Django DRF
I created REST API in Django DRF and it will using clients. Now, i would like to get Client's Domain name and IP address. I get the IP through request.META suggest me, is there any way to get proper Domain_name and IP_address -
How to pass parameters in dict form using drf-yasg(Swagger)
I'm trying to pass the parameters in dict format how can I do this using drf-yasg. { "a": false, "stores": { "type1": 678, "type2": 58, "type3": 58 }, "contact": { "mobile_valid": true, "mobile": "00000000" } } -
Correct way of overriding URL viewflow (Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name.)
im stuck with an error of : Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. when i tried to override the AssignTaskView View. The rationale for doing so is to allow my user to reassign Tasks to others without having to generate a seperate task to do so as well as to put in my custom forms for displaying the lsit of users to choose from. I have most of my inspirations from this particular post : Overwrite django view with custom context (Django 1.11, Viewflow) And here is my code: url.py It actually allows me to override and display my own form . path('pipeline/<process_pk>/documents/<task_pk>/assign/', OverrideTaskView.as_view(), { 'flow_class': Pipeline, 'flow_task': Pipeline.documents }), the issue lies here : views.py class OverrideTaskView(AssignTaskView,FormView): form_class=AssignForm def get_form_kwargs(self): kwargs = super(OverrideTaskView, self).get_form_kwargs() kwargs.update({'id': self.request.user}) return kwargs def get_context_data(self, **kwargs): context = super(AssignTaskView, self).get_context_data(**kwargs) context['activation'] = self.activation return context def form_valid(self, form): if '_assign' or '_continue' in request.POST: form.save(commit=False) assigned = form.cleaned_data.get('user') self.activation.assign(assigned) self.success(_('Task {task} has been assigned')) return HttpResponseRedirect(self.get_success_url()) else: return self.get(request, *args, **kwargs) I suspect it has something to do with the get_success_url ? The error only pops up after i click the confirmation button , please … -
Template Does not exsist-heroku django
I have been working on a django application by following the coreyMS tutorials.Now it is at the deployment stage.I tried to deploy the app using heroku. The app gets deployed and all the blog apps templates are fine.But the users app templates are not getting rendered.Any help will be appreciated.Thanks in advance! My settings.py file: { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], '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', ], }, }, ]``` Only the templates of blog are getting rendered.I am having two apps-blog and users. in both the apps i have the templates in the following way: app->templates->appname->.htmlfiles One is getting rendered while the other is not.. -
NoReverseMatch at / Reverse for 'delete_order' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_order/(?P<pk>[^/]+)/$']
i am using to delete a specific data in table. But this is not working ! i Can't seem to find any wrong with my code ! please help me this is making me crazy ! i did exactly what youtube did but their's code is working while mine is showing error like this: NoReverseMatch at / Reverse for 'delete_order' with arguments '('',)' not found. 1 pattern(s) tried: ['delete_order/(?P[^/]+)/$'] here the views.py def deleteOrder(request, pk): order = anime.objects.get(id=pk) if request.method == "POST": order.delete() return redirect('/') context={'list':order} return render(request, 'main/delete.html',context) here's table.html <td><a href="" class="btn btn-success">Update</a></td> <td><a href="{% url 'delete_order' order.id %}" class="btn btn-danger">Delete</a></td> </tr> {% endfor %} here's urls.py urlpatterns = [ path('',views.homepage,name ="homepage"), path('anime/',views.addAnime,name="anime"), path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"), ] -
django-inlinecss returns error You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
I am trying to load a page as PDF. actually it loaded successfully - without any style or even the images. So I installed django-inlinecss and added it in installed_apps in settings.py and loaded it in template and called it as I was told. but it returns an error You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. and points at: 1 {% load inlinecss %} 2 {% load static %} 3 {% inlinecss "css/style.css" %} <--- I don't have any idea how to fix it. Hope someone could help me in this -
Reverse for 'user_login' not found. 'user_login' is not a valid view function or pattern name
These are my files while making a signup and login page please tell me where it went wrong. url.py/home ''' from django.contrib import admin from django.urls import path,include from . import views app_name='home' urlpatterns = [ path('',views.index, name='index'), path('register/',views.register, name='register'), path('login/',views.user_login, name='login'), ] ''' views.py ''' def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account was inactive.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username,password)) return HttpResponse("Invalid login details given") else: return render(request, 'home/login.html', {}) ''' settings.py ''' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'media') STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR,] MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' LOGIN_URL = '/home/user_login/' ''' -
How to run properly my django project in aaPanel in production
I face with the problem that my app can not start properly in production using the aaPanel. How can i face that in order to run properly? Here is my log 2020-04-08 16:30:27 +0800] [16670] [INFO] Starting gunicorn 20.0.4 [2020-04-08 16:30:27 +0800] [16670] [INFO] Listening at: http://0.0.0.0:19997 (16670) [2020-04-08 16:30:27 +0800] [16670] [INFO] Using worker: geventwebsocket.gunicorn.workers.GeventWebSocketWorker [2020-04-08 16:30:27 +0800] [16673] [INFO] Booting worker with pid: 16673 [2020-04-08 16:30:27 +0800] [16673] [INFO] Worker exiting (pid: 16673) [2020-04-08 16:30:27 +0800] [16670] [INFO] Shutting down: Master [2020-04-08 16:30:27 +0800] [16670] [INFO] Reason: App failed to load. I have already installed gunicorn 19.6.0 gevent 1.4.0 event-websocket 0.10.1 Django 1.10.1 python 3.7.4 -
Openstack Horzion Install -> TemplateDoesNotExist: registration/login.html
I'm currently installing Openstack Stein, and now I'm trying to install Horizon, following the tutorial. I end up in this error: ERROR django.request Internal Server Error: /horizon/auth/login/ Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/usr/local/lib/python3.6/dist-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/usr/local/lib/python3.6/dist-packages/django/template/response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "/usr/local/lib/python3.6/dist-packages/django/template/response.py", line 63, in resolve_template return select_template(template, using=self.using) File "/usr/local/lib/python3.6/dist-packages/django/template/loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: registration/login.html I didn't create any template, it is a fresh installation from the Openstack Tutorial. I googled it but didn't found any answer. Thks for the help -
Django don't generate primary_key
I write the migration manually to quickly add to the new environment. When I try to create a new object of the Operator model I get an error about an empty id. I tried to set managed = False in meta and fake Operator model but none of this brought results. What's wrong with my code? My model: class Operator(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=256) class Meta: db_table = '"mts_market"."operator"' managed = False def __str__(self): return self.name My migration: from django.db import migrations def forwards_func(apps, schema_editor): product = apps.get_model("landings", "Product") merchant = apps.get_model("landings", "Merchant") partner = apps.get_model("landings", "Partner") operator = apps.get_model("landings", "Operator") tariff = apps.get_model("landings", "Tariff") db_alias = schema_editor.connection.alias partner = partner.objects.using(db_alias).get(name="binding") merchant = merchant.objects.using(db_alias).get(name="dc") operator.objects.using(db_alias).bulk_create([ operator(name="test") ]) operator = operator.objects.using(db_alias).get(name="test") product.objects.using(db_alias).bulk_create([ product(name="mirrorcheck", merchant=merchant, mnp_service_name_card="test", partner=partner, operator=operator, sub_service_name_card="test", has_many_subs=True, category='retail', ]) product = product.objects.using(db_alias).get(name="mirrorcheck", partner=partner.id, merchant=merchant.id, operator=operator.id) tariff.objects.using(db_alias).bulk_create([ tariff(name='card_subscription', value=100, product=product, mnp_instance_details={}, sub_instance_details={"amount": 29900}, ) ]) partner = partner.objects.using(db_alias).get(name="upfront") product.objects.using(db_alias).bulk_create([ product(name="mirrorcheck", merchant=merchant, mnp_service_name_card="test", partner=partner, operator=operator, sub_service_name_card="zenit_bank_test", has_many_subs=True, category='retail', ]) product = product.objects.using(db_alias).get(name="mirrorcheck", partner=partner.id, merchant=merchant.id, operator=operator.id) tariff.objects.using(db_alias).bulk_create([ tariff(name='card_subscription', value=29900, product=product, mnp_instance_details={}, sub_instance_details={"amount": 29900}, ) ]) def reverse_func(apps, schema_editor): operator = apps.get_model("landings", "Operator") product = apps.get_model("landings", "Product") tariff = apps.get_model("landings", "Tariff") partner = apps.get_model("landings", "Partner") db_alias = schema_editor.connection.alias partner = partner.objects.using(db_alias).get(name="binding") … -
why django is not fetching files from database again
why Django is not fetching files from database again? (i deleted) if it is not exist in media directory -
How to resolve static don't found on hosting django
Django does not load static on a site that is hosted (collectstatic did).I know that there are a lot of such questions, but I tried most of the solutions and did not help(I do not know what files to expose to understand the problem, so if you need more, I will expose) settings.py(static part): STATIC_URL = '/static/' MEDIA_URL = "/media/" STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), '/home/users/m/marselabdullin/caparol_center_spb_decision/static/', ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) static folder on hosting: -
Arbitrarily set position/order of ManyToMany field in django admin?
I have the below models: """ Child class Media (models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=128,unique=True) file = models.FileField() enabled = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name """ Parent class Gallery(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=128,unique=True) description = models.TextField(max_length=254,null=True) medias = models.ManyToManyField(Media,related_name='medias') enabled = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "gallery" verbose_name_plural = "galleries" def __str__(self): return self.name I would like to be able to sort the child table by setting it in junction table; therefore not affecting the child table. I'm thinking of setting position field in junction table, is manually adding it in DB the only way of doing that? I'm fairly new to Django and I'm sorry in advance if this happens to be just a basic question. -
How to use Select2 in Django custom SimpleListFilter
I've created a custom SimpleListFilter class (code below) and managed to have the options be displayed as a select input. What I'd like to add is the functionality that Select2 offers, namely being able to search for options within the select input. Can anyone tell me how to achieve this? Custom SimpleListFilter class: class AnswerTreeKnowledgeCodeListFilter(admin.SimpleListFilter): template = 'admin/dropdown_filter.html' title = _('Kenniscode') parameter_name = "knowledge_code" def lookups(self, request, model_admin): return [(instance.pk, str(instance)) for instance in AnswerTreeRepository.filter_by_level(0)] def queryset(self, request, queryset): # Custom queryset filtering here dropdown_filter.html: (copied from source that I forgot, so I take no credit for this code) {% load i18n %} <script type="text/javascript">var go_from_select = function(opt) { window.location = window.location.pathname + opt };</script> <h3>{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}</h3> <ul class="admin-filter-{{ title|cut:' ' }}"> {% if choices|slice:"4:" %} <li> <select class="form-control" style="width: 95%;margin-left: 2%;" onchange="go_from_select(this.options[this.selectedIndex].value)"> {% for choice in choices %} <option{% if choice.selected %} selected="selected"{% endif %} value="{{ choice.query_string|iriencode }}">{{ choice.display }}</option> {% endfor %} </select> </li> {% else %} {% for choice in choices %} <li{% if choice.selected %} class="selected"{% endif %}> <a href="{{ choice.query_string|iriencode }}">{{ choice.display }}</a></li> {% endfor %} {% endif %} </ul> -
Do you know Alternatives to PHPliteadmin or PHPAdminer? Create one with Django?
I'm struggling to find an Open Source Webinterface in Order to have a variety of options to interact with SQlite3 database. What I'm looking for is a webinterface, where I can have tables linked with keys to each other and a possibility to put SQL queries, that can output what I'm searching for in the tables. When it shows all the data it found with the queries I want to edit those right when it shows them to me - not by going back and searching the table where it is inside. I hope you understand what I'm trying to search. Phpliteadmin and adminer don't support it, do you know an alternative or a django example that goes in that direction that I'm searching for? Maybe I could program the code so that it could fullfill the needs. I thank you very much for your help, I really appreacciate it! -
Update Twilio CallStatus dynamically with Django template
I'm using Twilio to make outgoing and receive incoming voice calls from browser with Django, I'm trying to show user the callStatus dynamically. this is my view: @csrf_exempt def call(request): response = VoiceResponse() dial = response.dial(caller_id=settings.TWILIO_NUMBER, answer_on_bridge=True) if 'phoneNumber' in request.POST: dial.number(request.POST['phoneNumber'], status_callback_event='initiated ringing answered completed', status_callback='https://my-web-app/call-status', status_callback_method='POST') else: caller_number = request.POST.get('Caller') response = VoiceResponse() dial_incoming = response.dial(caller_id=caller_number) dial_incoming.client('agent') return HttpResponse( str(response), content_type='application/xml; charset=utf-8' ) I'm receiving the callStatus without any problems, I can print it doing: print(request.POST.get('CallStatus')) What is the best way to show user the callStatus dynamically? Javascript Websocket? Websocket using Django channels? -
Unable to deploy Django app in Heroku due to requirements.txt error
I am trying to deploy a django app I created to heroku. When i do git push heroku master an error shows remote: cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory. here is the full log: Enumerating objects: 35, done. Counting objects: 100% (35/35), done. Delta compression using up to 2 threads Compressing objects: 100% (32/32), done. Writing objects: 100% (35/35), 12.68 KiB | 405.00 KiB/s, done. Total 35 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory remote: -----> Installing python-3.6.10 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: Sqlite3 successfully installed. remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.7 remote: Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) remote: Collecting astroid==2.3.3 remote: Downloading astroid-2.3.3-py3-none-any.whl (205 kB) remote: Collecting colorama==0.4.3 remote: Downloading colorama-0.4.3-py2.py3-none-any.whl (15 kB) remote: Collecting dj-database-url==0.5.0 remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Collecting Django==3.0.5 remote: Downloading Django-3.0.5-py3-none-any.whl (7.5 MB) remote: Collecting django-heroku==0.3.1 remote: Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) remote: Collecting gunicorn==20.0.4 remote: Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) remote: Collecting isort==4.3.21 remote: Downloading isort-4.3.21-py2.py3-none-any.whl (42 kB) remote: Collecting lazy-object-proxy==1.4.3 remote: Downloading lazy_object_proxy-1.4.3-cp36-cp36m-manylinux1_x86_64.whl (55 kB) remote: Collecting … -
Django - How do I filter profile by user group?
How do I filter profile by user group? So far I have this: class StaffManager(models.Manager): def get_queryset(self): return ?? # should filter user group by staff class Operator(models.Model): user = models.OneToOneField( User, to_field='id', primary_key=True, related_name='operator', on_delete=models.CASCADE) ... staffs = StaffManager() def group(self): return ", ".join(list(self.user.groups.values_list('name', flat=True))) -
Python, passing object in html not working [closed]
def index(request): dest1= Destination() dest1.name ='kathmandu' dest1.desc = 'Golden city in the world' dest1.img = 'destination_2.jpg' dest1.price= 2000 dest2 = Destination() dest2.name ='Pokhara' dest2.desc = 'Beautiful city in Nepal' dest2.img = 'destination_3.jpg' dest2.price= 2500 dest3 = Destination() dest3.name ='Biratnagar' dest3.desc = 'Old city in the world' dest3.img = 'destination_1.jpg' dest3.price= 1000 dests = [dest1, dest2, dest3] return render(request, 'index.html', {'dests': dests}) by doing this its not working data is not displaying in the index page but if I pass like return render(request, 'index.html', {'dest1': dest1, 'dest2': dest2,'dest3': dest3}) IF I DO THIS THAN IT SHOWS THE DATA IN THE OUTPUT.. WHAT IS WRONG AS THE YOUTUBER WHO TEACHES IN HIS VIDEO IT SHOW IT WORKED IN THE FIRST ONE. CAN ANYONE HELP ME EXPLAINING THIS PLEASE -
Updating in Pipenv
I have a problem regarding pipenv. Maybe it is only my understanding, but we will see. I have a project that uses python 3.7 and Django 2.1. Now the latest version of Django is 3.0.5. I now want to update my Django version, but I have no idea how. pipenv update does nothing it only tells me that my requirements are already met. Even uninstalling Django an reinstalling it, does not update the version. I have no idea, how to do this. Thanks for the help. -
What is the proper way to write permission_required in a view in django?
I am trying to implement a web app in django where I have a class based view that inherits from PermissionRequiredMixin and generics.View. Here is an example model: class SomeModel(models.Model): # Here I will put some model attributes class Meta: permissions = ( ('some_permission', 'Can do some job'), ) Until now I am not confused yet. However, when I am trying to write the view, I am confused. I read some Stack Overflow questions and also the django documentation, but I did not understand well because they are writing something like this: class MyView(PermissionRequiredMixin, View) permission_required = ('polls.can_open', 'polls.can_edit') I tried to figure out what to write in my case, and I ended up in writing this: class SomeView(PermissionRequiredMixin, View): permission_denied_message = 'You don\'t have permission' permission_required = 'app_name.some_permission' What made me in doubt is that PyCharm did not auto-complete when I wrote the last line which is: permission_required = 'app_name.some_permission'. Also, I am not sure whether django will know which permission that I am talking about here. Did I understand how to do the job? or I am wrong? Should I write it like this: permission_required = 'app_name.SomeModel.some_permission'?