Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Factory boy yielding a "maximum recursion depth exceeded" error
I'd like to defined two models, Company and Package. Each Package has only one Company, but a Company can have several Packages. However, each company can have only one default_package (which can be null). I've set this up as follows: class Company(models.Model): default_package = models.OneToOneField( 'dashboard.Package', on_delete=models.SET_NULL, blank=True, null=True, related_name='default_for_%(class)s') class Package(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) where dashboard is the app label. In order to simplify tests with these models, I've created test factories for them using factory_boy as follows: import factory from .models import Company, Package class CompanyFactory(factory.Factory): class Meta: model = Company default_package = factory.SubFactory('dashboard.test_factories.PackageFactory') class PackageFactory(factory.Factory): class Meta: model = Package company = factory.SubFactory(CompanyFactory) Now I'm trying two tests: class DefaultPackageTest(TestCase): def test_1(self): company = Company.objects.create() def test_2(self): company = CompanyFactory() The first one simply creates a Company, whereas the second one tries to do the same thing using the CompanyFactory. Strangely, however, the first test passes, whereas the second one fails: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/factory/builder.py", line 233, in recurse return builder.build(parent_step=self, force_sequence=force_sequence) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/factory/builder.py", line 272, in build step.resolve(pre) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/factory/builder.py", line 221, in resolve self.attributes[field_name] = getattr(self.stub, field_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/factory/builder.py", line 355, in __getattr__ declaration = self.__declarations[name] File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/factory/builder.py", line 121, in __getitem__ context=self.contexts[key], RecursionError: maximum recursion … -
problems in constructing webmap using django leaflet with the data in database
I have done my leaflet program using django-leaflet but the map is not displaying anything in output Here is the code models.py from django.db import models from django.contrib.gis.db import models as gismodels class MushroomSpot(gismodels.Model): title = models.CharField(max_length=256) id1=models.IntegerField(primary_key=True) geom = gismodels.PointField() objects = gismodels.GeoManager() def __unicode__(self): return self.title urls.py from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from django.contrib import admin from django.views.generic import TemplateView from djgeojson.views import GeoJSONLayerView from .models import MushroomSpot urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'), url(r'^data.geojson$', GeoJSONLayerView.as_view(model=MushroomSpot), name='data'), ] index.html {% load leaflet_tags %} <html> <head> {% leaflet_js %} {% leaflet_css %} </head> <body> <h1>Weather Stations</h1> {% leaflet_map "main" callback="main_map_init" %} <script type="text/javascript"> function main_map_init (map, options) { var dataurl = '{% url "data" %}'; // Download GeoJSON via Ajax $.getJSON(dataurl, function (data) { // Add GeoJSON layer L.geoJson(data).addTo(map); }); } </script> </body> </html> contents related to leaflet in settings.py DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } SPATIALITE_LIBRARY_PATH = 'mod_spatialite' STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR LEAFLET_CONFIG = { 'DEFAULT_ZOOM': 6, 'MIN_ZOOM': 1, 'MAX_ZOOM': 20, } And I run the setup.py file which has import csv from django.contrib.gis.geos import Point from mushrooms.models … -
Nginx not serving up Django admin static files
An example 404 URL: http://ip.address/static/admin/css/base.css I'm not sure what I did wrong. Here's the associated files: settings.py STATICFILES_DIRS = [ '/home/username/sitename/sitenameenv/lib/python3.5/site-packages/django/contrib/admin/static', ] STATIC_URL = '/static/' STATIC_ROOT = '/home/username/sitename/website/staticroot/' Nginx config: server { listen 80; server_name http://ip.address/; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username/sitename/website/; } location / { include proxy_params; proxy_pass http://unix:/home/username/sitename/sitename.sock; } } The regular static files are being served up correctly, and they were doing so also before I added STATIC_ROOT and used collectstatic, which I didn't think was necessary. My admin is getting 404s for its static files though. -
Django REST framework cross model endpoint
Let's say I have these 3 models class Restaurant(models.Model): name = models.CharField(...) class Eater(models.Model): name = models.CharField(...) class Transaction(models.Model): eater = models.ForeignKey('Eater') restaurant = models.ForeignKey('Restaurant') How can I write an end point like "eater/1/restaurant" to query for all the restaurant that eater1 has a transaction with? My db is in PostSql if that matters. -
Django returns if request.method statement false and returns blank template
I'm trying to do a simple file upload for my project, but there seems to be a problem. So, once a user is logged, I try to upload a file by clicking a button, but the result is a blank template. Here is my upload function in views.py: def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('main:register') else: return render(request, 'main/model_form_upload.html', {'form': form}) else: return render(request, 'main/user_panel.html') Class in forms.py: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'document') Class in models.py: class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) And the url: url(r'^upload/$', views.model_form_upload, name='upload') In model_form_upload.html I have just this: {% extends 'main/user_base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'main:upload' %}">Return to home</a></p> {% endblock %} I attempt to render the template by clicking a button and it looks like this: <a href="{%url 'main:upload'%}" class="btn btn-primary"><font face="Ubuntu">Upload</font></a> The main problem is that, after a bit of checking and searching, I found out that it doesnt return anything mainly because the 'if request.method == 'POST'' statement in model_form_upload returns false, and so it … -
Timezone aware datetime field in Mysql with Django Rest Framework
I'm storing datetimes in Django in UTC format in a mysql db. I'm aware that mysql doesn't store datetimes with a timezone and the solution for most people seems to be to let the frontend convert the datetime to the client's current timezone. That solution doesn't work for me as I need to know the timezone of the datetime on the server as I run cronjobs based on the datetimes and they need to be timezone aware. The easiest solution seems to be to store the timezone in a separate db field and then do the conversion when I run the cronjob. I'm having a hard time believing that there's not a better way in 2018. Any ideas? -
How can I test alternative body content in EmailMultiAlternatives object using django test system?
I have EmailMultiAlternatives object with text and html content in my view: email = EmailMultiAlternatives(subject=subject, body=message, from_email=sender, to=recipient) email.attach_alternative(messageHTML, 'text/html') When I test the content of message body attribute contains the text version and I don't know how to assert html content: self.assertHTMLEqual(mail.outbox[0].body, message) # This test passes self.assertHTMLEqual(mail.outbox[0].<???>, messageHTML) # But here I don't know what to do -
Defining a limit_choices_to for a OneToOneField which references the current model
I have two models, Company and Package, with a many-to-one relationship between them: each Company can have several Packages, but each Package has only one Company. In addition, however, I'd like to define a default_package field for the Company model, which is a Package, and I'd like to limit the choices to the packages whose Company is the company under consideration. class Company(models.Model): default_package = models.OneToOneField( 'dashboard.Package', on_delete=models.SET_NULL, blank=True, null=True, related_name='default_for_%(class)s') class Package(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) However, I'd like to add a limit_choices_to argument to the default_package field which would be something like default_package = models.OneToOneField(..., limit_choices_to={'company': <this_company>}) where <this_company> is a reference to the current company. I'm not what the syntax for this would be, though; can anyone offer some help? -
How to create a URLS with the question mark (?) In Django
I create a URLS with the question mark (?) In Django. The link does not work because the? is replaced by ca: % 3F here is the result of the url: / blog / Detail /% 3Ffollow_Jeudi = 2018-03-15. I would like to get this: / blog / Detail /? Follow_Jeudi = 2018-03-15 How can I fix this problem. Here is my view, the template and the url. My view: from django.http import HttpRequest def DateAdd(request): if request.GET.get('date_create_schedule'): date_text = request.GET.get('date_create_schedule') newHistory = fdt_schedulejour(date=date_text,user_id=request.user.id) newHistory.save() results = 'test' title = '?follow_' jour_date = date_text return redirect('ajout_date', title,jour_date_text,jour_date) My template: <div class="container text-center"> <form class="form-signin" id="login_form" method="get" action="/blog/DateAdd/"> <br> <input type="text" name="date_create_schedule" value="{{ Activite_Date_click|date:"Y-m-d" }}" > <br> <button class="btn btn-lg btn-primary btn-block" type="submit">Get Data</button> </form> </div> My urls: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.urls import path,include from django.contrib.auth import views as auth_views from blog import views urlpatterns = [ path('Detail/<str:title_p><str:jour_date_text><str:jour_date>', views.DetailView.as_view(), name='ajout_date'), ] Thank you -
Django How improve query_params consult
i'm filtering my view queryset base on the request query_params but I don't like how i do it, is there any way to do this most pythonic? def get_queryset(self): qs = Publication.objects if self.request.query_params.get('user'): user = self.request.query_params.get('user') if user.isdigit(): qs = qs.filter(owner__pk=user) limit = self.request.query_params.get('limit') if limit and limit.isdigit(): return qs.all()[:int(limit)] return qs.all() -
connect next.Js with django
I'm trying to get Next to work with my django template. My urls.py looks like this: urlpatterns = [ path('admin/', admin.site.urls), re_path('^(?!static).*$', index), ] I'm basically redirecting every /foo/bar request to the index view, which renders the index.html template, which looks like this: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script type="application/javascript" src="{% static "dist/bundles/pages/_document.js" %}"></script> </head> <body> Hey </body> </html> So my question is, which one is the "main" next JS file, that should go inside my <script type="application/javascript" src="..."></script>? -
Saved model is None
So i have a model that i'm trying to save using a form which submits successfully, but in the Admin the object value None. I know the problem is in the views but i can't figure it out. Here's my code: Views.py def profilecreate(request): if request.method == 'GET': form = ProfileForm() else: form = ProfileForm(request.POST) if form.is_valid(): description = form.cleaned_data['description'] caption= form.cleaned_data['caption'] photo = form.cleaned_data['photo'] profile = Profile.objects.create(description=description, caption=caption, photo=photo) return HttpResponseRedirect(reverse('profile-id', kwargs={'profile_id': profile.id})) return render(request, 'profile_form.html', {'form': form}) Someone please assist -
Django ORM GROUP BY and SUM
Some trable with GROP BY and SUM Django ORM make this query : "SELECT "p_record"."h", SUM("p_record"."size") AS "size__sum" FROM "p_record" GROUP BY "p_record"."h", "p_record"."size" ORDER BY "p_record"."size" DESC LIMIT 15" when I do record.objects.all().values('h').annotate(Sum('size')).order_by('-size')[:15] or record.objects.all().values('h').order_by('h').annotate(Sum('size')).order_by('-size')[:15] BUT 'h' not grouped! Where I missed bug? tested on sqlite and postgres. Django 10.6 have some result: . h: size: <li>"aa.ss.aa" = 15</li> <li>"aa.dd.aa" = 2</li> <li>"aa.ss.aa" = 4</li> <li>"zz.aa.cc" = 9</li> <li>"aa.ss.aa" = 9</li> -
Django The empty path didn't match any of these
api/v1/views.py from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request, *args, **kwargs): return HttpResponse('Hello, World!') api/urls.py from django.urls import reverse, path from v1.views import MyView urlpatterns = [ path('/', MyView.as_view()), ] I get the following error when I run my script: The empty path didn't match any of these. Does this have to do with directory issues? -
AttributeError at /admin/ by Django 'WSGIRequest' object has no attribute 'user'
I cannot open the admin site, an error appears: 'WSGIRequest' object has no attribute 'user' Trying to enter in the site http://127.0.0.1:8000/admin/ I get this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.0.3 Python Version: 3.6.4 Installed Applications: ['polls', 'books', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: [] Traceback: File "C:\Users\joshu\Anaconda3\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\joshu\Anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\joshu\Anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\joshu\Anaconda3\lib\site-packages\django\contrib\admin\sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\joshu\Anaconda3\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\joshu\Anaconda3\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\joshu\Anaconda3\lib\site-packages\django\contrib\admin\sites.py" in inner 212. if not self.has_permission(request): File "C:\Users\joshu\Anaconda3\lib\site-packages\django\contrib\admin\sites.py" in has_permission 186. return request.user.is_active and request.user.is_staff Exception Type: AttributeError at /admin/ Exception Value: 'WSGIRequest' object has no attribute 'user' Error:'WSGIRequest' object has no attribute 'user' In my settings.py I have this: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.9.1. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import posixpath # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = … -
Issue with django-celery Not running at specific time
I am having issues with django-celery not running at the time specified, but it's always runnning every 1 minute. Below I have pasted the tasks.py, settings.py and celery.py. I have tested with djcelery and as well as celery. I am using celery-beat. celery.py (edited to only give specific and avoid confidential info.):- from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery.schedules import crontab from datetime import timedelta # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'netadc.settings') app = Celery('netadc') app.config_from_object(settings, namespace='CELERY') app.autodiscover_tasks() app = Celery('proj', broker='redis://', backend='redis://', include=['standalone.tasks']) CELERY_BEAT_SCHEDULE = { "runs-every-30-seconds": { "task": "tasks.cron_span", "schedule": 30.0, "args": () }, } if __name__ == '__main__': app.start() settings.py :- # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'ivpn', 'nsp', 'lib', 'ciscoaci', 'standalone', 'arista', 'spa', 'inet', #'django_countries', 'djcelery', #'debug_toolbar', 'celery', 'django_celery_beat', ) ROOT_URLCONF = 'netadc.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'ivpn.context_processors.vpnreq_info', 'django.template.context_processors.debug', 'django.template.context_processors.request', #'django.core.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'netadc.wsgi.application' # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' #TIME_ZONE = 'UTC' TIME_ZONE = 'America/Phoenix' USE_TZ = True ## Celery specific settings CELERY_BROKER_URL = 'redis://localhost:6379/0' … -
No search indexes bound via Haystack using Haystackbrowser
Has someone ever used this tool for all-text searching? I just installed this to my project and the installation seems working fine. But when I clicked the haystackbrowser button in my admin page, it returned to a webpage which said no search indexes bound via Haystack. I checked my project and I am sure that I created the search_index file. Could someone please help me? Thanks! -
User Registration and Login in Django
I have modified the default User and use this method to register a new User. class RegisterView(views.APIView): def post(self, request, **kwargs): location = Location.objects.get(id=kwargs.get('location_id')) serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() user.location = location user.save() subject = "Please Activate Your FootTheBall Account!" token = self._generate() link = HOST + PREFIX + str(user.id) + SUFFIX + token message = 'Please use the following link to activate your account.\n\n{}'.format(link) from_email = settings.EMAIL_HOST_USER to_list = [user.email, 'soumasish@foottheball.com'] send_mail(subject, message, from_email, to_list, fail_silently=True) Token.objects.create(user=user, token=token) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This works fine and the User is registered in the database. I have verified that. Now I call this method to login the User. class LoginView(views.APIView): def post(self, request): user = authenticate( email=request.data.get("email"), password=request.data.get("password") ) if not user: return Response({ 'status': 'Unauthorized', 'message': 'Email or password incorrect', }, status=status.HTTP_401_UNAUTHORIZED) login(request, user) return Response(UserSerializer(user).data) Despite providing the correct email and password it can't find the user and authenticate method fails. What am I doing wrong here? -
Filter on input select in python/django
I have two div's in my code. Left div has category names and right div has category names, title, and description. Right div values are coming from DB. I am basically trying to build a filter functionality in python/django when you click on a category on the left, right div shows the category selected with all the information. By default it shows all the categories and all details. Here is the code that I have: <div class="category_table"> { <form action="" method="post"> <input class="reset" type="button" onclick='UnSelectAll(this);' value="Reset" /> <ul class="vertical menu"> {% for category in Categories %} {% if 'Sr' in category.label_name %} <li> <input type="checkbox" name="checkbox1" id={{category.id}} > <span class="label star">{{category.label_name}}</span> <span class="category_name">{{category.name}}</span> </li> {% elif 'At' in category.label_name %} <li> <input type="checkbox" name="checkbox1" id="{{category.id}}"> <span class="label atm">{{category.label_name}}</span> <span class="category_name">{{category.name}}</span> </li> {% elif 'Inter' in category.label_name %} <li> <input type="checkbox" name="checkbox1" id="{{category.id}}"> <span class="label int">{{category.label_name}}</span> <span class="category_name">{{category.name}}</span> </li> {% elif 'TRN' in category.label_name %} <li> <input type="checkbox" name="checkbox1" id="{{category.id}}"> <span class="label rt">{{category.label_name}}</span> <span class="category_name">{{category.name}}</span> </li> {% elif 'OTP' in category.label_name %} <li> <input type="checkbox" name="checkbox1" id="{{category.id}}"> <span class="label obs">{{category.label_name}}</span> <span class="category_name">{{category.name}}</span> </li> {% elif 'FIE' in category.label_name %} <li> <input type="checkbox" name="checkbox1" id="{{category.id}}"> <span class="label fit">{{category.label_name}}</span> <span class="category_name">{{category.name}}</span> </li> {% … -
cloudtrax+Django HTTP authentication API
i'm creating a django HTTP server to accept and reject clients connecting to OM2p/cloudtrax , the Code that handle the authnetication : SECRET = 'cisco' def calculate_ra(request,response): CODE = response['CODE'] if not CODE : return '' old_ra = request.GET.get('ra') if not old_ra: return '' CODE = CODE.encode() old_ra = hex(int(old_ra,16)).encode() SECRETencoded = SECRET.encode() m = hashlib.md5(CODE + old_ra + SECRETencoded) return m.hexdigest().upper() <code snippit> elif request.GET.get('type') == 'login' : response_dict['CODE']='ACCEPT' response_dict.pop('BLOCKED_MSG') response_dict['RA'] = calculate_ra(request, response_dict) response_dict['SECONDS'] = '3600' response_dict['DOWNLOAD'] = '2000' response_dict['UPLOAD'] = '800' for item in response_dict : message_body += '"' + item + '" "' + response_dict[item] + '"\n' logger.info(message_body) response.write(content=message_body) return response but when client try to connect i get this error in debugs http_portal[25553]: Received answer with invalid RA -
django with python 3.4 import _mysql ImportError: /usr/local/lib/python3.4/dist-packages/_mysql.cpython-34m.so: undefined symbol: EVP_CIPHER_CTX_init
When I trying to run "pthon3 manage.py runserver" django. I found this error import _mysql ImportError: /usr/local/lib/python3.4/dist-packages/_mysql.cpython-34m.so: undefined symbol: EVP_CIPHER_CTX_init -
Http failure response for (unknown url) in FireFox with Django backend
I am developing a web application with a frontend written in Angular 4 and a backend in Django. Currently it is working perfectly in Chrome, but when I test it in FireFox I got several Http errors with the following message: Http failure response for (unknown url): 0 Unknown Error For this web application, after the user login, the frontend will try to make several API calls to the Django backend to get the data, then render the data in different places on the page. I used ngrx to handle all these API calls. The frontend looks something like the following: (There are 19 actions in total to make this Summary page work, I only included 3 actions in the example below) @Effect() refreshSummaryData = this.actions$ .ofType(DashboardActions.REFRESH_SUMMARY_DATA) .mergeMap(() => { return [ {type: ClientActions.FETCH_ALL_MAP_DATA}, {type: ClientActions.FETCH_MAP_STORE_DATA}, {type: ClientActions.FETCH_TOTAL_SALES_DATA}, ]; }); And the following is one of an example of the actions: @Effect() fetchAllMapData = this.actions$ .ofType(ClientActions.FETCH_ALL_MAP_DATA) .withLatestFrom(this.store.select(fromDashboard.getStateDashboard)) .switchMap(([action, state]) => { const params = {}; params['time_0'] = db.DatesManager.getyyyymmdd(state.startDate); params['time_1'] = db.DatesManager.getyyyymmdd(state.endDate); return db.ApiManager.requestRawData( this.httpClient, this.mapGeoDataUrl, params ); }) .map((data) => { return { type: ClientActions.GET_MAP_DATA_TABLE, payload: data }; }); I run Angular 4 with ng serve and Django backend with … -
Wsgi single thread configuration on a multi-threaded apache server
WSGIDaemonProcess <user> processes=5 threads=1 python-home=/path/to WSGIProcessGroup <user> WSGIRestrictEmbedded On WSGILazyInitialization On WSGIApplicationGroup %{GLOBAL} My application uses Gdal which is not thread safe. The documentation suggests using wsgi with threads=1. If the apache configuration is using a threaded mpm-worker will threads=1 guarantee thread safety? Apache settings: KeepAlive Off SetEnvIf X-Forwarded-SSL on HTTPS=1 ServerLimit 1 StartServers 1 MaxRequestWorkers 5 MinSpareThreads 1 MaxSpareThreads 3 ThreadsPerChild 5 -
How to have 2 different locale directories in django project?
I need to have two different locale directories in my django project. Because there are some translations in third-party apps like rest_auth which are not available for my language. We translated them manually in .po file, but the problem is whenever I run: python manage.py makemessages It scans the project and get rid of all the manually translated strings! So I want a directory for third party app translations (which django ignores it and doesn't update it), and another locale directory for my own stuff which get updated everytime I run makemessages. p.s: I already added the second locale folder to LOCALE_PATHS in settings. -
How can I keep the username after I logged out?
I'm using Django(2.03) to make my web application. To get the username in the template I used request.user and it works well while I'm logged in. After log out the username turns as AnonymousUser. How can I keep the username after I logged out? Note: I have also tried user.username and after log out the username vanished.