Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a subdirectory "/ appname" in Nginx + Django?
I need to know how to make a subdirectory in Nginx with Django + WSGI. Something like this: mydomain.com/app I use: Django 1.11.15 Nginx 1.14.0 -
What is the ideal format/structure of urlconfs in django 2
I creating an application and one of its urlconf is as follows urlpatterns = [ path('', DashboardView.as_view(),name='dashboard:index'), ] I am coming from PHP background (say Laravel) where we name our routes like below dashboard:index - for get dashboard:store - for post dashboard:update - for patch etc... So I named my route as above, but while performing the system check, the following warning comes up. System check identified some issues: WARNINGS: ?: (urls.W003) Your URL pattern '' [name='dashboard:index'] has a name including a ':'. Remove the colon, to avoid ambiguous namespace references. System check identified 1 issue (0 silenced). So my question is what is the ideal naming format of URLs in Django in general. dashboard_index ? dashboard.index ? -
Google Traffic Maps API
Is it possible to use Google location API to build an app showing a populated area? Like how Google does with Google maps traffic. I'm building an app where it will show populated area on the map at a given time, depending on how many people are on that location. My plan is to get data from those random people without their input, so long as their locations is turned on. -
Django: CSRF token missing or incorrect when doing a PUT in C# .net
I am building an plugin for a certain application in c# which has to communicate with a Django rest interface. As you know, Django uses CSRF tokens for extra security. I have a problem when doing a POST/PUT call to Django. The call will always return "CSRF Failed: CSRF token missing or incorrect.". I tested the call in the browser (The web interface can also edit data, and will call the same PUT request), and to my surprise a different csrf token value is used in the X-CSRFToken header, than the one stored in the cookie. Is the X-CSRFToken header supposed to use a newly generated token ? The X-CSRFToken value is never used again after this call (the old csrftoken value is still used for all subsequent calls...). Obiously I have also read the Django docs regarding csrf tokens. Even though I think I understand how it works, I don't get why a new token is used for a POST/PUT. There are a lot of examples which do not make sense for use in my C# plugin. What i do before doing the PUT: Fetch the CSRF token by requesting the login page which contains the csrfmiddlewaretoken in it's … -
How do I configure the sending of json objects to Django Channels?
How do I configure the sending of json objects to Django Channels? To ensure that when adding a new object in the admin panel, it immediately appeared on the front in real time. Maybe someone has any examples. Would be very grateful. There is a Factory object: models.py class Factory(models.Model): OBJECT_CHOICES = ( ('Завод', 'Завод'), ('Вышка', 'Вышка'), ('Хранилище', 'Хранилище'), ('АЗС', 'АЗС') ) title = models.CharField(max_length=200) choice = models.CharField(max_length=15, choices=OBJECT_CHOICES, default = '') address = YmapCoord(max_length=200, start_query=u'Россия', size_width=500, size_height=500, unique = True) When a GET request is made to / getFactory /, JSON type is issued [ { "title": "factory", "choice": "Завод", "address": [ 55.744607932133505, 48.99357300960071 ] } ] -
django context_processors, request 'function' object has no attribute 'path'
First question asked in stack overflow here. So, I am starting a few Django projects and ended up with this issue: AttributeError: 'function' object has no attribute 'path' Which happens on the following context processor: def get_request_promotions(request): promotions = PagePromotion._default_manager.select_related() \ .prefetch_related('content_object') \ .filter(page_url=request.path) \ .order_by('display_order') if 'q' in request.GET: keyword_promotions \ = KeywordPromotion._default_manager.select_related()\ .filter(keyword=request.GET['q']) if keyword_promotions.exists(): promotions = list(chain(promotions, keyword_promotions)) return render(promotions, request) That is, Django isn't able to find the path object on request. This is my context processors in settings.py: TEMPLATES = [ { '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', 'django.template.context_processors.request', # For EL-pagination 'common.core.context_processors.metadata', 'portfolio.search.context_processors.search_form', 'store.promotions.context_processors.promotions', 'store.checkout.context_processors.checkout', 'common.accounts.notifications.context_processors.notifications', ], }, }, ] Any hints? -
Password Reset View not sending the email
I am using the view Password Reset View to let the user change its password. When I let the command EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' on I get the e-mail just fine in my console. However, I do not get the e-mail in my google input box. I added the following command in my settings.py file: EMAIL_HOST = 'smtp.mandrillapp.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'CheckStore' EMAIL_HOST_PASSWORD = 'h0YQijr21BgZX25s4gWjUA' DEFAULT_FROM_EMAIL = 'Time ScaleStore <ti@checkstore.com.br>' EMAIL_USE_TLS = True -
Adding cache to django couses ImproperlyConfigured: WSGI error
I'm following the official Django documentation. I added this to my settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = '900' # 15 minutes CACHE_MIDDLEWARE_KEY_PREFIX = '' MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] And this somehow causes this error: django.core.exceptions.ImproperlyConfigured: WSGI application 'online_store.wsgi.applicati on' could not be loaded; Error importing module Have anybody ever dealt with this? -
Getting a Model dynamic by knowing its name
I use Django 2.1. I have a general utility/function(using celery) that I call from the save method of a Model(is an abstract Model, inherited by other Models). Because the data from the function will be serialize, I pass to it the Model name and PK. class A(models.Model) def save(self, *args, **kwargs): send_async(model_name=type(self).__name__, pk=self.id)) class B(A) Later, I want to query the Model, but I don't know how to get the Model: I tried: model = apps.get_model('django_app_name.{}'.format(model_name)) I get the following error: No installed app with label 'django_app_name'. Also: model = ContentType.objects.get(model=model_name) This doesn't trow an error, but very strange behavior 'recalls' the View with different arguments, and off course no results. -
Enable keep-alive in django for persistent connection
I keep seeing references for keep-alive as a way to help maintain persistent connection, but I can't find any information on how to implement this with Django. How can I access this setting for Django? Thanks. -
Redirect to login page on accepting a garbage url in Django
so I'm new to Django and I was making a webapp, named accounts. I would like to have a path method in my urlpatterns that sends me to the login page whenever I enter a url that is not mentioned in my other path methods.(NOTE: I have used the built-in login method) How do I implement? urls.py from django.urls import path, url from . import views from django.contrib.auth.views import login, logout from django.views.generic import DetailView urlpatterns = [ path('display/', views.display), path('', views.home), path('login/', login, {'template_name': 'accounts/login.html'}), path('logout/', logout, {'template_name': 'accounts/logout.html'}), path('register/',views.register, name='register'), url('xxxx', login, {'template_name': 'accounts/login.html'}) #here, I'd like to change 'xxxx' ] -
Database Design: Same entity different relationships
I'm working on an e-commerce platform build using Django and Postgresql. In my platform I have an entity called "Category" and an entity called "Attribute". A category can have multiple attributes, but an attribute can only belong to one category. For example, the "digital camera" category can have battery, lens, image quality, etc. as its attributes. I have come to realize that some attributes can belong to multiple or all categories. For example: packaging, shipping, customer service, etc. What's the best way to approach this? I have thought of the following solutions: Make a default category and assign those attributes to that category. In the code write a special logic that will always look at these categories. Allow a nullable foreign key in the attributes table. So an attribute can belong to no specific category indicating that it belongs to all categories. Make another table for general categories. Store the category-attribute relationship in a third table. But then my question is how can I query for attributes that don't belong to any specific category? I appreciate your help in advance. -
django-toga: setup.py returned non-zero exit status 1
Trying to install the tutorial django project by following the instructions in the briefcase tutorial. It installs the Linux file just fine, but attempting to install it the same way but with django python3 setup.py django -s gives me the following failure: running django * Updating user code... * Installing requirements... No requirements. * Installing plaform requirements... Collecting toga-django==0.3.0.dev9 Using cached https://files.pythonhosted.org/packages/9e/88/49d9ab4c128e61a47bb365201fdfa3ebf1fd8905c0c5baa06dc248db9f0a/toga_django-0.3.0.dev9-py3-none-any.whl Collecting toga-core==0.3.0.dev9 (from toga-django==0.3.0.dev9) Using cached https://files.pythonhosted.org/packages/50/a1/ebc3b57145b03b644cc53c2693838eb3afafdb686eec2dffd90cf3548d09/toga_core-0.3.0.dev9-py3-none-any.whl Collecting django-environ==0.4.1 (from toga-django==0.3.0.dev9) Using cached https://files.pythonhosted.org/packages/f4/06/8dd165534eae19e72ca78bd6e845566cd1e0aacc9c20cc43984675748345/django_environ-0.4.1-py2.py3-none-any.whl Collecting django==1.10.6 (from toga-django==0.3.0.dev9) Using cached https://files.pythonhosted.org/packages/b9/bb/723f78e6f6aea78590331eba4e42b8a09c33ce154204a942525a91101d0b/Django-1.10.6-py2.py3-none-any.whl Collecting travertino>=0.1.0 (from toga-core==0.3.0.dev9->toga-django==0.3.0.dev9) Using cached https://files.pythonhosted.org/packages/56/3f/f03efe63c2bdc72763ac39777c9ebbab98605ced5c74aefe48b4fa0abb4d/travertino-0.1.2-py3-none-any.whl Collecting six (from django-environ==0.4.1->toga-django==0.3.0.dev9) Using cached https://files.pythonhosted.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl Installing collected packages: travertino, toga-core, django, six, django-environ, toga-django Found existing installation: travertino 0.1.2 Uninstalling travertino-0.1.2: Successfully uninstalled travertino-0.1.2 Found existing installation: toga-core 0.3.0.dev9 Uninstalling toga-core-0.3.0.dev9: Successfully uninstalled toga-core-0.3.0.dev9 Found existing installation: Django 1.10.6 Uninstalling Django-1.10.6: Successfully uninstalled Django-1.10.6 Found existing installation: six 1.11.0 Uninstalling six-1.11.0: Successfully uninstalled six-1.11.0 Found existing installation: django-environ 0.4.1 Uninstalling django-environ-0.4.1: Successfully uninstalled django-environ-0.4.1 Found existing installation: toga-django 0.3.0.dev9 Uninstalling toga-django-0.3.0.dev9: Successfully uninstalled toga-django-0.3.0.dev9 Successfully installed django-1.10.6 django-environ-0.4.1 six-1.11.0 toga-core-0.3.0.dev9 toga-django-0.3.0.dev9 travertino-0.1.2 * Installing project code... Traceback (most recent call last): File "setup.py", line 79, in <module> 'toga-django==0.3.0.dev9', File "/home/hv/Projects/tutorial/venv/lib/python3.6/site-packages/setuptools/__init__.py", line 140, in setup return distutils.core.setup(**attrs) File "/usr/lib/python3.6/distutils/core.py", … -
Django: Save several entries at once in database
I tried to avoid writing new_order['key']= value all the time and my solution was the one attached. It doesn't work. Can you help me how to fix it? new_order = self.order.save(commit=False) new_order = { 'total_gross': self.order_items_dict['total_gross'], 'total_tax': self.order_items_dict['total_tax'], 'total_net': self.order_items_dict['total_net'], 'event': self.order_items_dict['event'], 'order_reference': order_reference, 'status': OrderStatus.PAID, 'access_key': get_random_string(length=10), 'application_fee': self.order_items_dict['application_fee'], 'charge_id': charge.id, 'livemode': charge.livemode, 'balance_transaction': charge.balance_transaction } new_order.save() -
Celery in virtualenv with supervisor
supervisor install in Linux Ubuntu with python2.7 virtualenv:python3.6 + Django2.0 + celery4.2 My celery worker in local is well, but when I run Celery in virtual with supervisor: File "/path/env/mysite/mysite/__init__.py", line 5, in <module> from .celery import app as celery_app File "/path/env/mysite/mysite/celery.py", line 7, in <module> app.config_from_object('django.conf:settings', namespace='CELERY') TypeError: config_from_object() got an unexpected keyword argument 'namespace' My celery worker setting: [program:celery.worker] directory=/path/env/mysite/ command=/path/env/mysite/celery -A mysite worker -l info user=root numprocs=1 autostart=true autorestart=true stopsignal=INT stdout_logfile=/path/env/mysite/celery_worker.log stdout_logfile_maxbytes=10MB stdout_logfile_backups=10 redirect_stderr=false stderr_logfile=/path/env/mysite/celery_worker_err.log stderr_logfile_maxbytes=10MB stderr_logfile_backups=10 I tryed : 1.environment environment=PATH="/path/env/bin",VIRTUAL_ENV="/path/env/mysite/",PYTHONPATH="/path/env/lib/python:/path/env/lib/python3.6/site-packages" 2.command full_path command=/path/env/mysite/celery -A mysite worker -l info supervisor> status supervisor> status celery.work BACKOFF can't find command '/path/env/mysite/celery' I refer to someone else's path like this: command=/path/env/mysite/bin/celery -A mysite worker -l info but my project is no "bin" directory I tried: command=/path/env/bin/celery -A mysite worker -l info the error: ModuleNotFoundError: No module named 'mysite' -
The problem is when changing the proxy type to ajax in Ext.data.Store on ExtJs
My problem is when I change the type in the Store to ajax. The store in my application looked like this: var urlRoot = 'data?model=Operation&method='; Ext.define('BookApp.store.BookStore', { extend: 'Ext.data.Store', model: 'BookApp.model.Book', autoLoad: true, storeId: 'BookStore', proxy: { type: 'jsonp', noCache: false, api: { create: urlRoot + 'Create', read: urlRoot + 'Read', update: urlRoot + 'Update', destroy: urlRoot + 'Destroy' }, reader: { type: 'json', metaProperty: 'meta', rootProperty: 'data', idProperty: 'id', totalProperty: 'meta.total', successProperty: 'meta.success' }, writer: { type: 'json', encode: true, writeAllFields: true, rootProperty: 'data', allowSingle: false } } }); When I change the store type to ajax ..... proxy: { type: 'ajax', ..... then when I download the application I get error 500 (Internal Server Error) I know that the jsonp type is required to load data from another domain on which my application is running, but I have the entire application and the database included, is on the same local machine, so I set the type of ajax. But with this type a problem arises. On the backend side, the answer is as follows: ... # Form the answer dict_out= {"data" : list, "meta": { "success": "true", "msg": "", "total": str(count) }} # Translate it into the format … -
Dependency repository has been deleted but still exists in Ubuntu Server running Django app
I have a small issue with our servers and the dependency that has been installed on one of them. While I had once run a python setup.py develop to install a dependency from a github repository and then removed that file I am now trying to figure out if I could repack this dependency. The github account that I cloned from has been deleted and so I am no longer able to create similar intances/servers (unless I clone, which I would like to avoid). -
Django not serving images based on ImageFiled
I'm having issues serving images based on the ImageField in Django. models.py part looks like that: class Post(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) category = models.ManyToManyField(Category) trip = models.ForeignKey(Trip, on_delete=models.CASCADE) main_image = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='main_image') images = models.ManyToManyField(Image, related_name='images') class Image(models.Model): name = models.CharField(max_length=32) picture = models.ImageField(upload_to='pictures/', blank=True) trip = models.ForeignKey(Trip, on_delete=models.CASCADE) taken = models.DateTimeField(blank=True, null=True) uploaded = models.DateTimeField(default=timezone.now) def __unicode__(self): return self.name settings.py contains the MEDIA_URL and MEDIA_ROOT: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Also included what I've found in other SO topics in the urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls import url from django.contrib.staticfiles.urls import static, staticfiles_urlpatterns from django.conf import settings from markdownx import urls as markdownx urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), url(r'^markdownx/', include('markdownx.urls')), ] + staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In the end I put it in the html template like that: {% extends 'blog/base.html' %} {% block leftcolumn %} {% for post in posts %} <div class="leftcolumn"> <div class="card" style="max-width: 100%"> <h2><a href="">{{ post.title }}</a></h2> <h5>published: {{ post.published_date }}, by: {{ post.author }}</h5> <div><img src="{{ post.main_image.url }}"></div> <p>{{ post.byline }}</p> </div> </div> {% endfor … -
New model field showing in database query but not in django admin
I just added time_inserted = models.DateTimeField(auto_now_add=True) to my Shift model and when I query an object in the database it shows 'time_inserted': datetime.datetime(2018, 9, 5, 15, 26, 20, 226797) great! But I don't see it as a field in admin, how can I get it to appear there? -
Django model - interface design to avoid need of passing object in CHILD class calling method defined in PARENT class
I am using django 2.0.8 and Python 3.5. I have written a base class which encapsulates behavior in a base class. When using the interface in the child class, I find that I have to pass the object of the child class to the parent - which is not only ugly, is error prone. I do not want to use composition (instead of an interface), because AFAIK fields in django models are saved to the DB - that aside, I prefer the sub classing approach, since all the functionality can remain in the base class. Is there any way I can (in the parent class), find/obtain the instance (or at least the name of the class and it's id) that invoked the method call? Here is my code: class Likeable(models.Model): likes = GenericRelation(Like) def action_is_permissible(self, actionable_object, actor): ct = ContentType.objects.get_for_model(actionable_object) object_id = actionable_object.id found_objects = Like.objects.filter(content_type=ct, object_id=object_id, liker=actor) return ((len(found_objects) == 0), ct, object_id, found_objects) def add_like(self, actionable_object, actor): can_add, ct, object_id, found_objects = self.action_is_permissible(actionable_object, actor) print(can_add, ct, object_id, found_objects) if can_add: print('Save Called!') # Create like object and save it like = self.likes.create(content_type=ct, object_id=object_id, liker=actor) like.save() else: # do nothing print('Nothing doing') return class Meta: abstract = True class … -
Django filter F and functions of fields. Filter by comparison between fields with lookups
models from django.db import models from django.utils import timezone import datetime class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.FloatField(default=0) # ... def __str__(self): return self.choice_text creation #from polls.models import Choice, Question;from django.utils import timezone #q = Question(question_text="What's new?", pub_date=timezone.now());q.add(Choice(choice_text='variant', votes=0),Choice(choice_text='Not much', votes=0),Choice(choice_text='Just hacking again', votes=0),Choice(choice_text='The sky', votes=0));q.save;q = Question(question_text="m?", pub_date=timezone.now());q.save #q = Question(question_text="Third question", pub_date=timezone.now());q.add(Choice(choice_text='single option', votes=0));q.save() what I am trying to do is filter questions by question_text length being more than amount of choices(children): #from django.db.models import Count,F, Func,Value #q=Question.objects.all() #q.annotate(no=Count('choice')).filter(question_text__regex=r'.{3}')#works #q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(3)+'}')#works #q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(F('no'))+'}') #q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(F('nod'))+'}') #q.filter(question_text__regex=r'.{'+str(F('choice__count'))+'}') #q.filter(question_text__regex=r'.{'+str(Count('choice'))+'}') #Question.objects.filter(question_text__regex = r'.{'+(str(Count('choice')))+'}') #q.filter(question_text__regex=r'.{'+str(Count([1]))+'}') #q.filter(question_text__regex=r'.{'+str(Count([1,2,2,2,2,2,2,2,2,2,2,2,2,2]))+'}') #q.annotate(no=Func(F('question_text'), function='LENGTH')).filter(question_text__regex=r'.{'+str(F("no"))+'}') #q.annotate(no=Func(F('question_text'), function='LENGTH')).filter(no__gte=F('choice__count'))#works #q.filter(question_text__regex=r'.{'+str(F("choice__count"))+'}') #q.filter(question_text__regex=r'.{'+str(("choice__count"))+'}') #q.filter(question_text__regex=r'.{'+str(Count("choice__count"))+'}') #q.filter(question_text__regex=r'.{'+str(Count("choice"))+'}') #q.filter(question_text__regex=r'.{'+str(Value("choice__count"))+'}') #q.filter(question_text__regex=r'.{'+str(Value("choice__count"))+'}') question, which has length longer than amount of choices -
django model - message in save() method printed twice, but object saved once
I am using django 2.0.8 and Python 3.5. I have written a base class which encapsulates behavior in a base class. When the object is saved, it's supposed to print a message ONCE. However, when I run code that is supposed to save the object, I get the message "fire of message" printed twice - why? Here is my code: class Likeable(models.Model): likes = GenericRelation(Like) def action_is_permissible(self, actionable_object, actor): ct = ContentType.objects.get_for_model(actionable_object) object_id = actionable_object.id found_objects = Like.objects.filter(content_type=ct, object_id=object_id, liker=actor) return ((len(found_objects) == 0), ct, object_id, found_objects) def add_like(self, actionable_object, actor): can_add, ct, object_id, found_objects = self.action_is_permissible(actionable_object, actor) print(can_add, ct, object_id, found_objects) if can_add: print('Save Called!') # Create like object and save it like = self.likes.create(content_type=ct, object_id=object_id, liker=actor) like.save() else: # do nothing print('Nothing doing') return class Meta: abstract = True class Foo(Likeable): name = models.CharField(max_length=255,default='') objects = models.Manager() Example use (imports omitted) foo = Foo.objects.get(id=1) p = User.objects.get(id=1) foo.add_like(foo, p) # <- nasty API a** calling convention, but I digress Console output True foo 1 <QuerySet []> Save Called! Fire of like saved signal Fire of like saved signal Why is the message printed twice - when the object is saved only once in the db? -
Celery schedule doesn't trigger the tasks, no error reported
I'm using Django with celery: In celery.py I have: app.conf.beat_schedule = { 'send_notes_email': { 'task': 'send_notes_email_async', 'schedule': crontab(minute=3), }, } The task is set: @app.task(bind=True, name='send_notes_email_async', max_retries=3) def send_notes_email_async(): print('a') send_notes_email() Celery is working, recognize the tasks, but doesn't trigger after 3 minutes. Also no errors. -------------- celery@WIN-U5VDSO5V1CK v4.2.1 (windowlicker) ---- **** ----- --- * *** * -- Windows-7-6.1.7601-SP1 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: PH:0x3d2d128 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 2 (eventlet) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . send_notes_email_async Redis reports 2 keys -
Pass a URL as parameter in Django Urls
I'm working on a Django(2) project in which I need to pass an URL as a parameter in a Django URL, Here's what i have tried: urls.py: urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/(?P<address>.*)/$', PerformImgSegmentation.as_view()), ] views.py: class PerformImgSegmentation(generics.ListAPIView): def get(self, request, *args, **kwargs): img_url = self.kwargs.get('address') print(img_url) print('get request') return 'Done' But it doesn't work, I have passed an argument with the name as address via postman, but it failed. It returns this error: Not Found: /api/ [05/Sep/2018 15:28:06] "GET /api/ HTTP/1.1" 404 2085 -
How to automatically log user out when server is restarted?
Even when I restart my Django server, my user is logged in. Is there a quick way to log my user out automatically when I quit the server? I tried SESSION_EXPIRE_AT_BROWSER_CLOSE = True and it doesn't do anything Thanks!