Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django & ReactJS no template rendered
Already 24 hours and still can't figure out, template not being rendered whenI browse 127.0.0.1:8000 or localhost:8000 in my browser. I configured this with react js as my frontend please see my path in the picture. I am printing in my views and it shows in my terminal, but when in the browser, I can't see my template, only blank page. settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'webpack_loader', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, "templates") ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', # end with slash 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-local.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, } } STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'app/static'), ] urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('app.urls')), ] **urls.py ** [inside app folder] from django.conf.urls import url, include from .views import * urlpatterns = [ url(r'^$', homePage, name = 'home_page'), ] views.py from django.shortcuts import render def homePage(request): # landing page context = {} template = 'base.html' print('testing terminal') #this comment in termninal is printing when I … -
How to fail any Django REST Framework requests with unknown parameters?
Django REST Framework API ignores any unknown parameters. This has led to several issues. For example, when a model filter was missing, a client received all records rather than the single one they were expecting. How can I force DRF to return 400 Bad Request whenever an API call includes an unknown parameter? -
How are my Heroku web dynos executing code outside of a standard HTTP request loop?
I'm running a Django application on Heroku with logging via Papertrail. I'm seeing a peculiar phenomenon in my Papertrail logs where web dynos are executing code outside of the regular HTTP request/response loop. To explain further, I have a function that is highly resource intensive and takes much longer than 30 seconds. This function isn't triggered inside any Django view handler. However, the papertrail logs from my web dynos clearly show that this function is being executed. I'm confident that this function isn't being triggered by an actual HTTP request because: 1) I've thoroughly code reviewed the URL's that were called up to 30s prior to these logs and none of them call this function 2) The function executes for much longer than 30s. If it was being called from within a HTTP request, it would have terminated with a H12 timeout error. How is this possible? I've pasted my Procfile below in case it helps add context. web: gunicorn -t 6000 project.wsgi --log-file - worker: python -u manage.py rqworker queue_name worker-hp: python -u manage.py rqworker queue_name2 clock: python clock.py -
How do i create seperate tasks for every objects with celery beat in Django models
Let's assume we have following model field: class Project(models.Model): project_name = models.CharField(max_length=200,unique=True) project_scan = models.IntegerField() ### Scan interval project_status = models.BooleanField() ### To Enable "Scan" or Disable "Scan" Tasks Assume We have 2 Project Objects: 1. Project(project_name='test1',project_scan=5) ### Scan `test1` every `5` hour 2. Project(project_name='test2',project_scan=10) ### Scan `test2` every `10` hour Tasks.py @task(name='project_tasks') def Project_Tasks(): get_all_projects = Project.objects.all() for each_project in get_all_project: if each_project.project_status == True: ### Checking if it "Scan" is allowed. get_interval = each_project.project_scan get_name = each_project.project_name print(get_name) My Question : How do i run tasks on each object based on given project_scan Interval ? , Since Celery beat takes Tasks name as argument to perform scan like: PeriodicTask.objects.create(interval=given_interval, name='I dont know', task='project_tasks', ) How do i create separate instance for each project task ? I Tried creating intervalSchedule field in models.py but didn't worked: class Project(models.Model): project_name = models.CharField(max_length=200,unique=True) project_scan = models.IntegerField() ### Scan interval project_status = models.BooleanField() ### To Enable "Scan" or Disable "Scan" Tasks schedule = IntervalSchedule() -
How to set dynamic page_size in DRF PageNumberPagination
In class PostByFilters, I'm getting limit as a url parameter, and I want to assign the value into page_size in class BasicSizePagination. I tried to use global variable outside of the two classes, but it didn't work. Is there anyway reinitialize the BasicSizePagination in PostByFilters so that I can directly assign the value in PostByFilters? class BasicSizePagination(pagination.PageNumberPagination): page_size = 10 class PostByFilters(ListAPIView): serializer_class = serializers.PostSerializer pagination_class = BasicSizePagination def get_queryset(self): limit = self.request.query_params.get('limit', None) ... return queryset -
How To Build a DRY Image Gallery - in Django
I've been tinkering with a small image gallery for my project for a few days now, but I feel that I'm not going about it in a very pythonic manner thus far in terms of this part of the project. A lot of questions have risen during the tinkering, alas being new to python and django I cannot immediately see how I ought to go about improving what I'd like to improve in the code. Here's the user profile model; I reckon it will sort of jump at you what I mean: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from PIL import Image, ImageOps from ckeditor_uploader.fields import RichTextUploadingField class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_visible = models.BooleanField(null=True) activation_key = models.CharField(max_length=120, blank=True, null=True) name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') slogan = models.CharField(max_length=250, blank=True, null=True) bio = RichTextUploadingField( external_plugin_resources=[( 'youtube', '/static/ckeditor/ckeditor/plugins/youtube/', 'plugin.js' )], blank=True, null=True, ) phone = models.CharField(max_length=20, blank=True, null=True) reddit = models.CharField(max_length=30, blank=True, null=True) facebook = models.CharField(max_length=30, blank=True, null=True) twitter = models.CharField(max_length=30, blank=True, null=True) youtube = models.CharField(max_length=30, blank=True, null=True) linkdin = models.CharField(max_length=30, blank=True, null=True) img_1 = models.ImageField(default='default.jpg', upload_to='images') img_2 = models.ImageField(default='default.jpg', upload_to='images') img_3 … -
Acces data from other table - Foreign Key in Django Rest Api - Unknown column
I created Django Rest Models from existing MySQL database with inspectdb. I have two models, and I want to access some data from other model. My models: class Impreza(models.Model): year = models.IntegerField() tytul = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = '2006_impreza' class Description(models.Model): year = models.IntegerField() year_id = models.IntegerField() id_imprezy = models.IntegerField(blank=True, primary_key=True) class Meta: managed = False db_table = '2006_description' My serializer: class ImprezaSerializer(serializers.ModelSerializer): desc = serializers.StringRelatedField(many=True) class Meta: model = Impreza fields = ('year', 'tytul', 'desc') My problem is that Django is searching for id named 'impreza_id', but it exists with other name - 'id_imprezy'. As you can see, I tried to give 'id_imprezy' a 'primary_key=True' to tell Django that this is the right name but it doesn't work. It still gives me error: (1054, "Unknown column '2006_description.impreza_id' in 'field list'"). In my database both tables have id, but it doesn't show up in the model. I read that Django isn't showing id columns in models. How can I do it right? How to add foreign key? Sorry, but I'm realy new to Django ;-) -
How add photo encodings to db with django?
I try but it doesn't work... My model: class Staff(models.Model): photo = models.FileField() encodings = models.TextField() def get_encodings(self): enc = face_recognition.face_encodings(self.photo) return enc def save(self, *args, **kwargs): self.encodings = self.get_encodings() super(Staff, self).save(*args, **kwargs) The error which i have when try to add new object __call__(): incompatible function arguments. The following argument types are supported: 1. (self: dlib.fhog_object_detector, image: array, upsample_num_times: int=0) -> dlib.rectangles Invoked with: <dlib.fhog_object_detector object at 0x0000023D8CD9E570>, <FieldFile: photo_2018-12-05_23-09-20.jpg>, 1 -
Successful saving in post_ajax with status code 200 but not save on django database
I would like to ask if what’s wrong if your application returns status code 200 then it won’t saved on backend. Here’s the code of the CBV. def post_ajax(self, request, *args, **kwargs): ..... if fetch_pk: form = SomeForm(data=self.request.post()) else: form = SomeForm(data=self.request.post(), instance=fetch_pk if form.is_valid(): fetcher = form.save() #throws json response I tried to print self.request.post() the data is coming through and status is okay but the problem is it is not saved. And there’s no error being thrown. Thanks in advance -
Django logging only works when restart
I've asked a similar questions before, but having trouble getting more information on what the problem is. I have a Django app, and its running with channels. So, Django, Daphne, Channels, NGINX, Redis I have logging configured like this: # Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, 'level': 'INFO' }, 'dashboards': { 'handlers': ['console'], 'propagate': False, 'level': 'DEBUG', }, }, } Channels: CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, "ROUTING": "app.routing.channel_routing", }, } In my view: import logging loger = logging.getLogger(__name__) def index(request): loger.debug(":dsfasdfasdfasdfasdfasdfasdfasdfasdfasdf") return render(request, 'site/index.html', context) Using supervisor to manage service: [program:Daphne] environment=PATH="/opt/site/venv/bin" command=/opt/site/venv/bin/daphne -b 0.0.0.0 -p 8000 site.asgi:channel_layer --proxy-headers -v2 directory=/opt/site/site autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/daphne.out.log [program:Worker] environment=PATH="/opt/site/venv/bin" command=/opt/site/venv/bin/python manage.py runworker -v2 directory=/opt/site/site process_name=%(program_name)s_%(process_num)02d numprocs=10 autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/workers.out.log I can see the worker logs upon request to the page, and I can also see the exceptions hit the log (/tmp/workers.out.log). 2018-12-13 21:36:22,396 - DEBUG - worker - Got message on http.request (reply daphne.response.SrXmOkzSNt!bUdAxibnQp) 2018-12-13 21:36:22,396 - DEBUG - runworker - http.request 2018-12-13 21:36:22,397 - DEBUG - worker - Dispatching message on http.request to channels.staticfiles.StaticFilesConsumer … -
How to get multiple values from joined tables
How can I get all the laws from all the courses that an specific user is subscribed? class Law(models.Model): name = models.CharField('Nome', max_length=100) slug = models.SlugField('Atalho') description = models.TextField('Description', blank = True, null=True) class Course(models.Model): name = models.CharField('Nome', max_length=100) slug = models.SlugField('Atalho') description = models.TextField('Descrição', blank = True, null=True) laws = models.ManyToManyField(Law, related_name='law_course') class Subscription(models.Model): STATUS_CHOICES=( ( (0, 'Pendente'), (1, 'Approved'), (2, 'Canceled'), ) ) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, verbose_name="Usuário", related_name="inscricao") #inscricao é criado no usuario course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name="Course", related_name="subscription") status = models.IntegerField( 'Status', choices=STATUS_CHOICES, default = 0, blank=True ) class Meta: unique_together = (('user','course')) So, the user can be subscribed in one or more courses. Each course has one or many laws. I have a page that I need to list all the laws of each course that an specific user is subscribed if the subscription is Approved (status = 1). Example: The user John has subscribed in 2 courses: Course A and Course B. Course A laws: law1, law2, law3 Course B laws: law1, law20, law30 So, when John is logged in, I need to show the laws of the courses and the name of the course: law1 - Course A, Course B law2 - Course A … -
Deploying Django to AWS; static files for dummies
I am utterly lost on one of the last steps of this project. So far, I've been able to develop a django app that works the way I want it to on localhost; I've been able to deploy the website to AWS EC2, but I must be missing something fundamental about serving the static files. (I haven't even tried media files yet.) I've read the Django Deployment page and How-To manage static files, but I have never deployed a website from scratch before. The tutorials I've found seem to be contradicting (or outdated?). Here are the questions I think I have at this time: Do I need to host static (and/or media) files in a bucket, or is this merely a good idea? When I set up STATIC_ROOT and STATIC_URL, should I have a STATICFILE_DIRS setup? (I mean, I think I really need a tutorial on how they even go together, their settings, and how 'static' works in the templates.) I've tried to get whitenoise going; I get a message that STATIC_URL isn't set up correctly; I can't find the documentation to tell me what it should be. Is this a viable root to take? -
Django Channels windowsSelectorEventLoop object has no attribute 'create_future'
I am now using Django Channels for WebSockets and it requires the use of Redis. I download the frontend and backend from here: https://revs.runtime-revolution.com/a-simple-real-time-chat-with-django-channels-and-react-b73edc3a79f2 However, I constantly have the error of '_WindowsSelectorEventLoop' object has no attribute 'create_future'. I am using Python 3.5, Django 2.1, Windows 7, Redis 2.4. It this because the redis version compatible on Window 7 is too old or because of sth. else? -
Django plus jQuery Ajax: can't add csrf_token to form when preventing default, adding data, and resubmitting
This is the first time i post, i hope i do it correctly. I spent days on this issue and it seems i just can't find a solution. I need to add data to a form before submitting. The data i'm adding is a bit complex so it has to go into a JSON object (it includes characteristic of a previously drawn polygon on the same page). The html looks like this: <form id="form-submit-data" action="{% url 'app_name:submit-data' %}" method="POST"> {% csrf_token %} <input type="text" id="input-value" name="my-value"> <input type="submit" value="Confirm"> </form> After days of digging i settled for the below implementation (it comes from Cory Danielson's reply with 61 votes posted here: How to trigger an event after using event.preventDefault() ). The problem is that if i add the decorator @csrf_exempt in my views function my form gets submitted twice, once with the data formatted correctly and once it looks like this "csrfmiddlewaretoken=2cYsUn5m50RU1oFwOjPsGpCY5HBelIjQPOOV52KoTpQMWE2zRPzwsDA0UKrI7ZFj&my-value=35": If i do try to add the csrf_token to the post request (and commenting out the decorator in my views function) i first get a "Forbidden (CSRF token missing or incorrect.)" 403 error and when i refresh i get "code 400, message Bad request syntax (' {[my data … -
Accessing django website hosted on vm with mobile device
I run my django website with python manage.py runserver 0.0.0.0:8080 on Vagrant which is set up to forward 8080 port to 8081 on host machine. I'm able to access this website on host by going to it's local ip (192.168.X.X) but can't on mobile device (of course also by going into it's local ip). Any idea? All I could find about this is to run server with 0.0.0.0 what is already happening in my case. -
How to use Webtorrent.io to play a video in HTML?
I got a torrent link in for a movie that im trying to play on a web page but im confushed how i actually use webtorrent.io. The code below is something ive copied for testing purposes, how would i use the script/Play the video in the "Vid" Tag? <!DOCTYPE html> <html lang="en" dir="ltr"> <head> </head> <body> <div class="Vid"> #I want to use the script here </div> <script type="text/javascript"> var client = new WebTorrent() var torrentId = 'magnet:?xt=urn:btih:6268ABCCB049444BEE76813177AA46643A7ADA88&tr=udp://glotorrents.pw:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://torrent.gresille.org:80/announce&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://tracker.leechers-paradise.org:6969&tr=udp://p4p.arenabg.ch:1337&tr=udp://tracker.internetwarriors.net:1337&tr=wss%3A%2F%2Ftracker.webtorrent.io' client.add(torrentId, function (torrent) { var file = torrent.files[0] file.appendTo('body') // append the file to the DOM }) </script> </body> </html> -
Modeling a restaurant menu with django
I am creating a website with a collection of menus from restaurants in my town (since none of them seem to be on grubhub or the internet). I am having trouble creating a model for this. As you know every restaurant menu has sections(I.e Appetizers, Chicken, Steak) and entries under each section(I.e under Appetizers: Mozzarella Sticks, Nachos, etc.) I am trying to create a Menu model so that each section of the menu and all of its entries can automatically fill a template: <h1>{{section}}</h1> <!--I.e:"Appetizers"--> <p>{{food}} </p><!--I.e:"Mozzarella Sticks"--> <p>{{ food_details }}</p> With the above template, I can use a loop to loop through each section, then another inner loop to loop through each food and food_details belonging to that specific section, but I am not sure how to model this properly: from django.db import models class Restaurant(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) phoneNumber = models.CharField(max_length=10) def __str__(self): return "%s the place" % self.name class Menu(models.Model): restaurant = models.OneToOneField( Restaurant, on_delete=models.CASCADE, primary_key=True, ) # not sure how to build menu fields #if I do the following each menu will only have one of these fields, which will not work: section = models.CharField(max_length=50) food = models.CharField(max_length=50) food_details = models.CharField(max_length=200) How can … -
403 Forbidden CSRF verification failed. Request aborted
I got this error when i try to login in my website. I have {% csrf_token %} in my form and 'django.middleware.csrf.CsrfViewMiddleware' in my setting file. I try to run in another browser and it run without error. I was delete cache and cookies in chorm but it didn't work -
The right way to use Ajax to Update a Single field in a specific Object
Is it possible to use Ajax to Update a Single field in a Specific Object? I have an postgres table with lots of records, I want to use a jquery Ajax request to update a single field in a specific object within that table. Can that be done without replacing or reposting the entire record?. I want this (Gives me a 400 bad request error): $.ajax({ type: "POST", url: '/api/MyEndPoint/', data: { id: Specific_Record, Field_To_Update: New_Value, }, success: function(data){ console.log( 'success, server says '+data); } }); Instead of this (which works): $.ajax({ type: "POST", url: '/api/MyEndPoint/', data: { id: Specific_Record, Field_To_Update: New_Value, Field1: SameAsBefore, Field2: SameAsBefore, Field3: SameAsBefore, ... Field16: SameAsBefore, }, success: function(data){ console.log( 'success, server says '+data); } }); *Note: I'm using Django, and could easily do this update in views.py but I want to use Javascript to avoid a page refresh. Since I'm also using Django Rest Framework, would it be better for me to create a new endpoint that is specific to the field I want to update? ex: /api/DB_Table/Object_id/Field_to_Update Thanks! -
Django newbie - URL refusing to match for me..
Currently learning the ways of the Django. But stuck on the following. html <a href="{% url 'module:review' module.name area vocabs.name 'Review' %}" class="btn btn-primary btn-sm btn-block" role="button">Review</a> url.py url(r'^(?P<module_name>\w+)/(?P<area>\w+)/(?P<vocab_name>\w+)/Review$', views.review, name='review'), views.py def review(request,module_name,area,vocab_name): try: vocabObj = Vocab.objects.get(name=vocab_name) if area == 'Vocab': reviewItems = vocabObj.vocabcontent_set.all() elif area == 'Phrase': reviewItems = vocabObj.phrasecontent_set.all() except Modules.DoesNotExist: raise Http404("No Words found") return render(request, 'module/reading.html', {'reviewItems': reviewItems}) The error i'm getting NoReverseMatch at /Introduction/Vocab/ Reverse for 'review' with arguments '('Introduction', 'Vocab', 'Numbers', 'Review')' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I would appreciated getting pushed in the right direction on this Thanks -
how to add data into database in django?
I am having trouble about how to solve this problem...Please help me get out of this error...it's also printing the value and database table is already created .following is my code and error says something like Exception Value: save() missing 1 required positional argument: 'self' //This is my model.py file rom django.db import models class Reg(models.Model): name = models.CharField(max_length=20) //this is my form.py file from django import forms class RegistrationForm(forms.Form): name = forms.CharField() //this is my view.py file from django.shortcuts import render from .forms import RegistrationForm from .models import Reg def ragistration(request): if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): Reg.name = form.cleaned_data.get('name') Reg.save() print(Reg.name) else: form = RegistrationForm() return render(request, 'registration/reg.html', {"form": form}) //I got this error Exception Value: save() missing 1 required positional argument: 'self' -
Submitting request to https returns http
Heyo! So I'm creating and angular app that uses a django backend accessed as a Api. The link for my backend is https, and one of its main purposes is to act as a database for image storage. I am trying to grab the URLs in the backend by using http calls from my front end. It's not working because the GET calls only return Http urls not Https. This means that when the front end tries to access the url it can't be found :( Does anyone know how I can change my code so Https is returned or can suggest me some type of workaround? Here is my API call: export class ImageService { baseUrl = 'https://link.com'; constructor(private httpClient: HttpClient) { } getBebidas() { return this.httpClient.get(`${this.baseUrl}/bebidas`); } And this is an example of the return (an array of json objects): [{image_url: "http://link.com/image}] Any help would be greatly appreciated! -
Django - clean return needed or something like that
is there any way to return decorator (final line of post) as a clean return response? Otherwise the middleware im using get's sick about this and returns list index out of range. I subclassed the login_required function of django decorator build-in subsets. from myproject import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.shortcuts import resolve_url from urllib.parse import urlparse from functools import wraps def auth_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator def user_passes_test(test_func, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(settings.AUTH_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc … -
django static files are not copied to saticfiles folder on dicker's container
I'm trying to understand what am I doing wrong when trying to copy my static/media folder to staticfiles/medialfiles on docker. This is what I have: settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles") Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 ENV C_FORCE_ROOT true RUN mkdir /www WORKDIR /www COPY . /www/ RUN pip install -r requirements.txt RUN python3 /www/manage.py collectstatic --noinput docker-compose # use this file only for live production # docker-compose up -d web version: '3' volumes: db_psql: postgis-data: esdata: services: web: build: . restart: always container_name: django_web command: gunicorn --bind 0.0.0.0:8080 LG__CXS4.wsgi depends_on: - nginx volumes: - .:/www ports: - "8080:8080" links: - redis nginx: restart: always image: "nginx" ports: - "80:80" volumes: - ./nginx/conf.d:/etc/nginx/conf.d - ./staticfiles:/static - ./mediafiles:/media When I run my docker file I get: 5355 static files copied to '/www/staticfiles'. but when I look into the container's staticfiles -it's empty. you will note that there are 0 files and as a result the html is off. -
Django: Filtering children of children of model for use within view/template
We have the following model structure: Parent (name, slug, country, children[ManyToMany on Child]) Child (name, country, children[ManyToMany on Grandchild]) Grandchild (name, country) Now, in my view, I want to make sure we are only dealing with data for the current country (country=kwargs["country"]) at all levels. Now, I have been using the following (obfuscated code) in order to filter the children. This allows me to simply reference "children" in the template in order to access the filtered child records, however I'm having trouble determining a best-practice solution for applying this same filtering at the grandchild level. Below is an example of what is working for filtering children, but how do I perform this same filtering within the template when looping through the grandchildren? I don't want a front-end developer to have to understand the data structure - ideally, I would want them to be able to loop through children, and within that loop, loop through child.grandchildren, which will already be filtered. View class: class ParentView(DetailView): model = Parent def get_object(self): return self.model.objects.filter(slug=self.kwargs["slug"], country=self.kwargs["country"]) def get_context_data(self, **kwargs): context = super(ParentView, self).get_context_data(**kwargs) context["children"] = self.object.children.filter(country=self.country) return context Template sample: {% for child in children %} <li>{{child.name}} <ul> {# This list of grandchildren is …