Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python manage.py runserver fails. ImportError: module not found
Unhandled exception in thread started by <function wrapper at 0x1046deb18> Traceback (most recent call last): File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/User/Desktop/App/App/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named profiles I keep getting this error No module named profiles and I'm not sure why. Profiles is defined in app.py: from __future__ import unicode_literals from django.apps import AppConfig class ProfilesConfig(AppConfig): name = 'profiles' and is called in urls.py from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.contrib import admin from profiles import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^one/', views.one, name='one'), url(r'^two/', views.two, name='two'), url(r'^three/', views.three, name='three'), url(r'^four/', views.four, name='four'), url(r'^five/', views.five, name='five'), ] Profiles is also added in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # greater consistency between gunicorn and `./manage.py runserver`. See: # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development 'whitenoise.runserver_nostatic', … -
Swagger in Django rest function based api does not show properly on ubuntu server
Checkout my website swagger: http://railer.com/swagger/ (screnshot https://imgur.com/TnTNExa) I cannot get my swagger to display properly on ubuntu django setup. And I am using function based API just like here https://github.com/m-haziq/django-rest-swagger-docs This is the outcome which doesnt display swagger properly - ubuntu 16.04 (in AWS) https://imgur.com/TnTNExa <-- this is the problem, how to fix this ? But on my development environment mac pc https://imgur.com/E1Zst0E <--- its good on PC (Mac) Here is my swagger schema. As you can see I have some logging: https://gitlab.com/firdausmah/railerdotcom/blob/master/railercomapp/swagger_schema.py Here are some logging: 2017-11-30 06:06:57,367 DEBUG xxxx home hello 2017-11-30 06:07:25,131 DEBUG get(self, request) 2017-11-30 06:07:25,132 DEBUG Check and load if the function has __doc__ 2017-11-30 06:07:25,132 DEBUG swagger try yaml_doc 2017-11-30 06:07:25,134 DEBUG if yaml_doc My Django/NGINX/Ubuntu setup is based on this: https://jee-appy.blogspot.my/2017/01/deply-django-with-nginx.html Feel free to look through my code, https://gitlab.com/firdausmah/railerdotcom/tree/master what could be the problem with swagger? On development its working. There is nothing different how I setup development & production. On production its using nginx, gunicorn, supervisor. on PC its running on python manage.py runserver. -
ajax call in django with fild detect with js
i have a model class name(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, default='') rfc = models.CharField(max_length=255) I have a view: def get(request): val=request.GET.get("username") print val response=name.objects.filter(story='{}'.format(val)) print response[0].rfc return HttpResponse(response) I have model form: class nameForm(ModelForm): class Meta: model = Manifest fields = "__all__" In template user have to drop down some choices in the first three fields name, project,story . Now i want to detect what user has droped down for the third field 'story'. So that i can make a ajax call with that value just user drop down on third field , to the function 'get' . How can i do it with ajax and js . Kindly help -
serving Django app by NGINX and uWSGI
My project "mysite" is all about creating a pdf file from a HTML document. Now i am facing problem while creating pdf file. Nginx working properly. Project is also loading properly in webbrowsers. My assumption is either uwsgi or nginx conf file is not proper. If its so please help me with some detailed answer. My project is working fine with django server. My uWSGI file and NGINX conf as shown below: server { listen 80; server_name mysite-uat.skysoft.com; charset utf-8; #forward all the request to HTTPS proxy_set_header X-Forwarded-Proto $scheme; if ( $http_x_forwarded_proto != 'https' ) { return 301 https://$host$request_uri; } location / { include uwsgi_params; uwsgi_read_timeout 300; include /var/www/html/mysite/uwsgi_params; uwsgi_pass unix:///tmp/mysite.sock; } access_log /var/log/nginx/mysite-access.log ; error_log /var/log/nginx/mysite-error.log; # Django media location /media { # your Django project's media files - amend as required alias /var/www/html/mysite/media; } location /static { # your Django project's static files - amend as required alias /var/www/html/mysite/static; } # static code has to reside in /home/project/project/static error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } My UWSGI file : [uwsgi] # path to where you put your … -
Django Pagination object is not persistent(Error: object of type 'NoneType' has no len())
# Views from gitdiff import operations from django.shortcuts import render, HttpResponse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger class Dashboard(operations.Operations): def render_dashboard(self, request): l_filters = [] # Adds configured filters from the config to a sorted list. for k in self.filters: l_filters.extend(k) l_filters.sort() repos = None # Condition to check if the filter is selected in GUI if "selected-filter" in request.POST: selected_filter = request.POST["selected-filter"] repos = selected_filter.split(" to ") # Removes the selected filter and adds in the end of list. l_filters.remove(selected_filter) # if selected, execute filterTool(.pl) self.get_filter_result(selected_filter=selected_filter, dev_repo = repos[0]) else: selected_filter = None # Paginator try: page = request.GET.get('page', 1) except ValueError: page = 1 print("Page is : {}".format(page)) # Retrieving end result from the DB db_res = self.get_dashboard_data(selected_filter) paginator = Paginator(db_res, 10) res = None try: res = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. res = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. res = paginator.page(paginator.num_pages) return render(request, 'dashboard.html', {'end_res': res, 'filters': l_filters, 'selected_value': selected_filter, 'repos': repos}) # In Template: <div class="pagination"> <span class="step-links"> {% if end_res.has_previous %} <a href="?page={{ end_res.previous_page_number }}" class="btn btn-xs btn-default">Previous </a> {% endif %} <span class="current">Page … -
How to link to other websites in my django?
I want to link my buttons to diffrent websites in my django website. <div class="container-fluid" style='margin-left:15px'> <p><a href="#" target="blank">Contact</a> | <a href="#" target="blank">LinkedIn</a> | <a href="#" target="blank">Twitter</a> | <a href="#" target="blank">Google+</a></p> </div> The above href only holds for the urls.py or only to the local pages of the project. -
Get User who owner a Content Object in Django
Helllo everyone, I have no solution to Get User who owner a Content Object in Django. So I post for your guys help! I'm building 2 models: Reaction and Notification. If user React, Notification will auto be created a object. This is my code: Model Reaction: class Reaction(models.Model): user = models.ForeignKey(User) react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='NO') timestamp = models.DateTimeField(auto_now_add=True, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') def save(self, force_insert=False, force_update=False, *args, **kwargs): Notification(from_user = self.user, to_user = ???, notification_type = Notification.LIKED, target_content_type = self.content_type, target_object_id = self.object_id).save() super(Reaction, self).save(*args, **kwargs) Models Notification class Notification(models.Model): from_user = models.ForeignKey(User, related_name='+') to_user = models.ForeignKey(User, related_name='+') date = models.DateTimeField(auto_now_add=True, null=True) is_read = models.BooleanField(default=False) target_content_type = models.ForeignKey(ContentType, related_name='notify_target', blank=True, null=True) target_object_id = models.PositiveIntegerField(null=True) target = GenericForeignKey('target_content_type', 'target_object_id') As you saw, I have problem with get to_user fields. This field I want to get User who owner a Content Object in Django Example: Post, Comment, ... Please help me with this case! -
Why is my Django template not loading?
I have the following code which seeks to pull a number "counter" out of a DB, add a value ("+1") to it, save the new "counter" value, wait for a specified amount of time, and then start again from the beginning. This same function would be called via a view on Django, so it is also responsible for generating the template as well. According to the development server, the function IS performing the simple arithmetic and saving the new value to the DB. As I can see the value being updated every time I refresh the Django-Admin. However, it fails to load the template. Specifically, the page stays loading indefinitely, while the calculations happen. Sorry if the code isn't perfect, I'm new to everything ever. Also, please note that I have previously tested the entire ecosystem with a much simpler index function (generates simple HTML) and the template indeed generates. So I'm assuming that the problem must come from this code specifically. Views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import Context, loader from home.models import DeathNum import datetime import time def index(request): while True: counter = DeathNum.objects.get(pk=1) counter.deaths += 1 counter.save() print('Added @ %s ' … -
Celery Beat unable to find database models (django.db.utils.OperationalError)
I have to add few periodic tasks. I'm using Celery - Redis in Django platform. When I execute the method from shell_plus all is well . However Celery Beat is unable to find the database instance properly. Celery version = 4.1.0. I had previously installed django-celery-beats etc Database = MySQL Where am i wrong. Thanks in advance. Celery Command (venv)$:/data/project/(sesh/dev)$ celery -A freightquotes worker -B -E -l INFO --autoscale=2,1 settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_BROKER_TRANSPORT = 'redis' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 604800} CELERY_RESULT_BACKEND = BROKER_URL CELERY_TASK_RESULT_EXPIRES = datetime.timedelta(days=1) # Take note of the CleanUp task in middleware/tasks.py CELERY_MAX_CACHED_RESULTS = 1000 CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERY_TRACK_STARTED = True CELERY_SEND_EVENTS = True CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml'] REDIS_CONNECT_RETRY = True REDIS_DB = 0 BROKER_POOL_LIMIT = 2 CELERYD_CONCURRENCY = 1 CELERYD_TASK_TIME_LIMIT = 600 CELERY_BEAT_SCHEDULE = { 'test': { 'task': 'loads.tasks.test', 'schedule': crontab(minute='*/1'), }, init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.base') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) loads/tasks.py @task() def test(): x = [i.id for i in Load.objects.all()] print (x) Error [2017-11-30 03:52:00,032: ERROR/ForkPoolWorker-2] Task loads.tasks.test[0020e4ae-5e52-49d8-863f-e51c2acfd7a7] raised unexpected: OperationalError('no such table: loads_load',) Traceback (most recent call last): File "/data/project/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line … -
`send_mail` method send email, the receive address did not received
I use the send_mail to send email to a list of email addresses, but it seems did not send to the addresses. My key code are bellow: from django.core.mail import send_mail result = send_mail(subject, message, from_email, to_email_list, fail_silently=False) print(result) # there prints `1` My email settings in settings.py is bellow: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.qq.com' # QQ:smtp.qq.com 163:smtp.163.com EMAIL_PORT = 465 EMAIL_HOST_USER = 'qiyunserveremail@qq.com' EMAIL_HOST_PASSWORD = 'qiyunserver_password' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER and the traceback is bellow: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Subject: =?utf-8?b?5Li76aKY?= From: qiyunserveremail@qq.com To: lxt123@126.com Date: Thu, 30 Nov 2017 03:02:26 -0000 Message-ID: <20171130030226.15096.58930@aircraftdemacbook-pro.local> 内容 ------------------------------------------------------------------------------- 1 # this is the print(result) EDIT And I login my EMAIL_HOST_USER email, in the sent email section, there is no email there. -
Double underscore method for ordering the list returned by the view based on a field in another model not working
I'm trying to order the list the view returns based on a field in another model. I read the documentation over here and it says I could do that by using the model's name followed by double underscore followed by the field in the model. But that for some reason is not working. I tried another method, as mentioned below. View class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' ordering = ['choice'] Model class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Meta: ordering = ['-votes'] The above method works but the below one does not, can someone kindly point me why. View class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def get_queryset(self): """Return the choices in the order of votes""" return Question.objects.order_by('-choice__votes') Model class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Even tried replacing def get_queryset() with ordering = ['-choice__votes'] didn't work either. -
Not able to get url parameter while unit testing Django's rest api using APIRequestFactory
I have created a rest api using Django's rest_framework. It's created using class based view. views.py import logging from rest_framework.views import APIView from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication from rest_framework.response import Response from handlers.product import get_data log = logging.getLogger(__name__) class ProductView(APIView): authentication_classes = (TokenAuthentication, BasicAuthentication, SessionAuthentication) def get(self, request, **kwargs): try: product_id = kwargs['product_id'] response = get_data(product_id) return Response(response) except KeyError as key: log.exception(key) return Response({'error_msg': '{} is required'.format(key)}, status=400) urls.py url(r'^product/(?P<product_id>[0-9]+)/data/$', ProductView.as_view(), name='product'), And this is what I have tried, import pytest from django.contrib.auth.models import User from mixer.backend.django import mixer from rest_framework.authtoken.models import Token from rest_framework.test import APIRequestFactory from views import * pytestmark = pytest.mark.django_db @pytest.fixture() def token(): user = mixer.blend(User) return Token.objects.create(user=user) class TestProductView: def test_get_data(self, token): factory = APIRequestFactory() request = factory.get('/product/100230/data/', HTTP_AUTHORIZATION='Token {}'.format(token)) response = ProductView.as_view()(request) assert response.status_code == 200 My test fails because I get an exception, KeyError: 'product_id' But when I run my app and request the api from browser it takes the product_id from the url. Please note that I really have to use kwargs in get api method because later I want to make get_data generic and pass all the url params and query params to it. -
odd Django behavior with multiple forms
I have a Django app with 1 views.py and 1 forms.py file, however within these they had distinct forms. The forms sometime call functions of other scripts which log data using logging module. Recently I've noticed that script 1 is writing data to script 2's log instead of its own. The code is solid and this wasn't an issue before. My only theory is the same person is submitting 2 different forms using multiple tabs/same session in the same browser. How can I prevent this? or at least prevent the data cross over -
Multiple validators for Django 1.11 Model CharField
Does anyone know if it is possible to apply multiple validators to a Django 1.11 Model CharField? I am trying to enforce formatting of the field as either: "Use format XX XXXX XXXX" or "Use format XXXX XXX XXX" prefphone = models.CharField(max_length=255,null=True,blank=True,validators=[RegexValidator(r'^[0-9]{2} [0-9]{4} [0-9]{4}$', "Use format XX XXXX XXXX"),RegexValidator(r'^[0-9]{4} [0-9]{3} [0-9]{3}$', "Use format XXXX XXX XXX")]) The first validation is failing and the second validation is not tested. If there are alternative methods to achieve my outcome I would be grateful to hear them. Thanks! -
handle two difference action, add and save
I have a form where user can add multiple items which will be shown in table and then if user hits the save button, all those items will be saved to database but I have no idea on how should i do this. Can anyone give me an idea, please? This is the form I have to process In screenshot, there is one add button which will add in the below table and then there is save button which will post to the database. I have only created a model and forms for now class OpeningStock(models.Model): office = models.ForeignKey(OfficeSetup, blank=True, null=True, on_delete=models.CASCADE) miti = models.DateTimeField(null=True) item_group = models.ForeignKey(ItemGroup, blank=True, null=True) item = models.ForeignKey(Item, blank=True, null=True) department = models.ForeignKey(DepartmentSetup, blank=True, null=True) employee = models.ForeignKey(Employee, blank=True, null=True) quantity = models.PositiveIntegerField(default=0) value = models.DecimalField(default=0.0, max_digits=100, decimal_places=2) specification = models.CharField(blank=True, null=True, max_length=600) remarks = models.TextField(blank=True, null=True) def stock(request): form = StockForm(request.POST or None) if request.method == "POST" and form.is_valid(): office_instance = OfficeSetup.objects.get(user=request.user) new_form = form.save(commit=False) new_form.office = office_instance new_form.save() messages.success(request, 'Thank you') return redirect('stock') messages.warning(request, "Correct the errors below") stocks = OpeningStock.objects.all() context = { "form": form, "stocks": stocks } return render(request, 'dashboard/stocks/stock.html', context) {% block content %} <div class="right_col" role="main"> <h1 class="text-center">Stock</h1> <div … -
Deleting 'models.py' from Django app
Inside a project I'm implementing using Django framework, I have two applications: Application responsible for REST API, containing production models.py file. Application responsible for Web client, that uses REST API's models. Both of them contain vast static files and hierarchy of additional source code, that is why it came to my mind to split this responsibilities into two apps, rather than different views.py and urls.py files inside one application. Because application responsible for Web relies entirely on REST API's models is it a good practice to delete models.py file from this application entirely? -
django 1.11 app can't find style.css in static/app/style.css dir
my app dir: my base.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'sns/style.css' %}" /> style.css content: li a { color: green; } for some reason, I get a 404 when it tries to load style.css page source: Not sure what im missing? -
Making a queryset on the same attribute name across multiple models
I have a few models that I want to create a queryset on. The problem is that I have to keep specifying every time what model I want to search for that set attribute every time. Example: I have two models called computer and one called cord. Both share the attribute barcode. (Which Barcode is a foreign key to the Barcode table.) I want to be able to write something like. Computer_Cord.objects.filter(Q(barcode__icontains=barcode)) Instead of Computer.objects.filter(Q(barcode__icontains=barcode)) Really sorry if this already posted out in the stack overflow atmosphere but I am either having trouble finding it or asking the question. Any sort of help would be fantastic. -
how give a default value at username field of User class in python
sorry my english is not very god. That is my problem. i want give by default at username field the value of email field this is my model from django.db import models from django.contrib.auth.models import User class Member(User): class Meta: verbose_name_plural = 'Member' my serializer file thanks -
Cannot run unit-tests with pytest
I have an app with Python 2.7, Django 1.9 and pytest 3.2.5. I try to run unit-tests locally and I am getting that error: AssertionError: Query fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping. I run tests in common way, like: python pytest app_name/tests/test_tasks.py What can be wrong? -
How do to Turn QueryDict into Object?
How do to Turn QueryDict into Object? The result of POST QueryDict is not assembling a json object. You would need to convert this data to better handle. Thank you very much. html <input name="pesquisa[1]item[]"/> <input name="pesquisa[2]item[]"/> view def post(self, request): data = json.dumps(request.POST) return HttpResponse(data, content_type='application/json') Result { "csrfmiddlewaretoken": "txecn4TDkoYtFeS2a9LEKzI4X8MEUgUmgrGFDvOf54oJpV10mjW08aDAjLFgRzO0", "unidade_nome": "--", "pesquisa[1][item]": "", "pesquisa[2][item]": "" } Expected Result { "csrfmiddlewaretoken": "txecn4TDkoYtFeS2a9LEKzI4X8MEUgUmgrGFDvOf54oJpV10mjW08aDAjLFgRzO0", "unidade_nome": "--", { "pesquisa":{[ "item": "", "item": "", ]} } -
Django - Overriding labels is not working with forms ChoiceField
I found a workaround to this problem, but I'm asking it anyways because it was quite odd. I have a model field called agent_title under model Agent. I want to display it on my form as just Title. I need to display the field with ChoiceField. However when I modify the field to be a ChoiceField, the label override stops working. Any reasons why? This works... class AgentInfoForm(forms.ModelForm): class Meta: model = Agent labels = { 'agent_title': 'Title', } But this doesn't class AgentInfoForm(forms.ModelForm): agent_title = forms.ChoiceField(choices=AGENT_TITLE) class Meta: model = Agent labels = { 'agent_title': 'Title', } -
Model if logic not working correctly
Why won't my logic work to verify if a field in my custom user model named formattedusername is equal to a field my QvDatareducecfo model using the def cfo defined below. class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_cfo = models.BooleanField(default=False) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); def cfo(self): cfo = self.QvDatareducecfo.cfo_ntname if self.formattedusername == cfo: self.is_cfo = 1 else: self.is_cfo = 0 print (is_cfo) super(User, self).save(is_cfo) # REQUIRED_FIELDS = "username" def __str__(self): return "@{}".format(self.username) I defined the cfo_ntame field as a OneToOneField in the QvDatareducecfo model. I don't receive an error message on my logic and it looks like return is_cfo prints a 0, but if i update the cfo table to a 1 and re-login it doesn't update to a 0 and the user id i'm using isn't listed in the cfo table. -
Django : how to limit the open app?
I have several apps on my django project : DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'django.contrib.gis.db', ] LOCAL_APPS = [ #'cycliste' , #'logger' , 'position' , 'reseau' , 'station' , #'trajet' , #'useful_functions' , 'velo' , #'ville' , ] INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS My url file is : urlpatterns = [ url(r'^', include('reseau.urls')), url(r'^', include('station.urls')), url(r'^', include('velo.urls')), url(r'^', include('position.urls')), ] Now, each app is a rest server. I want to start a different app on each of the servers of my cluster. I see 2 ways to do that : I comment the LOCAL_APPS I don't want on the server I change the urls file, removing the url I don't want to accept The issue is that I have 6 or 7 apps. For each one of them I just want to be able to start a "station" server, or a "logger" server. So I need to dynamically change which app is included in LOCAL_APPS at runtime. I tried to do it through a --settings command, but had no luck. I tried to do it through a specific management.command but without succcess... Finally I think it should be simpler. Maybe a test on the settings … -
Is it possible to access userID of the current LoggedIn user in django.
if user in users_in_group: from django.contrib.auth.models import Group users_in_group = Group.objects.get(name="group name").user_set.all()