Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination not working with Django Class Based Generic ListView as expected
I'm having issues with paginating the data for all other views, apart for the first view present in the same views.py file. For the first view (JobList) pagination works completely fine, whereas for the second view (JobSearchView) pagination doesn't work at all. I'm not sure, what's preventing the JobSearchView from paginating. I have another 2 views present within the same views.py file, which are identical to the JobSearchView, even for those views the pagination isn't working. Here is my code within the views.py file. class JobList(ListView): model = Job template_name = "jobs/job_listings.html" context_object_name = "job_list" # ordering = ['-published_date'] ordering = ['-id'] paginate_by = 3 def get_context_data(self, **kwargs): context = super(JobList, self).get_context_data(**kwargs) jobs_expiring_soon = Job.objects.filter(application_last_date__gte=datetime.now(), application_last_date__lte=lookup_date) state_list = State.objects.order_by('name') profession_list = Profession.objects.order_by('name') context['jobs_expiring_soon'] = jobs_expiring_soon context['state_list'] = state_list context['profession_list'] = profession_list return context class JobSearchView(ListView): model = Job template_name = 'jobs/job_search_results.html' ordering = ['-published_date'] context_object_name = 'search_results' paginate_by = 3 def get_context_data(self, **kwargs): context = super(JobSearchView, self).get_context_data(**kwargs) search_results = [] distinct_search_results = [] query = self.request.GET.get('search_term') keyword_list = query.split(" ") keyword_list = [x for x in keyword_list if len(x.strip()) > 0] for keyword in keyword_list: posts = Job.objects.filter( Q(title__icontains=keyword) | Q(organization__name__icontains=keyword) | Q(type__icontains=keyword) | Q(address__icontains=keyword) | Q(city__name__icontains=keyword) | Q(state__name__icontains=keyword) | … -
Adjusting current code to be able to add items from new table to the basket
My website is currently adapted to deal with things like adding to the cart, removing from the cart and creating an order, only on one Item table. I wanted to add different products to the site, so I need to create a new table, that will handle other items. The thing is, that I am not really sure how to properly implement that to my website, so things like adding to the cart and creating order would work with that new table as well. So thats the model of the first Item table: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ManyToManyField(Category) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) When you add item to the cart it goes to this table: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity * self.item.price def get_total_discount_item_price(self): return self.quantity * self.item.discount_price def get_amount_saved(self): return self.get_total_item_price() - … -
Django markdown/wysiwyg with global css support
I am looking for a post editor for Django Admin which will incorporate my sites css classes / styles. I installed Martor markdown editor, which I think is fantastic, but It does not seem possible to add css to the rendered markdown when using: {{ post.content|safe_markdown }} This is also the case with CKeditor, which I can't get to match my sites style in fonts, colors etc. Anyone have any tips for me for an easy to use solution which will adapts site css classes, and has an editor with code snips, images, h1, h2, h3, quote and paragraph etc? -
Foreign key POST in Django
I have some problems with my app . I need to make task with relations to user. Here is my code: bug ValueError at / Cannot assign "(<SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x04C54E38>>,)": "Task.usertask" must be a "UserMembership" instance. models.py class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True,blank=True) image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True) class Task(models.Model): title=models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now,blank=True) is_published=models.BooleanField(default=True) usertask=models.ForeignKey(UserMembership, on_delete=models.PROTECT, null=True, blank=True) views.py if request.method == 'POST': usertask = request.user, title = request.POST['title'] task = Task(usertask=usertask,title=title) task.save() task = Task.objects.order_by('-date').filter(is_published=True, usertask=request.user.id) context={ 'task':task, } return render(request,'index.html',context) html form <form action="" method="POST"> {% csrf_token %} <input name="title" type="text" class="form-control" id="usr"> <button type="submit" class="btn btn-primary">add</button> -
How can I skip deleted models during a loop doing expensive operations in Django?
I have a model called device. Each device has a data_downloaded() and data_uploaded() method, which look through the database for all records associated with that device, and sum up the data they've used. Each device can potentially have thousands of records that need to be aggregated to calculate its usage. My models look like this: class Device(models.Model): ... mac_address = models.CharField(...) data_downloaded_cached = models.BigIntegerField(...) data_uploaded_cached = models.BigIntegerField(...) def data_downloaded(self): return DataRecord.objects.filter(mac_address=self.mac_address, direction="download").aggregate(data=Sum('data')).get("data", 0.00) or 0.00 def data_uploaded(self): return DataRecord.objects.filter(mac_address=self.mac_address, direction="upload").aggregate(data=Sum('data')).get("data", 0.00) or 0.00 class DataRecord(models.Model): timestamp = models.DateTimeField(...) mac_address = models.CharField(...) direction = models.CharField(...) data = models.BigIntegerField(...) Since device.data_downloaded() and device.data_uploaded() are expensive operations that can take a minute to calculate (a lot of database rows need to be aggregated), I can't call those methods directly when a template is loading, so I cache the values. A background process runs the following code to update these cached values every few minutes: for device in Device.objects.all(): device.data_downloaded_cached = device.data_downloaded() device.data_uploaded_cached = device.data_uploaded() device.save() When templates are displaying a list of devices, along with download and upload values for each devices, they can just use the cached values instead of trying to run these expensive operations on-the-fly, which would cause templates to … -
how to use set_cookie in context processors?
I have the following code in context_prcessors.py def company(request): … context = { ‘company’: company } response = render(request, ‘company.html’, context) response.set_cookie(‘company’, current_company return response and the following error: RecursionError at / maximum recursion depth exceeded while calling a Python object -
Nginx failure: (111: Connection refused) while connecting to upstream, client
I am running a django app with nginx in a docker container and everything was running perfectly fine up until I rebuild the container. Suddenly I get a 502 (Bad Gateway) error and the logs say (111: Connection refused) while connecting to upstream, client: 216.245.221.82, I have no idea what changed. I am pulling the lates nginx image so maybe there was a change which doesn't work well with my config. But I don't know. I am deploying my app on an EC2 instance with nginx in a docker container. Here are my configs and my compose file: server { listen 443 ssl; server_name mywebsite.de; client_max_body_size 0; charset utf-8; ssl_stapling off; ssl_stapling_verify off; ssl_certificate /etc/letsencrypt/live/mywebsite.de/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mywebsite.de/privkey.pem; set $my_host $http_host; if ($http_host = "mywebsite.de") { set $my_host "mywebsite.de"; } location / { proxy_pass http://django:5000; proxy_set_header Host $my_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } server { listen 80 ; server_name mywebsite.de; return 301 https://mywebsite.de$request_uri; } server { listen 80 ; server_name www.mywebsite.de; return 301 https://mywebsite.de$request_uri; } server { listen 443 ; server_name www.mywebsite.de; return 301 https://mywebsite.de$request_uri; ssl_stapling off; ssl_stapling_verify off; ssl_certificate /etc/letsencrypt/live/mywebsite.de/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mywebsite.de/privkey.pem; } My docker-compose file: version: '3' services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile image: my_website_production_django … -
Calling function in function using Django causes NameError
to keep my project clean I have module with my CalculationLogic class. I call this class in my views.py file, like: def method_in_views_file(request): cl = CalculationLogic() return cl.method_in_calculation_logic() In my CalculationLogic: def other_function(self,x): # some logic here # return result def method_in_calculation_logic(self,args): # some logic here # x = ['x','y','z'] data = other_function(x) return render(request,'file.html',{'data':data}) Unfortunately after calling this view in my browser I get NameError that other function is not defined. Which part can be wrong here? -
Get all the inputs that has been used in the search fields (historic) and display in the template in Django
I research a lot but did not found any answers to my question - hope anyone can help me. I made a simple view to search some points from my DB: class SearchResults(LoginRequiredMixin, ListView): model = Points template_name = 'search_results.html' def get_queryset(self): # new query_x = self.request.GET.get('query_x') query_y = self.request.GET.get('query_y') points_returned = self.request.GET.get('points_returned') distance_condition = self.request.GET.get('distance_condition') if distance_condition == 'Nearest': object_list = Points.objects.filter( geom_point__distance_lte=('POINT({0} {1})'.format(query_x, query_y), D(km=10000000000000)) ).order_by('geom_point')[:int(points_returned)] return object_list else: object_list = Points.objects.filter( geom_point__distance_lte=('POINT({0} {1})'.format(query_x, query_y), D(km=10000000000000)) ).order_by('-geom_point')[:int(points_returned)] return object_list The search works well and I get the right values. But what I need now (and didn`t find the solution) is to display in the home.html (home page from the search) all the inputs that has been made by the user in the query_x and query_x search fields, like a search historic. The inputs that the user put need to be recorded in his profile if possible. I already tried some stuff like using MiddleWare, JSON Response but did not have success. -
Django context returned by get_object
class ListDetailView(DetailView): context_object_name = 'aaaa' def get_object(self, queryset=None): return List.objects.get(unique_list_id=self.kwargs['unique_list_id']) In template I have to equal contexts: {{ object.list_name }} {{ aaaa.list_name }} How to override get_object() to return only context specified by context_object_name = 'aaaa'? Why I have 2 contexts? -
Django: interacting with multiple databases in a centralized way and in read only mode
I'm trying to understand what is the best solution to make Django interact with more databases. I need to use one db as the Django models backend, and I need also to interface Django apps with another legacy db but, in this case, only to read data. More context: I can just connect to the legacy db with a user with read and write permissions, but I want to be sure that the legacy db is used in read only mode (at least implicitly). Moreover, I need to query the legacy db from many apps and views, so a centralized connection management would be the optimal solution, both to manage the configuration in one place and to optimize resources (connections, cursors and so on) At first, I tried to create a connection object with a python library and to share it across the project apps and views, but I realized I was reinventing the wheel. Indeed, Django natively supports more databases connections in a centralized way. E.g., settings.py from Django doc: DATABASES = { 'default': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres_user', 'PASSWORD': 's3krit' }, 'legacy_db': { 'NAME': 'user_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'priv4te' } } As far as … -
how to serialize list of form object to JSON in django
I'm trying to serialize the form objects and return to the AJAX call so that I can display them in the template, but I'm not able to serialize them unlike serializing the model objects don't we have an option for form objects if request.method == 'POST': temp_data_form = TemplateDataForm(request.POST) if request.POST.get('temp_id'): # getting id of the current template existing_template = Template.objects.filter(id=request.POST.get('temp_id'))[0] if request.POST.get('item'): item_query = existing_template.tempdata_set.filter(item=request.POST.get('item')) if item_query: item_query = item_query[0] and True # we only edit the existing object of the template always as we create the object by default on GET request if existing_template and existing_template.title != request.POST.get('title') and request.POST.get('title')!= None: existing_template.title = request.POST.get('title') existing_template.save() if temp_data_form.is_valid() and item_query != True: # Template items alias data td_obj = temp_data_form.save(commit=False) td_obj.template = existing_template td_obj.save() values_form = [] for item in existing_template.tempdata_set.all(): values_form.append(TemplateDataForm(instance=item)) return JsonResponse(values_form, safe=False) I'm getting the below error. raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type TemplateDataForm is not JSON serializable -
Requesting /admin but return to the same page
Hello there i m looking to fix a problem i m working on django right now the issue is that when i try to go to the admin area login it returns me to the same index.html page my code: urls.py on main folder from django.conf.urls import url,include from django.contrib import admin from first_app import views urlpatterns = [ url('',views.index,name="index"), url('first_app/',include('first_app.urls')), url('admin/', admin.site.urls) ] urls.py on first_app folder urlpatterns = [ url('',views.index,name="index") ] the views.py on first_app folder def index(request): my_dic = {'insert_me':"Hello Jinja"} return render(request,'index.html',my_dic) index.html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{% static 'css/style.css'%}"> <title>Django Page</title> </head> <body> <p>{{ insert_me}}</p> <h1>a picture </h1> </body> </html> -
connecting multiple create-react-apps with django
I have one big Django project consisting out of several small apps, independent from each other but partly sharing the same database or/and models. All the apps are created with python manage.py startapp appa so they have their own urls.py and views.py. I started using create-react-app for the front end for two of those apps and connected them successfully by turning the index.html of the react project into a template and serve it through the views.py (more here). Now each one of these create-react-app projects has its own build folder which's path I include in the STATICFILES_DIRS in settings.py to collect the static files. It looks like this: static/ templates/ appa/ build/ static/ index.html ... appb/ build/ static/ index.html ... Now, I was wondering if there is a way to have only one build folder that contains all built files respectively to their projects something like: appa/ appb/ static/ templates/ build/ appa/ static/ index.html ... appb/ static/ index.html ... I'm imagining that this folder would live on the same level as the the static folder and the appa and appb folders. One way, since by default I can't have the build folder outside the project folder structure(?) and I don't … -
Is there a way to retrieve the value of object instead of the id?
What I like to know is if there is a way to retrieve the object instead of the id (pk) when using django.core.serializers.serialize. I have a model named MenuItem with a ManyToManyField releated to a MenuSubItem. When I execute this code serializers.serialize('json', MenuItem.objects.all()) I got {'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**3**]}} But what I really wanna get is {'model': 'support.menuitem', 'pk': 2, 'fields': {'type': 2, 'app_label': None, 'label': 'Intranet Administration', 'sub_item': [**objects or objects_attribute**]}} Or if there is a workaround using other libs -
Howdo you create a Multipolygon field in GeoDjango from geojson objects
I'm new to GeoDjango and noticed some weird behavior when I was trying to convert a geojson object to a MultiPolygon object which is a field on the model. The geojson I upload is different than what the geojson property on the MultiPolygon field returns. Either I am not understanding what a MultiPolygon in GeoDjango is compared to a geojson MultiPolygon or I am creating the object improperly. I'm showing an example below with some real outputs and sudo code. Any direction would be appreciated including tell me I'm not creating the object properly, or that it is correct and I need to distinguish things differently. import json geojson = { "type": "MultiPolygon", "coordinates": [ [ [ [ [-77.62939453125, 38.53097889440024], [-76.70654296875, 38.53097889440024], [-76.70654296875, 39.32579941789298], [-77.62939453125, 39.32579941789298], [-77.62939453125, 38.53097889440024], ] ] ], [ [ [-77.783203125, 39.58875727696545], [-77.178955078125, 39.58875727696545], [-77.178955078125, 40.153686857794035], [-77.783203125, 40.153686857794035], [-77.783203125, 39.58875727696545], ] ], ], } my_model = MyModel.objects.first() my_model.multipolygon_field = json.dumps(geojson) my_model.save() my_model.multipolygon_field.geojson # return which contains different coords than I entered. '{ "type": "MultiPolygon", "coordinates": [ [ [ [ -77.783203125, 39.588757276965453 ], [ -77.178955078125, 39.588757276965453 ], [ -77.178955078125, 40.153686857794035 ], [ -77.783203125, 40.153686857794035 ], [ -77.783203125, 39.588757276965453 ] ] ] ] }' -
table services_parceiros has no column named user_id, DJANGO
thanks for your time. i've been trying to set a model to his creator user. although i'm getting this error and would like to know if am'i doing anything wrong before try a AbstractUser. i'did my user app just in the forms.py i don't know if thats the reason. Error: table services_parceiros has no column named user_id accounts/forms.py: from django import forms from django.contrib.auth import get_user_model, authenticate User = get_user_model() class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput()) def clean (self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('usuario não encontrado') if not user.check_password(password): raise forms.ValidationError('senha incorreta') if not user.is_active: raise forms.ValidationError('usuario desativado') return super(LoginForm, self).clean(*args, **kwargs) class RegisterForm(forms.ModelForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) email = forms.EmailField(label='Email address') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'email2', 'password' ] def clean(self, *args, **kwargs): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError("Emails must match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError( "This email has already been registered") return super(RegisterForm, self).clean(*args, **kwargs) services/models.py: from django.db import models from phone_field import PhoneField from datetime … -
How can i post a mp4 using moviepy without saving in local storage?
I'm trying to make a serve that concatenate two videos in one. But i need the server don't save the temp file in my local folder or any folder, only using the memory. clip1 = VideoFileClip(videoBegin) clip2 = VideoFileClip(videoEnd) final_clip = concatenate_videoclips([clip1, clip2]) # final_clip.write_videofile('video.mp4') files = {'file': final_clip} hea = {'Authorization': 'Token ' + token} import requests res = requests.post(url, files=files, headers=hea) But the problem is the request can't send the moviepy object, because it needs a bytes-like. *** TypeError: a bytes-like object is required, not 'VideoClip'. Is there a way to send a video from moviepy without saving in folder? And only use the memory? I'm using Django as a server. I don't know if it helps. -
How to create a virtual pdf file to be used in Django unit tests
I have this function in my viewset to upload a pdf file to A @api_view(['POST', 'DELETE']) @permission_classes((AllowAny,)) def upload_file_pdf(request): # Uploading and saving the file if the request is a POST - Validating the extension of the file as well if request.method == 'POST': try: upload = Upload(file_pdf=request.FILES["filepond"]) upload.full_clean() except ValidationError as e: return Response(e, status=status.HTTP_400_BAD_REQUEST) upload.save() return Response(upload.pk, status=status.HTTP_200_OK) # Deleting the file if the request is DELETE if request.method == 'DELETE': file_pk = str(json.loads(request.body)) return Response(file_pk, status=status.HTTP_200_OK) When I want to test it, I don`t know how to create a sample pdf file in unit tests def test_create(self): self.pdf_file = .... self.client.post('/api/v1/file/pdf/', data={"filepond": self.pdf_file}) self.assertEqual(response.status_code, 200) What should I put in front of self.pdf_file -
Saving Generated PDF to Django Model
Just want to create a pdf using pdfgen and then save it to my model with a file field, then return the link to the file. Getting error saying memoryview object has no attribute '__committed' views.py def pdf_creator(request): import io from django.http import FileResponse from reportlab.pdfgen import canvas from .models import Invoice # create buffer to hold pdf buffer = io.BytesIO() # create canvas with buffer as file c = canvas.Canvas(buffer) # draw on canvas c.drawString(0,300,"Hello") # save pdf c.save() # create instance of new invoice with pdf in buffer as its pdf file i = Invoice.create(buffer) # save instance of model i.save() models.py class Invoice(models.Model): def invoice_path(self): from datetime import date file = self.pdf today = date.today() return f'invoices/{today}/'+file @classmethod def create(cls, file): invoice = cls(pdf = file) return invoice pdf = models.FileField(upload_to=invoice_path) created_date = models.DateField(auto_now=True) -
Is there a canonical design pattern for an in-memory filter in either Django or Django Rest Framework?
Is there a canonical design pattern for an in-memory filter in either Django or Django Rest Framework? For example, does Django have a way to filter a queryset using a lambda? Or does Django Rest Framework have a Viewset method that can be overridden to filter query results? Neither get_queryset nor filter_queryset seem to be appropriate places to do that, because they both return a queryset. In contrast, an in-memory filter would be accepting the list of query results as input, and returning a filtered subset of the input list. Perhaps the Viewset's list() method could be overridden for that purpose, but it's not ideal, because then the default ListModelMixin's implementation would need to be duplicated. Alternatively, filtering in the serializer get_representation method or data property also doesn't seem ideal, because it would mean doing the work to serializing results that then get dropped. -
How to use id as file name in django base template
I have a base file in my django template and it has an image in my nav that of the employee: <img src="{% static 'assets/dist/img/employee/'1.jpg' %}" class="rounded-circle" width="50" height="50" alt="user"></a> And i need that 1.jpg received {{user.employee.id}} but i can't concat .. i try this but not work: <img src="{% static 'assets/dist/img/employee/'|add:{{user.employee.id}}|add:'.jpg' %}" class="rounded-circle" width="50" height="50" alt="user"></a> -
Apply filter to search in django
I want to search a user name in the database and list all the results of the search in another page. In this page, on the listed results, I want to apply some filtering. It sounds like a simple thing to do but I am having difficulties. I am using django-filters. in the home.html I have my search <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> </head> <body> <form action = {% url 'users:index' %} method="get"> {% csrf_token %} <div class="d-flex justify-content-center"> <div> <input class="form-control" type="text" name="search" placeholder="Search a user..."> </div> <div> <button class="btn btn-dark" type="submit" name="action">Search</button> </div> </div> </form> </body> </html> The results are listed in index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Users App</title> </head> <body> <form method="GET"> {{ filter.form }} <button type="submit" >Search</button> </form> {% if filter.qs %} <ul> {% for user in filter.qs %} <li><a href="{% url 'users:detail' user.id %}">{{ user.name }}, {{ user.nationality }}</a></li> {% endfor %} </ul> {% else %} <p>No users available.</p> {% endif %} </body> </html> now if I try to apply the filter off filter.form I get the error Cannot use None as a query value. Here are the views.py: # Create your views here. def home(request): return render(request, 'users/home.html') … -
How to dockerize a django app with nginx and gunicorn using supervisor
I have a dockerized project built with django and nginx. The app runs gunicorn to serve the python project and nginx to serve static files. The problem was that nginx serves the assets in a different port and this is not suitable for production nor testing specially if I am running my projects with Kong and Konga and I need to run the app in the port 8010. To face this problem I tried to implement supervisor but I haven't been able to make it run properly. This the project structure: blacklist/ asgi.py settings.py urls.py wsgi.py blacklist_app/ controllers/ migrations/ templates/ uploaded_files/ urls.py models.py views.py etc (app's files) config/ nginx/ nginx.conf uwsgi/ uwsgi.ini supervisor/ supervisord.conf docker-compose.yml Dockerfile manage.py requirements.txt #docker-compose.yml version: '3' services: web: container_name: subida-excel build: . command: gunicorn -w 10 --timeout 86400 -b 0.0.0.0:8011 blacklist.wsgi volumes: - ./db.sqlite3:/code/db.sqlite3 ports: - "8010:8010" networks: - kong-net environment: - ALLOWED_HOST=${SUBIDAEXCEL_HOSTS} - DEBUG=${SUBIDAEXCEL_DEBUG} - BASE=${SUBIDAEXCEL_URLBASE} networks: kong-net: external: true volumes: db.sqlite3: #/config/uwsgi.ini [uwsgi] socket = 127.0.0.1:8011 chown = www-data:www-data uid = www-data gid = www-data chdir = /code/ processes = 4 threads = 2 wsgi-file = /code/blacklist/wsgi.py #/config/nginx/nginx.conf server { listen 8010; server_name _; location /static { alias /code/assets/; try_files $uri $uri/ =404; … -
Combining ListView and DetailView
I need your help please. I need to combine a ListView and a DetailView in a single template. I have list items appearing on the left and so I want when someone clicks one of the list item, the details should show on the left. Picture is here of what I want to achieve views.py class RequestDetail(LoginRequiredMixin, DetailView): model = Request fields = ['content', 'author_group', 'assign_to', 'ref_code'] template_name = 'request/request_detail.html' def in_requests_progress(request): context = { 'in_requests_in_progress': Request.objects.filter(assign_to=request.user.profile.department).filter(status='Progress') } return render(request, 'request/in_inprogress.html', context)