Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
apache2 with django - can't write to log file
I have django running on apache2 server. my settings.py looks like this: WSGI_APPLICATION = 'my_app.wsgi.application' ... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s: %(message)s' } }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '../django.log', 'formatter': 'verbose', 'maxBytes': 1024 * 1024 * 5, # 5 MB 'backupCount': 5, }, }, 'loggers': { 'my_app': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } My idea was basically to create a log that all the components of my django app will write to, with level INFO. The issue I am facing is, when running the server, the log is created with root permissions: ll ../django.log -rw-r--r-- 1 root root 0 Jan 9 10:17 ../django.log And so, what happens when I try to log to it is: /var/log/apache2/error.log [Wed Jan 09 11:37:43.677755 2019] [:error] [pid 1457:tid 140554321598208] [remote 192.168.254.52:60257] ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '../django.log' I did find those issues: Permission Denied when writing log file and Django: Setup an efficient logging system for a website in production. and if I change the permissions of the file to be owned by www-data and not root, it works. My … -
ValueError at / Django
I am getting Error: ValueError at /user-admin/manager/manager-add Cannot assign "<QuerySet [<Groups: Codism>, <Groups: Codism>, <Groups: Codism123221>]>": "UserGroup.usergroup_group" must be a "Groups" instance. Forms.py class ManagerGroupForm(forms.ModelForm): usergroup_group = forms.ModelMultipleChoiceField(queryset=Groups.objects.all()) class Meta: model = UserGroup fields = ['usergroup_group'] Views.py @login_required def ManagerAddView(request): if request.method == 'POST': random_password = User.objects.make_random_password() # generate password here ur_form = ManagerRegisterForm(request.POST, pwd=random_password) pr_form = ManagerProfileForm(request.POST, request.FILES) gr_form = ManagerGroupForm(request.POST) user_role = ACLRoles.objects.get(acl_role_title='Manager') if ur_form.is_valid() and pr_form.is_valid() and gr_form.is_valid(): new_user = ur_form.save(commit=False) new_user.username = new_user.email new_user.set_password(random_password) new_user.save() profile = pr_form.save(commit=False) if profile.user_id is None: profile.user_id = new_user.id profile.user_role_id = user_role.id profile.user_company_id = request.user.userprofile.user_company.id profile.save() # newly added code new_user_group = gr_form.save(commit=False) new_user_group.usergroup_user = new_user.id new_user_group.usergroup_created_by = request.user new_user_group.usergroup_updated_by = request.user new_user_group.save() return redirect('admin_managers') else: ur_form = ManagerRegisterForm() pr_form = ManagerProfileForm() gr_form = ManagerGroupForm() return render(request, 'users/admin/managers_form.html', {'ur_form': ur_form, 'pr_form': pr_form, 'gr_form': gr_form}) The actual problem started when i add ManagerGroupForm() because i want to select multiple select and multiple i have used forms.ModelMultipleChoiceField in my forms.py. Please help me because it is not validating my form and also should i am manually entry data like request.user and new_user.id -
How to integrate django project with nextcloud calendar
We're planning to write a Django application that can manage events for a group of users. The things that we need: There is an easy way for the admins to create new events and upon creation users are notified (per email) and can confirm or decline attendance. The user can integrate these events in their calendar client, e.g. thunderbird, iOS, etc. Depending on people attending to the event, we can create some stats, overviews, graphs, etc. Users can change their RSVP status and the admins are notified per email. Events will have probably several linked data to them (maybe some maps, documents, etc.) and other fields for categories, etc. Events might be recursive or one-time events. There is an easy way to add exceptions for recursive events. There is an overview for all events and RSVP status for the events is easily accessible. The count of attendees is listed for each event. The events overview can be filtered by different criteria (date range, category, ...) We want to use a Django project for managing stats, linked media, listings, etc. And the plan was to add fields for the scheduled date + recurrence. But all existing calendar alternatives for Django I've … -
How to compare some_time|timeuntil with specific time interval in Django templates?
I'm making a new label on my BBS. (When an article is a relatively new one, then a label says 'this is new one' appears.) After reading Django Docs I know |timeunitl returns the value from given time to now. I want to compare this value to a specific time interval such as two days or two hours. So I tired below {% if article.created_at|timeunitl < 2 %} <span class = "label label-new">NEW</span> {% endif %} However, I can't see <span class = "label label-new">NEW</span> in actual page no matter how I change the value of the right side. How Can I compare this value? My Django version is 1.11.16, and Python version is 3.6.7. -
keyerror in verification of email api
in project i am working getting error KeyError at /rest-auth/registration/verify-email/ def get_object(self, queryset=None): key = self.kwargs('key') emailconfirmation = EmailConfirmationHMAC.from_key(key) if not emailconfirmation: if queryset is None: queryset = self.get_queryset() try: emailconfirmation = queryset.get(key=key.lower()) except EmailConfirmation.DoesNotExist: raise Http404() return emailconfirmation -
Django: Some strings are automatically added to my code
I'm creating a website using the django framework. But recently, I found something strange. I loaded the page at 127.0.0.1:8000, but failed. I checked the console log and found some js files with errors. Then I check the error in the js file and find some strings added to my code automatically. If I clean up the cookies and reload the page, I might load the page successfully or these strings might still appear in other js files. Why is it happen? /error js file if ($element.data('on-label') !== undefined) onLabel = $element.data('on-label'); if ($element.data('ofDate: Wed, 09 Jan 2019 09:25:20 GMT Server: WSGIServer/0.2 CPython/3.7.1 f-label') !== undefined) offLabel = $element.data('off-label'); if ($element.data('icon') !== undefined) icon = $element.data('icon'); Sometime the two strings will add into my code automatically When I first visited the page. Date: Wed, 09 Jan 2019 09:25:20 GMT Server: WSGIServer/0.2 CPython/3.7.1 js file will auto -
How django resolve the foreign key in its models.py?
I am wondering how django decides which column or field will act as foreign key to another model in One to Many relationship. class Department(models.Model): dept_name = models.CharField(max_length=100) dept_head = models.CharField(max_length=100) dept_abbrv = models.CharField(max_length=100) class Employee(models.Model): dept = models.ForeignKey(Department) emp_name = models.CharField(max_length=100) Now how django knows which column of Department (dept_name, dept_head or dept_abbrv) will map to 'dept' in Employee. In my admin page of Employee details if I have to add a new employee, there is dropdown listing all Department.dept_name against 'dept'. How django decides that? Why it is not dropdown list of dept_head or dept_abbrv ? -
How to make this function easier to test?
I have the function which builds and return Slack message with text and attachments. How can I refactor this function to make it easier to test? Should I split it into multiple functions? def build_list_message(team_id, user_id, msg_state=None, chl_state=None): if not msg_state: msg_state = {} if not chl_state: chl_state = {} resource_type = msg_state.get('resource_type', 'all') availability = msg_state.get('resource_availability', 'all') pages = Page.objects.none() async_tasks = AsyncTask.objects.none() if resource_type in ['web_pages', 'all']: pages = Page.objects.filter( user__team__team_id=team_id).order_by('title') if resource_type in ['async_tasks', 'all']: async_tasks = AsyncTask.objects.filter( user__team__team_id=team_id).order_by('title') if availability == 'available': pages = pages.filter(available=True) async_tasks = async_tasks.filter(available=True) elif availability == 'unavailable': pages = pages.filter(available=False) async_tasks = async_tasks.filter(available=False) channel_id = chl_state.get('channel_id') if channel_id: pages = pages.filter(alert_channel=channel_id) async_tasks = async_tasks.filter(alert_channel=channel_id) user = SlackUser.retrieve(team_id, user_id) attachments = [ _build_filters(resource_type, availability), *[_build_page_item(p, user) for p in pages], *[_build_async_task_item(at, user) for at in async_tasks] ] return { 'text': "Here's the list of all monitoring resources", 'attachments': attachments } -
Put Django ORM iterations to one request
I have three models: class Box(models.Model): name = models.TextField(blank=True, null=True) class Toy(models.Model): box = models.ForeignKey(Box, related_name='toys') class ToyAttributes(models.Model): toy = models.ForeignKey(Toy) color = models.ForeignKey(Color, related_name='colors') And list: list = [[10, 3], [4, 5], [1, 2]] Where every value is a pair or box and color id's. I need to filter this data and return boxes objects with toys of needed color. Now I do this: box = Box.objects.filter(id=n[0], toys__colors=n[1]) for n in list: if box.exists(): ... But it takes a lot of time for long lists, as I understand because of multiple SQL requests. Can I make it faster? Is it possible to get only needed boxes with one request and how can I make it? Thanks! -
Why I have error message Unknown field for ModelAdmin?
I have created model and admin model In admin editor interface i have error Whats wrong? FieldError at /admin/videos/video/1/change/ Unknown field(s) (name) specified for Video. Check fields/fieldsets/exclude attributes of class VideoAdmin. class Video(models.Model): name = models.CharField(max_length=255) image = models.ImageField(max_length=255, blank=True) video = models.FileField(max_length=255, blank=True) description = models.TextField(blank=True) producer = models.CharField(max_length=255, blank=True) actors = models.TextField(blank=True) duration = models.CharField(max_length=64, blank=True) hit = models.BooleanField(default=False) new = models.BooleanField(default=False) class VideoAdmin(admin.ModelAdmin): fields = ('name',) admin.site.register(Video, VideoAdmin) -
Matplotlib with mpld3: tight_layout works different on Windows and Ubuntu
I use matplotlib and mpld3 to display an interactive figures in Django template. On Windows with python3.5.1 this code with tight_layout works fine and bars in first figure have a correct padding, but in a production server with Ubuntu 16.04.5, with python3.5.2 and same libs I have this warning and there is no padding between two bars: tight_layout.py:181: UserWarning: Tight layout not applied. The bottom and top margins cannot be made large enough to accommodate all axes decorations. warnings.warn('Tight layout not applied. ' views.py: import matplotlib.pyplot as plt from matplotlib import rc from mpld3 import fig_to_html, plugins def graphs(request): ... rc('font', size=16) fig1 = plt.figure() # users profits diagram plt.subplot(121) plt.bar(usernumbers, profits, color='g') for i, v in enumerate(profits): plt.text(i - 0.2, v + 0.3, ' ' + str(v), va='center', fontweight='bold') plt.xticks(usernumbers, usernames) plt.ylabel('$') plt.title('Users profits', fontsize=20) # users orders number diagram plt.subplot(122) plt.bar(usernumbers, ordernumbers, color='b') plt.xticks(usernumbers, usernames) plt.ylabel('Count') plt.title('Users orders', fontsize=20) fig1.tight_layout() ... return render_to_response('graphs.html', {'figure1': fig_to_html(fig1), 'figure2': fig_to_html(fig2), 'user': request.user}) graphs.html: {% extends 'main.html' %} {% block content %} <div class="row"><div class="column"> <center>{{ figure1|safe }}</center><hr/> <center>{{ figure2|safe }}</center> </div></div> {% endblock %} Versions: Django==2.0.7 matplotlib==3.0.2 mpld3==0.3 jinja2==2.10 I also tried plt.tight_layout(), but got the same warning. Maybe exists more … -
docker setting up gdal for django
I'm setting a django project and trying to use docker with it. It has a dependency to gdal likely from using postgis. This is the docker file FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt and the requirements file Django==2.1.5 psycopg2==2.7.6.1 gdal==2.2.3 when it reaches gdal it throws this error FileNotFoundError: [Errno 2] No such file or directory: 'gdal-config': 'gdal-config' however this is something I've already got working locally (pw) sam@sam-Lenovo-G51-35:~/code/pw$ gdal-config --version 2.2.3 I did try to see if I can make it setup gdal-config using run by editing the docker file to this FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code RUN apt-get install libgdal-dev RUN export CPLUS_INCLUDE_PATH=/usr/include/gdal RUN export C_INCLUDE_PATH=/usr/include/gdal WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt based on the nearest match for error to possible solution but it throws this error Step 4/9 : RUN apt-get install libgdal-dev ---> Running in 8e5e71369e4a Reading package lists... Building dependency tree... Reading state information... E: Unable to locate package libgdal-dev -
Django-import-export accessing fields in file not used by the ModelResource
The original question was posted here: https://github.com/django-import-export/django-import-export/issues/886 Hello everyone, I have an xslx document with the following columns: category | venue | event | question | answer | client | Action The Category, Venue, Event and Client are ForeignKeys. If they do not exist they should be created so I have created custom ForeignKeyWidgets: class ForeignKeyWidgetWithCreation(ForeignKeyWidget): def __init__( self, model, field='pk', create=False, *args, **kwargs): self.model = model self.field = field self.create = create # super(ForeignKeyWidgetWithCreation, self).__init__(*args, **kwargs) def clean(self, value, row=None, *args, **kwargs): val = super(ForeignKeyWidgetWithCreation, self).clean(value) if self.create: instance, new = self.model.objects.get_or_create(**{ self.field: val }) val = getattr(instance, self.field) return self.model.objects.get(**{self.field: val}) if val else None # Event Widget class EventWidget(ForeignKeyWidget): def __init__( self, model, field='pk', create=False, *args, **kwargs): self.model = model self.field = field self.create = create # super(ForeignKeyWidgetWithCreation, self).__init__(*args, **kwargs) def clean(self, value, row=None, *args, **kwargs): val = super(ForeignKeyWidgetWithCreation, self).clean(value) if self.create: instance, new = self.model.objects.get_or_create(**{ self.field: val }) val = getattr(instance, self.field) return self.model.objects.get(**{self.field: val}) if val else None # CLIENT WIDGET class ClientWidget(ForeignKeyWidget): def __init__(self, model, field='client', *args, **kwargs): self.model = Client self.field = field def clean(self, value, row=None, *args, **kwargs): val = super(ClientWidget, self).clean(value) if val: client = Client.objects.get_or_create(name=val) return client # return self.get_queryset(value, … -
DRF: drf-nested-routers: Could not resolve URL for hyperlinked relationship using view name
I'm having trouble displaying the -detail of a model using viewsets. I'm using the drf-nested-routers package for my urls. Here is an example of Courses and a Section related to the course. (code is below) [ { "url": "http://127.0.0.1:8000/courses/CS250/", "course_code": "CS250", "sections_offered": [ "http://127.0.0.1:8000/courses/CS250/sections/01/" ] }, { "url": "http://127.0.0.1:8000/courses/CS150/", "course_code": "CS150", "sections_offered": [] } ] I can navigate to courses/CS250/sections only if there was nothing, but once I create an object there I can no longer visit that endpoint, and I also cannot visit the URL of that object (http://127.0.0.1:8000/courses/CS250/sections/01/) without getting this error: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "section-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute on this field. However, I can perfectly navigate to the url of a course (http://127.0.0.1:8000/courses/CS250/) /models.py from django.db import models class Course(models.Model): course_code = models.CharField(default='', max_length=50, primary_key=True) class Section(models.Model): section_number = models.CharField(default='01', max_length=100, primary_key=True) parent_course = models.ForeignKey(Course, related_name="sections_offered", on_delete=models.CASCADE, blank=True, null=True) /views.py from . import models from . import serializers from rest_framework import viewsets class CourseViewSet(viewsets.ModelViewSet): serializer_class = serializers.CourseSerializer queryset = models.Course.objects.all() class SectionViewSet(viewsets.ModelViewSet): serializer_class = serializers.SectionSerializer queryset = models.Section.objects.all() /serializers.py from rest_framework_nested.relations import NestedHyperlinkedRelatedField from … -
How do I restore access to local Django site using "python manage.py runserver" after upgrading Homebrew?
I upgraded Homebrew in the terminal. After entering my virtual environment with no problem, I typed "python manage.py runserver" as usual, but I got the following error: /usr/local/Cellar/python/3.7.2/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'manage.py': [Errno 2] No such file or directory I assume the upgrade requires me to change something, but I'm not sure what I need to do. Do I need to reinstall Django? -
How can I fix errors in django?
I've tried everything I can, but I can't fix this error. I am a beginner and imitated what was in the book. Give me a hand. Source Code This is my urls.py-fistsite source code. from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), path('/polls', views.polls, name='polls'), path('/admin', views.admin, name='admin') ] This is my urls.py-polls from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/result/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote') ] But there was an error. enter image description here And this is my project.enter image description here Help me! -
Django Migration errors
im trying to migrate these models and im getting error.I added the field position,manager which were initially not in my model.made project_name a primary key in Project models:i ran python manage.py migrate and i get an error: Below is the models. class Employee(models.Model): position = models.CharField(max_length=200) manager= models.CharField(max_length=200,default="x") employee_number = models.PositiveIntegerField(primary_key=True) class Project(models.Model): project_code=models.CharField(max_length=200) employees=models.ManyToManyField(Employee,through="User_Projects") project_name= models.TextField(primary_key=True) class User_Projects(models.Model): employee_number=models.ForeignKey(Employee,to_field='employee_number',on_delete=models.CASCADE) project_name=models.ForeignKey(Project,to_field="project_name",on_delete=models.CASCADE) The error i am getting is below,i need help: InternalError:(1829,"cannot drop column 'id' : needed in a foreign key constraint 'timeapp_user_projects_projects_id_cf8c73ba_fk_timeapp_project_id' of table 'timesheets.timeapp_user_projects'") -
problems with pip install mod-wsgi
I'm new IT and programming; I been struggling to install mod_wsgi with pip Example in cmd: pip install mod_wsgi I been trying to lunch my django project on my own pc acting as a server I'm using Apcache 24 and my PC is windows 10, 64bits My python is 3.7.1 and Django is 2.1.3 Solution I had try: https://stackoverflow.com/a/42323871/10865416 error: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ I had check and and intsall the C++ 14 here the link where I download: https://www.microsoft.com/en-gb/download/details.aspx?id=48145 https://github.com/sammchardy/python-binance/issues/148#issuecomment-374853521 error: C:\Users\user>pip install C:/mod_wsgi-4.5.24+ap24vc14-cp35-cp35m-wind_amd64.whl Requirement 'C:/mod_wsgi-4.5.24+ap24vc14-cp35-cp35m-wind_amd64.whl' looks like a filename, but the file does not exist mod_wsgi-4.5.24+ap24vc14-cp35-cp35m-wind_amd64.whl is not a supported wheel on this platform. https://github.com/GrahamDumpleton/mod_wsgi/blob/develop/win32/README.rst error: error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x86\\link.exe' failed with exit status 1120 ---------------------------------------- Command "c:\users\user\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-f9igth3o\\mod-wsgi\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\user\AppData\Local\Temp\pip-record-kmcbksbk\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\user\AppData\Local\Temp\pip-install-f9igth3o\mod-wsgi\ and yes hd VC10 install to had this error, here the link https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2017 In advance thank you for your help, apprentice it -
Retrieving a user based on email fails in django
I created a user in django that only has an email and a password. I am trying to obtain the object using that email address. I am doing the following user_obj = User.objects.filter(Q(email=email)) However user_obj is always empty. Then I tried the following. In the following method i got all the users and iterated over them until I came across the user with that email address allusers = User.objects.all() user_obj = User.objects.filter(Q(email=email)) #--->Returns empty Why? for a in allusers: if a.email == email: print("Found") #<---Email Exists #-->Comes in here. So email does exist My question is why is User.objects.filter(Q(email=email)) returning an empty queryset when the object does exist in the db. It just doesnt have a username or anything. It only has email address and a password. -
Multiple Select Foreign Key Field Django Form
I have a form where I want to display multiple select foreign key field. Form.py class ManagerGroupForm(forms.ModelForm): class Meta: model = UserGroup fields = ['usergroup_group'] Models.py class UserGroup(models.Model): usergroup_user = models.ForeignKey(User, on_delete=models.CASCADE) usergroup_group = models.ForeignKey(Groups, on_delete=models.CASCADE) In my form I want to select usergroup_group multiple times. -
django modelform more then one foreign key using exclude
here user i want user and userprofile. useing exclude. when i add userprofile error 'WSGIRequest' object has no attribute 'userprofile' modelform class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('categories', 'title', 'description', 'image', 'price') exclude = ('user','userprofile') view @login_required def productpost(request): form = ProductForm() if request.method == "POST": form = ProductForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.userprofile = request.userprofile form.save() return success(request) else: print("The Form Is Invalid") return render(request, 'product/postproduct.html', {'form': form}) -
POST http://127.0.0.1:8000/api/users/ 400 (Bad Request)
I was trying to create simple api using django rest framework but stuck in the error. Hoping for the soon response. Thanks in advance. serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = { 'password' : { 'write_only' : True , 'required':True }} def create(self, validated_data): user = User.objects.create_user(**validated_data) return user views.py from django.contrib.auth.models import User from rest_framework import viewsets from register_api.serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer register/urls.py(app) from django.urls import path, include from rest_framework import routers from register_api import views # from rest_framework.authtoken.views import ObtainAuthToken router = routers.DefaultRouter() router.register('users', views.UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls',namespace='rest_framework')), ] **django_api/url.py** (project) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('register_api.urls')), ] Backend error Console Error -
nginx access log shows HEAD request every 5 seconds
I have a Django Gunicorn Nginx setup that is working without errors but the nginx access logs contains the following line every 5 seconds: 10.112.113.1 - - [09/Jan/2019:05:02:21 +0100] "HEAD / HTTP/1.1" 302 0 "-" "-" The amount of information in this logging event is quite scarce, but a 302 every 5 seconds has to be something related to the nginx configuration right? My nginx configuration is as follows: http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/.conf; upstream app_server { server unix:/path_to/gunicorn.sock fail_timeout=0; } server { server_name example.com; listen 80; return 301 https://example.com$request_uri; } server { listen 443; listen [::]:443; server_name example.com; ssl on; ssl_certificate /path/cert.crt; ssl_certificate_key /path/cert.key; keepalive_timeout 5; client_max_body_size 4G; access_log /var/log/nginx/nginx-access.log; error_log /var/log/nginx/nginx-error.log; location /static/ { alias /path_to/static/; } location /media/ { alias /path_to/media/; } include /etc/nginx/mime.types; # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $host; proxy_redirect off; proxy_pass http://app_server; } } } -
Reorder available options in filter_horizontal widget
I use an m2m relation in my Django model and filter_horizontal option to show it in the admin. After moving some items to the "chosen" and then removing them back to the "available" in this widget, the items are shown at the bottom of the "available" list. Is it possible to rearrange them in the order in which they were shown initially? -
Django search result with pagination
There is search field in template that can enter a keyword to search in a model and show the result with pagination. I need to pass this keyword in views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if 'color' in self.request.GET and self.request.GET['color']: context['query'] = self.request.GET.get('color') return context and combine it with pagination to prevent error.( If I don't do this, it will go to next page with raw data) {% if page_obj.has_next %} <a id="next" href="?page={{ page_obj.next_page_number }}{% if query %}&q={{ query }}{% endif %}">next</a> <a id="last" href="?page={{ page_obj.paginator.num_pages }}{% if query %}&q={{ query }}{% endif %}">last &raquo;</a> {% endif %} Is there any good idea to solve this problem? I know this is such a stupid solution...