Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with Filter code and using switch function call within class method, Got AttributeError when attempting to get a value for field
Got AttributeError when attempting to get a value for field. Kindly help resolve. Issue is withing the filters code as plain serialization is working well views.py class Job_Application_StateList(generics.ListCreateAPIView): serializer_class = Job_Application_StateSerializer def get_queryset(self): queryset = Job_Application_State.objects.all() request_queries = self.request.query_params if(request_queries): user = self.request.user queryset = Job_Application_State.objects.filter(user = user) status = request_queries.get('status', None) queryset = self.statusFilter(queryset, status) return queryset def statusFilter( self, queryset, args ): switcher = { 'saved': queryset.filter(saved = True), 'applied':queryset.filter(applied = True), 'shortlisted':queryset.filter(shortlisted = True), } return switcher.get("Invalid Status: ", args) models.py class Job_Application_State(models.Model): job = models.ForeignKey(Job, on_delete=models.PROTECT, related_name='applicant_status') user = models.ForeignKey(User, null=True, on_delete=models.PROTECT, related_name='application_status') saved = models.BooleanField() applied = models.BooleanField() shortlisted = models.BooleanField() Error: Got AttributeError when attempting to get a value for field saved on serializer Job_Application_StateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'saved'. -
Populating models inner classes from the same table
I had a database composed by: Table1: columns: a1, b1, c1 Table2: columns: a2, b2 And for the models I had: class Table1(models.Model): a1 = models.IntegerField(id) b1 = models.CharField() c1 = models.ForeignKey(Table2) class Table2(models.Model): a2 = models.IntegerField(id) b2 = models.CharField() So to access instances of Table2 all my system worked around this: table1.table2.b2 Bu that database has been reestructured to: Table1: columns: a1, b1, a2, b2 Hence my model became: class Table1(models.Model): a1 = models.IntegerField(id) b1 = models.CharField() table2_a2 = models.IntegerField(id) table2_b2 = models.CharField() So now in order to access the old value b2 I need to: table1.table2_b2 Is it possible to do something like to following model? class Table1(models.Model): class Table2(models.Model): a2 = models.IntegerField(id) b2 = models.CharField() a1 = models.IntegerField(id) b1 = models.CharField() table2 = Table2() table2.a2 = models.IntegerField(id) table2.b2 = models.CharField() -
Django dependencies reference nonexistent parent node when making model changes
I have a Django project deployed on aws server.I made some changes in the models on my machine and pushed the changed by Github and on the server, I pulled the changes by git command but the app isn't working so when I tried running python manage.py makemigrations it returns errors like Django: dependencies reference nonexistent parent node I tried removing the file mentioned in the error and tried removing the .pyc files but still the same problem so what can I do here and how should I do this in the future to avoid these problems. here's the traceback Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 89, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 273, in build_graph raise exc File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 247, in build_graph self.graph.validate_consistency() File "/home/ubuntu/Eyelizer/eyenv/lib/python3.6/site-packages/django/db/migrations/graph.py", line 243, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] … -
Load result from requests.get into django template (tableau)?
I've got a super tiny (one view) django application that loads a view from a tableau server. I've got it working with the trust app method of connection and if I just put the URL into a browser it loads up okay without issue. When I try to render that same page inside of a django template however - django tries to load all the resources as if they existed locally (which doesn't work). The view looks like this: def index(request): url = os.environ.get("tableau_HOST") username = request.user.username ticket = get_tableau_ticket(url, username) if ticket: data = requests.get(url+ticket+'/views/SIPPlan/DashboardView', data={'username': username}) print(data.text) else: # Handle the error - not implemented yet r = ticket return render( request, "tableau/index.html", { "tableau_data": data.text, }, ) Inside my template it looks like this: {% extends "myapp/base_template.html" %} {% load static %} {% block content %} {% autoescape off %} {{ tableau_data }} {% endautoescape %} {% endblock %} When I load the view - I see it trying to load the resources from my local machine (which it shouldn't, they exist on the tableau server). [09/Aug/2019 08:26:28] "GET /vizql/v_201921906211547/javascripts/formatters-and-parsers.en_US.js HTTP/1.1" 404 3610 Not Found: /vizql/v_201921906211547/javascripts/vqlweb.js 2019-08-09 08:26:28,639 - django.request WARNING Not Found: /vizql/v_201921906211547/javascripts/vqlweb.js [09/Aug/2019 08:26:28] "GET … -
How to save the number of registered users in mongodb?
I have a problem and I am looking for a solution. I want to save the number of users registered in mongodb. For example, in django, the admin page has the number of registered users, and all other data is saved there. I want it to be saved in mongodb database instead of showing it on admin page, because my other data is also saved in mongodb. How do I do this? Should I make separate a class in models.py or something else. -
How to list the id with getlist method in Django checkbox
html file Here I list the client and Process in the input tag And select the and submit {% for client in form %} <tr> <td> <input type="checkbox" name="cname[]" value="{{ client.id }}"> {{ client.Name }} </td> <td> {% for process in client.clients %} <input type="checkbox" name="process[]" value="{{ process.id }}"> {{ process.process }}<br /> {% endfor %} </td> </tr> {% endfor %} views file The below code is get the selected in checkbox. The getlist method return nothing if request.method == "POST": cname = request.POST.getlist('cname[]') print("cname", cname) process = request.POST.getlist('process[]') print("process", process) -
Implementation of allauth FB auth, "breaks" others urls in Django?
I'm following this answer, but when I add, these lines to settings.py, cannot load localhost:8000/admin/login anymore: 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', Error: Site matching query does not exist. Same error for localhost:8000/users/login but when hit localhost:8000/users urls are there: -
How do i create views.py with Django queryset filter to compare Specific value of two different tables in django?
JOB_TYPE = ( ('1', "Full time"), ('2', "Part time"), ('3', "Internship"), ) class Job(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) description = models.TextField() location = models.CharField(max_length=150) type = models.CharField(choices=JOB_TYPE, max_length=10) category = models.CharField(max_length=100) last_date = models.DateTimeField() skillRequired1 = models.CharField(max_length=100, default="") skillRequired2 = models.CharField(max_length=100, blank=True, null=True) work_experience = models.IntegerField(default=0) company_name = models.CharField(max_length=100) company_description = models.CharField(max_length=300) website = models.CharField(max_length=100, default="") created_at = models.DateTimeField(default=timezone.now) filled = models.BooleanField(default=False) def __str__(self): return self.title class EmployeeProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) location = models.CharField(max_length=150) type = models.CharField(choices=JOB_TYPE, max_length=10) work_experience = models.IntegerField(default=0) category = models.CharField(max_length=100) emailContact = models.CharField(max_length=100, default="") skill1 = models.CharField(max_length=100) skill2 = models.CharField(max_length=100) skill3 = models.CharField(max_length=100, blank=True) skill4 = models.CharField(max_length=100, blank=True) about_me = models.TextField() images = models.ImageField(upload_to='employeeProfiles', default='default.jpg') def __str__(self): return f'{self.user.first_name} Profile' i have created two database tables 'Job' and other is "employeeProfile".. I want to Compare and match 'title' of both and want to show only those 'title' which is present in Job but not in 'employeeProfile'.These two tables are in two different Models. -
Openstack horizon dashboard internal server error 500
I have installed openstack horizon service. I am facing internal server error 500. Error detail Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache/2.4.18 (Ubuntu) Server at 10.0.0.10 Port 80 Log File /etc/var/apache2/error log [Fri Aug 09 18:36:29.429558 2019] [wsgi:error] [pid 6300:tid 139822948239104] [remote 10.0.0.10:0] mod_wsgi (pid=6300): Target WSGI script '/usr/share/openstack-dashboard/openstack_dashboard/wsgi/django.wsgi' cannot be loaded as Python module. [Fri Aug 09 18:36:29.429618 2019] [wsgi:error] [pid 6300:tid 139822948239104] [remote 10.0.0.10:0] mod_wsgi (pid=6300): Exception occurred processing WSGI script '/usr/share/openstack-dashboard/openstack_dashboard/wsgi/django.wsgi'. [Fri Aug 09 18:36:29.429645 2019] [wsgi:error] [pid 6300:tid 139822948239104] [remote 10.0.0.10:0] Traceback (most recent call last): [Fri Aug 09 18:36:29.429722 2019] [wsgi:error] [pid 6300:tid 139822948239104] [remote 10.0.0.10:0] File "/usr/share/openstack-dashboard/openstack_dashboard/wsgi/django.wsgi", line 16, in [Fri Aug 09 18:36:29.429811 2019] [wsgi:error] [pid 6300:tid 139822948239104] [remote 10.0.0.10:0] application = get_wsgi_application() [Fri Aug 09 18:36:29.429859 2019] [wsgi:error] [pid 6300:tid 139822948239104] [remote 10.0.0.10:0] File "/usr/lib/python2.7/dist-packages/django/core/wsgi.py", line 14, in get_wsgi_application [Fri Aug 09 18:36:29.429905 2019] [wsgi:error] [pid 6300:tid 139822948239104] [remote 10.0.0.10:0] django.setup() [Fri … -
DRF update from list instead of post
I'm not really sure how to word this question which is probably why I can't find an answer. Using rest_framework.renderers.BrowsableAPIRenderer when viewing a list the HTML form at the bottom of the page is for a POST request. I'd like to be able to map it to a PUT request. Below is my urls.py - do i need to override routers.SimpleRouter? router = routers.SimpleRouter() router.register(r'', views.OrderAPIViewSet, base_name='order') merge_router = routers.SimpleRouter() merge_router.register(r'', views.OrderMergeAPIViewSet, base_name='merge') app_name = 'order' urlpatterns = [ path('', include(router.urls)), path('<int:pk>/merge/', include(merge_router.urls)), ] -
How can I create object day by day in Django?
I have just begin the Django web framework and I am trying to make internship diary application. I want to create an model which has name as "RecordedWorkDay" automatically for each intern user. But these object should be created by program for each day. What I mean is if today is Monday, tomorrow new object should be created by program. #That is my user class which extends from AbstractUser class CustomizedUser(AbstractUser): authory_choices = ( ("İntern", "İntern"), ("Manager", "Manager"), ) authory = models.CharField(choices=authory_choices, default="İntern", max_length=10) school = models.CharField(max_length=200, default='') description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') def is_intern(self): if self.authory == "İntern": return True return False def is_manager(self): if self.authory == "Manager": return True return False #This class should save diary text for each day class RecordedWorkDays(models.Model): # TextField that holds users' working day records record = models.TextField() #Corresponding intern that owns this day object assignedIntern = models.ForeignKey(CustomizedUser, related_name="assigned", null=True, blank=True, on_delete=models.SET_NULL) creation_date = models.DateTimeField(default=datetime.now) -
Email the contents of saved record in django
How can I retrieve content of the object and send as an email notification ''' django ''' def submit_outages(request): upload_data = upload_data_form(request.POST) print(upload_data) request.session['info'] = {} data_to_submit = request.session['info'] if not data_to_submit: turb = unit_details.objects.filter( unit_name=request.POST['turbine']).first() print(type(turb)) # if upload_data.is_valid(): start_timestamp = request.POST['start_timestamp'] end_timestamp = request.POST['end_timestamp'] availability_type = request.POST['availability_type'] capacity_kw = request.POST['capacity_kw'] capacity_perc = (request.POST['capacity_perc']) outage_info = planned_outages( start_timestamp=start_timestamp, end_timestamp=end_timestamp, unit_id=turb, availability_type=availability_type, capacity_kw=capacity_kw ) outage_info.save() # send_mail(subject, message, from_email, to_list, fail_silently =True) subject = 'Outage Submitted' messages= "This should contain form data and unit_name from unit_details table" from_email = settings.EMAIL_HOST_USER to_list = [''] send_mail(subject,messages,from_email,to_list,fail_silently=True) print("*** upload_data ***") return redirect('get_outages') Subject - Outage Submitted Message - unit_name; start_timestamp ; end_timestamp ;capacity_kw ; -
TypeError: 'str' object is not a mapping in django urls template
I have an issues with urls in django which it was not there before in all other projects that i have done and suddenly in new django project this problem pops up. url.py urlpatterns = [ path('',views.Home.as_view(),name='home'), ] Html template <a class="nav-link" href="{% url 'home' %}"> console error: {**defaults, **url_pattern.default_kwargs}, TypeError: 'str' object is not a mapping in debug page: TypeError at / 'str' object is not a mapping Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1 Exception Type: TypeError Exception Value: 'str' object is not a mapping Games -
in django admin model listing, Display 'Yes/No' for method's return value
I am learning django admin on dJango project site, and I want to display 'Yes/No' instead of True/False icons in admin listing page. These values come from a method defined in AdminModel. There is a method in a model class that returns True/False. in django there is an attribute "boolean", when assigned "True", it show red & green icons for column on admin listing page. **class** Question(models.Model): pub_date = models.DateTimeField('date published') def was_published_recently(self): now = timezone.now() **return** now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.boolean = True -
how to use multi select in django forms
I just want to use multiselect dropdown using django forms I have tried but simple multichecklist is comming class Hotel(models.Model): # COUNTRY =( # ('INDIA','INDIA'), # ('sri','sri'), # ('pak','pak') # ) hotel_Main_Img = models.ImageField(upload_to='images/') # geo = MultiSelectField(choices = COUNTRY,null =True,blank=True) geo = models.ForeignKey(Geo, on_delete=models.CASCADE, null=True, blank=True) genre = models.ForeignKey(Genre,on_delete=models.CASCADE,null=True, blank=True) free_tag = models.ForeignKey(FreeTag,on_delete=models.CASCADE,null=True, blank=True) default = models.ForeignKey(Default,on_delete=models.CASCADE,null=True, blank=True) for forms.py class HotelForm(forms.ModelForm): geo = forms.ModelMultipleChoiceField(queryset=Hotel.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Hotel fields = '__all__' -
Nginx 500 (internal server) error Django and Gunicron?
I have a Django app deployed on an ubuntu machine with Nginx and gunicorn. The app was working until I made some changes in the code and pushed the changes to Github and pulled it on the server and now it returns this error. the code works on my machine but on the server doesn't work, I tried rechecking the libraries and installing them and restarting both nginx and gunicron. I even checked the logs and errors of nginx and gunicorn but nothing suspicious. The changes I made was adding a python file to process some user input if this piece of information could help. -
how to resolve mysql connection errors with django
File "/home/suainul/dev/Env/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/suainul/dev/Env/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in class AbstractBaseUser(models.Model): File "/home/suainul/dev/Env/lib/python3.7/site-packages/django/db/models/base.py", line 117, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/suainul/dev/Env/lib/python3.7/site-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "/home/suainul/dev/Env/lib/python3.7/site-packages/django/db/models/options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home/suainul/dev/Env/lib/python3.7/site-packages/django/db/init.py", line 28, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "/home/suainul/dev/Env/lib/python3.7/site-packages/django/db/utils.py", line 201, in getitem backend = load_backend(db['ENGINE']) File "/home/suainul/dev/Env/lib/python3.7/site-packages/django/db/utils.py", line 125, in load_backend ) from e_user django.core.exceptions.ImproperlyConfigured: 'django.db.backends.mysql' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'oracle', 'postgresql', 'sqlite3' -
Views for forms.py for different checkboxes in the same model
I am creating a website where a user can create a project and answer some questions regarding this project. I want the user to be able to select some possible answers from two different checkboxes forms. models.py class Initialquestion(models.Model): INITIAL_ONE_CHOICES = ( ('Diagnostic', 'Diagnostic'), ('Therapeutic','Therapeutic'), ('Population health','Population health'), ('Care-based','Care-based'), ('Triage','Triage'), ('Self-care','Self-care'), ('Health promotion','Health promotion'), ('Remote Monitoring','Remote Monitoring'), ('Remote Consultation','Remote Consultation'), ('Other','Other'), ) INITIAL_TWO_CHOICES = ( ('Primary Care', 'Primary Care'), ('Secondary Care','Secondary Care'), ('Tertiary Care','Tertiary Careh'), ('Individual Care of Self','Individual Care of Self'), ('Triage','Triage'), ('For the purposes of population screening','For the purposes of population screening'), ('Other','Other'), ) initial_one = MultiSelectField(choices=INITIAL_ONE_CHOICES) initial_two = MultiSelectField(choices=INITIAL_TWO_CHOICES) developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project = models.OneToOneField(Project, on_delete=models.CASCADE) forms.py from django import forms class InitialquestionForm(forms.ModelForm): INITIAL_ONE_CHOICES = ( ('Diagnostic', 'Diagnostic'), ('Therapeutic','Therapeutic'), ('Population health','Population health'), ('Care-based','Care-based'), ('Triage','Triage'), ('Self-care','Self-care'), ('Health promotion','Health promotion'), ('Remote Monitoring','Remote Monitoring'), ('Remote Consultation','Remote Consultation'), ('Other','Other'), ) INITIAL_TWO_CHOICES = ( ('Primary Care', 'Primary Care'), ('Secondary Care','Secondary Care'), ('Tertiary Care','Tertiary Careh'), ('Individual Care of Self','Individual Care of Self'), ('Triage','Triage'), ('For the purposes of population screening','For the purposes of population screening'), ('Other','Other'), ) initial_one = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=INITIAL_ONE_CHOICES) initial_two = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=INITIAL_TWO_CHOICES) developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project = models.OneToOneField(Project, on_delete=models.CASCADE) class Meta: model = Initialquestion I am struggling to create … -
S3 versioning with django-storages
I use django-storages in my app, and I want to use S3 versioning just out of the box. I mean, I want to store and retrieve different versions of the same file without implementing any additional mechanism. By reading the docs, I understand that: Retrieving an object is as easy as adding a version=XX parameter to the GET request. Uploading an object is handled by S3 itself. You just need to configure versioning in your bucket But, going to the code. If I have this: from django.db import models from django_s3_storage.storage import S3Storage storage = S3Storage(aws_s3_bucket_name='test_bucket') class Document(models.Model): name = models.CharField(max_length=255) s3_file = models.FileField(storage=storage) How can I get one specific version of a Document? Something like: doc = Document.objects.get(pk=XX) doc.s3_file.read(version=XXXXXXXXXX) # Something like this? I've been reading the official documentation, but can't find how to: Get available versions of an object Retrieve one specific version Any help is appreciated. -
Getting Forbidden (CSRF token missing or incorrect.): /myurl/ error while Overriding ObtainJSONWebToken
I inherit ObtainJSONWebToken and trying to override its post method but every time I hit API It throws me error : Forbidden (CSRF token missing or incorrect.): /myurl/ class LoginDrfJwtView(ObtainJSONWebToken): def post(self, request, *args, **kwargs): response = super(LoginDrfJwtView, self).post(request, *args, **kwargs) if condition == True: # my code return True -
I can't create tables after migrating the models from Django models.py
so i created a user from django.contrib.auth.models import User and i managed to migrate it to MySQL database using python manage.py makemigrations python manage.py migrate but when i tried to add new tables in my app model.py when i makemigrations is sais that "No changes detected" and when i use python manage.py migrate i reciev this message which includes the user tables but none of the models i created Operations to perform: Apply all migrations: admin, api, auth, authtoken, contenttypes, sessions Running migrations: No migrations to apply. my model code from django.db import models from django.contrib.auth.models import User CHOICES = ( (None, "indéterminé"), (True, "actif"), (False, "non actif") ) class Departement(models.Model): id = models.AutoField(primary_key=True) nom = models.TextField(max_length=255) fk_transfo = models.ForeignKey(Transfo, on_delete=models.CASCADE) def __str__(self): return self.nom class PointMesure (models.Model) : id = models.AutoField(primary_key=True) nom = models.TextField(max_length=64) etat = models.NullBooleanField(choices = CHOICES) nbHeursCons = models.FloatField() fk_departement = models.ForeignKey(Departement, on_delete=models.CASCADE) def __str__(self): return self.nom class Mesure (models.Model): id = models.AutoField(primary_key=True) t = models.FloatField() i1inst = models.FloatField() i2inst = models.FloatField() i3inst = models.FloatField() i4inst = models.FloatField() u1inst = models.FloatField() u2inst = models.FloatField() u3inst = models.FloatField() p1 = models.FloatField() p2 = models.FloatField() p3 = models.FloatField() fk_PointMesure = models.ForeignKey(PointMesure, on_delete=models.CASCADE) def __int__(self): return self.id class ValCle … -
how to deal with dynamic items that are used on the base.html in Django
I have some dynamic fields on the base.html like the footer text and the social accounts links, but I need to fetch them from the database and send them alongside with each response for a view that uses a template which extends the base.html template. right now I am fetching the needed Items on every view and send them alongside with the view context, but I feel that this is repetitive, especially if I have more dynamic items, I tried also to save them to the request session but also it will require more code and edge cases. what is the most efficient way to fetch these items once and be able to use them on all the views that extends the base.html template? -
How to load data from a model into django settings.py variable?
I am writing a django application where I have a model called Website which contains websites of people. I only allow people who have their websites in my database to use my Django REST API. I am using the django-cors-headers package to whitelist the domains of people: https://github.com/adamchainz/django-cors-headers. CORS_ORIGIN_WHITELIST variable in settings.py allows me to white list domains as shown in https://github.com/adamchainz/django-cors-headers#cors_origin_whitelist The problem is that I have to query my models to get the website domains, append them to a list and then put that list into CORS_ORIGIN_WHITELIST. But I can't do that in settings.py because models are loaded after the app starts and settings.py is the one that starts the app. Does anyone know a way around that? Any suggestions will be appreciated. Thanks in advance. -
Converting latitude and longitude columns into a geopoint in django
I have latitude and longitude as separate columns and want to use geo point in Elasticsearch. How can i convert the columns into geopoint so I can find all points in database within a given radius. -
Trouble with deploy django channels using Daphne and Nginx
I got a 502 error when I'm trying to open a website. I used the instructions from the official website link Added new file lifeline.conf at /etc/supervisor/conf.d/ lifeline.conf [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:8000 # Directory where your site's project files are located directory=/home/ubuntu/lifeline/lifeline-backend # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/home/ubuntu/Env/lifeline/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-head$ # Number of processes to startup, roughly the number of CPUs you have numprocs=4 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/home/ubuntu/asgi.log redirect_stderr=true Setup nginx conf upstream channels-backend { server localhost:8000; } server { listen 80; server_name staging.mysite.com www.staging.mysite.com; client_max_body_size 30M; location = /favicon.ico { access_log off; log_not_found off; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } I checked the asgi log file and it contains …