Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to config webpack entry and output path for multiple files in different apps of Django project
I am having the following Django project structure. PROJECTROOT βββ package.json βββ package-lock.json βββ Pipfile βββ Pipfile.lock β βββ DJANGOROOT β βββ db.sqlite3 β βββ DJANGOROOT β β βββ __init__.py β β βββ settings.py β β βββ urls.py β β βββ wsgi.py β βββ manage.py β β βββ APP_XYZ <-- app β β βββ admin.py β β βββ apps.py β β βββ __init__.py β β βββ migrations β β β βββ __init__.py β β βββ models.py β β βββ static <-- app static files β β β βββ APP_XYZ β β β βββ bundles β β β β βββ ANYNAME1-90dfdbd133f2c98a5365.js β β β β βββ ANYNAME2-90dfdbd133f2c98a5365.js β β β βββ js β β β βββ ANYNAME1.js β β β βββ ANYNAME2.js β β βββ templates <-- app template files β β β βββ APP_XYZ β β β βββ ANYNAME1.html β β β βββ ANYNAME2.html β β βββ tests.py β β βββ urls.py β β βββ views.py β βββ webpack-stats.json βββ webpack.config.js APP_XYZ can be any app in the django. I have created the following folder structure to work with webpack and reactjs: PROJECTROOT/DJANGOROOT/APP_XYZ/static/APP_XYZ/js/ -- to have the source js for reactjs code PROJECTROOT/DJANGOROOT/APP_XYZ/static/APP_XYZ/bundles/ -- to have the bundled js If β¦ -
Best way to run task on Windows from web server on Linux
I have a task written in Python with a 1-2 minute run-time that I want to run on-demand. The requests would come In very small volumes from a Django server on Linux. The return would be a file. Usually, I'd use a queue system like Celery. But, this task can only be run on Windows. What is the best way to make this happen? Remotely execute the task by establishing an SSH session? Still use Celery, go through a lot of workarounds to get it to work on Windows (seems messy)? -
DRF: How to add authentication and permissions info from class-based views into autogenerated documentation?
In Django Rest Framework you can simply generate documentation: https://www.django-rest-framework.org/topics/documenting-your-api/#documenting-your-api from rest_framework.documentation import include_docs_urls urlpatterns = [ ... url(r'^docs/', include_docs_urls(title='My API title')) ] Autogenerated documentation has request body nicely generated from serializer, nice documentation from docs but how to add authentication and permission classes information? Some of my class-based views have custom authentication_classes and permission_classes and how to display information about them? -
How to do if imports if multiple settings files
I have three settings files in a django project, so for example in my wsgi file I can do: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings_staging') But then my question is, how would I do imports everywhere else in the project? For example: from settings import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY This wouldn't be from "settings" anymore, but from "settings_staging". -
How to convert a WebSocket connection into a SockJS connection
I have a python server that is accepting a websocket connection and returning information. Here is how I connect with normal websockets: new WebSocket('ws://localhost:8000/ws/registration/None/info?t=1539140761696') I'd like to use SockJS to do the connect, and I'm trying to do the following: new SockJS('http://localhost:8000/ws/registration/None/info?t=1539140761696') 404 (Not Found) How would I route these 'socket urls' to the correct endpoint -- that is, so that they go to the ws: endpoint? -
Preventing Django table creation from migrations to Readonly Databases
I have a legacy database that I connected my Django app to. The user I connected to the database only has read access and this holds when trying to make any changes through the Django shell. My issue lies in the fact that after running my migration, Django created a few tables within the database: django_migrations, django_admin_log, auth_group, auth_user, etc Is there a way to connect to my database so that Django doesnt create these tables? The only thing I want Django to do is be able to pull information from it, not make any changes. I am using Django 2. -
Allow Django user to create another one
first of all, I'm a beginner. I'm creating a website for my family to trade presents on Christmas. Everyone can post gifts ideas for everyone. I'd like to allow parents to create an account for their children and be able to manage them. E.g. rename, delete, change profile picture... I have a profile model linked to User... I was thinking of creating a child model...? But I'm stuck. -
Django using URL parameters to query database in class-based view
I have a form which when submitted goes to a results page where the URL would be for example: appname/results/?make=BMW I want to use the URL parameters to query database and display the results on that page. This is the code I have so far: views class SearchView(FormView): template_name = 'carproject/search.html' def get(self, request, *args, **kwargs): form = AdvancedSearch(self.request.GET or None) context = {'form': form} if form.is_valid(): return render(request, 'carproject/results.html') else: return render(request, self.template_name, context) class ResultsView(TemplateView): template_name = 'carproject/results.html' def get_queryset(self, request, *args, **kwargs): make = self.request.GET.get('make') results = Vehicles.objects.filter(makename__icontains='make') context = {'results': results} return render(request, self.template_name, context) HTML <table> {% for item in results%} <tr> <td>{{item.makename}}</td> <td>{{item.model}}</td> <td>{{item.seriesname}}</td> <td>{{item.seatingcapacity}}</td> <td>{{item.pricenew}}</td> </tr> {% endfor %} </table> -
Using formsets with formwizard and django-dynamic-formset (jquery)
from layout.html <script src="{% static 'resumes/js/jquery.formset.js' %}"></script> <script type="text/javascript"> $(function() { $('.formset').formset(); }) from views.py FORMS = [('resumes', ResumeForm), ('work_experience', WorkExperienceForm), ('certifications', CertificationForm), ('education', EducationForm), ('skills', SkillFormSet), ('languages', LanguageForm), ] class ResumeWizard(LoginRequiredMixin, SessionWizardView): login_url = '/login/' def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): return HttpResponseRedirect(reverse('resumes:my-resumes')) from forms.py class SkillForm(ModelForm): class Meta: model = Skill fields = ['name', 'competency', ] widgets = {'competency': forms.Select(choices=COMPETENCY_CHOICES, attrs={'class': 'form-control'}), } SkillFormSet = formset_factory(SkillForm, extra=2, max_num=4) django-dynamic-formset can be found here: [https://github.com/elo80ka/django-dynamic-formset] Hi! I'm trying to implement a dynamic form using form wizard, formsets and django-dynamic-formset (jquery plugin). I am having trouble putting it all together. For a certain step, I want my user to be able to add more forms but after a max number of forms, I would like to stop allowing the user to add forms. I have added max_num = 4 to the formset_factory but this doesn't seem to do the trick. I have replicated this and got it to work with a custom formset that I pass into context by overriding the get_context_data method of the Wizard view and change the form management. However, when I pass this current formset as it is, I am unable to get a β¦ -
Creating super user in django python
I have a problem when creating super user in django : I can't understand what. Please help me ! Thank you -
How to call a django queryset using a string?
Lets say I want to run this query on a model called Person: person = Person.objects.get(pk=1) I want to run it using a string. Something like this: person = getattr(Person, 'objects.get(pk=1)')() This does not work, but hopefully it clearly conveys the idea. I know I can just run eval, but its apparently dangerous. What is the safest way to do this? -
Debugging QuerySets in Django
When in debug mode and looking at a QuerySet that did return results, how / where can I see the objects in the debugger? I am not interested in the code to evaluate (e.g. Class.objects.all() etc, but more like the structure, e.g.: - QuerySet -- object_list --- object[0] --- object[1] --- object[n] Thanks! -
Docker - Communication failure between containers on same network
I'm deploying an Angular - Django app on a Digital Ocean droplet. It's composed of 3 Docker containers: cards_front: the Angular front-end cards_api: the django rest framework back-end cards_db: the postgres database They're all on the same network: [ { "Name": "ivan_cards_api_network", "Id": "ddbd3524e02a7c918f6e09851731e015fdb7e8647358c5ed0c4cd949cf651fd9", "Created": "2018-10-09T23:44:33.293036243Z", "Scope": "local", "Driver": "bridge", "EnableIPv6": false, "IPAM": { "Driver": "default", "Options": null, "Config": [ { "Subnet": "172.22.0.0/16", "Gateway": "172.22.0.1" } ] }, "Internal": false, "Attachable": true, "Ingress": false, "ConfigFrom": { "Network": "" }, "ConfigOnly": false, "Containers": { "0d3144b27eaf6d7320357b6d703566e489f672b09b61dba0caf311c6e1c4711c": { "Name": "cards_front", "EndpointID": "47b1f8f42c4d18afeafeb9da502fd0197e726f29bd6d3d3c2960b44737bd579a", "MacAddress": "02:42:ac:16:00:04", "IPv4Address": "172.22.0.4/16", "IPv6Address": "" }, "3e9233f4bfc023632aaf13a146d1a50f75b4944503d9f226cf81140e92ccb532": { "Name": "cards_api", "EndpointID": "34d4780dc6f907a8cb9621223d6effe0a0aac1662d5272ae4a5104ba7f3808c4", "MacAddress": "02:42:ac:16:00:03", "IPv4Address": "172.22.0.3/16", "IPv6Address": "" }, "e5e208a20523c2d41433b850dc64db175de8ee7d0d156e2917c12fd8ebdf97ab": { "Name": "cards_db", "EndpointID": "8a8f44bbcdf2f95e716e2763e33bed31e1d2bdbfae7f6d78c8dee33de426a7ef", "MacAddress": "02:42:ac:16:00:02", "IPv4Address": "172.22.0.2/16", "IPv6Address": "" } }, "Options": {}, "Labels": { "com.docker.compose.network": "cards_api_network", "com.docker.compose.project": "ivan", "com.docker.compose.version": "1.22.0" } } ALLOWED_HOSTS on django settings is set to ['*'] When I try the app on the browser I get: GET http://localhost:8000/themes net::ERR_CONNECTION_RESET But if I do a curl localhost:8000/themes from inside the DO droplet I get a response. I know there's something missing on the network configuration, but I can't figure out what it is. Thank you -
Django migrate error _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax
TL;DR: python versions conflicts, i think that the python i downloaded and compiled (3.6) can't use this package (libmysqlclient-dev) to make migrations to mysql. only the system's default python (3.4) can. my ubuntu server came with python 3.4, all of my django work and other work depend on 3.6. i have learned that upgrading system python is a bad idea, so i compiled python 3.6 (with altinstall). when i ran python3.6 manage.py migrate it gave me this mysql error: _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) NOT NULL)' at line 1") i tried virtual environment and normal python 3.6, both gave the same error, and i made sure that libmysqlclient-dev and mysqlclient are installed. as this answer suggests, the problem is with libmysqlclient-dev because it's installed via apt-get not pip so i guess it's only compatible with the default python (3.4 that came with the system) or my compiled python 3.6 isn't allowed to use it, because when i made a dummy django project with python3.4 (system's default) and attempted python3.6 manage.py migrate on the same mysql database with β¦ -
Django Admin Form: Set the default value of a readonly field
THE GOAL: Display a request-specific, read-only user_id on a django admin form when creating and updating a resource. This display should be a readonly field (readonly, NOT disabled). The user_id displayed is derived from the requesting user (request.user) so the initial value is set from that. Following this post, we should simply set it in the get_form method like so: def get_form(self, request, obj=None, *args, **kwargs): form = super(ProfileAdmin, self).get_form(request, *args, **kwargs) form.base_fields['user'].initial = request.user return form However, user is no longer on the base_fields when it is readonly. In fact, I can't find it anywhere. Any thoughts? Other posts suggest on save, which I intend to do, but I need it to show on the form before then. -
How do I filter by occurrences count in another table in Django?
Here are my models: class Zoo(TimeStampedModel): id = models.AutoField(primary_key=True) class Animal(models.Model): id = models.AutoField(primary_key=True) zoo = models.ForeignKey(Zoo, on_delete=models.PROTECT, related_name='diffbot_results') I would like to run a query like this: Zoo.objects.filter("WHERE zoo.id IN (select zoo_id from animal_table having count(*) > 10 group by zoo_id)") -
Docker WindowsServerCore running Django/Python extremely slow
Running a python docker image based off of Windows Server Core-LTSC 2016. Within the application is a Django web api we've created. Calls to routes that don't exist seem to work fine. This application works perfectly fine and returns results in under 50ms when running locally on my machine (no docker container). When calling my service and passing in 132KB of JSON data, the service completely hangs. We've found that reducing the amount of JSON sending in will allow the web api to respond successfully. But it still takes a couple of seconds to process the request. Here's the command I'm using to build: docker build -t mysvc-1.0 . Here's the command I'm using to run: docker run -it --rm --name vsvc -p 12000:8000 mysvc-1.0 Here's my dockerfile: FROM python:3.6.6-windowsservercore-ltsc2016 ENV PYTHONUNBUFFERED 1 RUN mkdir TEMP ENV PATH="C:/python/Scripts;C:/python;${PATH}" RUN mkdir C:/app WORKDIR C:/app ADD ./ C:/app # Update pip RUN python -m pip install --upgrade pip RUN pip install -r requirements.txt RUN python manage.py makemigrations pharmid_app RUN python manage.py migrate EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I've tried setting the memory and CPU count, neither fixed the issue. Am I missing something? -
Send Reminder Email using Django
I have a model of student with event date time and student's email field. I want to send a reminder email 12hours before event time to student's email. What are the ways to achieve this? -
Gunicorn can't start
Ok, I'm trying to run a django app with gunicorn, but nothing seems to make it work, my app folder structure looks like this: /home/web/app/ appenv/ dtest/ static/ db.sqlite3 manage.py appenv contains my virtual environment and inside dtest I have the file wsgi.py which contains: import os import sys sys.path.append('/home/web/app/dtest') sys.path.append('/home/web/app') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dtest.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Then I try to run gunicorn like this: gunicorn wsgi.py -b 0.0.0.0:9999 But I get the error: [2018-10-09 17:37:46 -0500] [15177] [INFO] Starting gunicorn 19.9.0 [2018-10-09 17:37:46 -0500] [15177] [INFO] Listening at: http://0.0.0.0:9999 (15177) [2018-10-09 17:37:46 -0500] [15177] [INFO] Using worker: sync [2018-10-09 17:37:46 -0500] [15180] [INFO] Booting worker with pid: 15180 [2018-10-09 22:37:49 +0000] [15180] [ERROR] Exception in worker process Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked AttributeError: 'module' object has no attribute '__path__' Then gunicorn dies ... It must be something in the way my module is getting imported but Im not sure exactly what is it (maybe modifying sys.modules?) Im using Django version 2.0.9, gunicorn (version 19.9.0), Python 3.4.2 on dietpi (debian 8 Jessie). [By the way, running python manage.py runserver works just fine] -
Django Templates Inclusion / Blocks
I have the following template structure: base.html detail.html extending base.html list.html extending base.html Now, I have implemented a filter panel which is invoked by a button using onclick="filter_open()". The respective method is in an external JS file and basically opens a side panel: function filter_open() { document.getElementById("filtersidebar").style.display = "block"; document.getElementById("filtersidebar-outer").classList.add("fc-filters-overlay"); } This filter, I want to make available on detail.html and list.html. So, I created a new file 'filter.html'. Both, the 'detail.html' and the 'list.html' have a {% block filter %}{% endblock %} and in 'filter.html' I add the functionality within the respective Django blocks. The button however, now throws an error: Uncaught TypeError: Cannot read property 'style' of null at filter_open (main.js:146) at HTMLButtonElement.onclick ((index):158) I guess this is because I moved the filter to 'filter.html'. Any ideas? -
Why is DRF browsable API running permission checks on multiple request types for every actual request?
I have a simple DRF list view and wanted to write some permissions pertaining to POST requests. That resulted in an error when GET requests were issued. That led me to realize that my permission class is being called multiple times on requests that were not submitted. Here are my files. permissons.py: class IsDummy(permissions.BasePermission): def has_permission(self, request, view): print("\n{}\n".format(request.method)) if request.method in permissions.SAFE_METHODS: return True return False views.py: class UserListView(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsDummy] The issue only happens when I submit a request from my browser on the browsable api. When I submit a GET request at the list url I get the following printed to the terminal from the print statement in the IsDummy permission class: GET POST POST OPTIONS When I submit a GET or OPTIONS request through postman I see the single, appropriate, request method that I actually used. It seems that the first method listed is always the actual method that I used, I have no idea where the extra POSTs and the OPTION are coming from. The even stranger part is that the page will load fine after all of this even though the POST requests should clearly be resulting β¦ -
django celery beat arguments with imported class functions from another library
I'm trying to get a function to work in my django project with celerybeat that imports a class based function from a wrapper library. I've been reading that celery doesn't work with classes too easily. my function login_mb doesn't take an argument but when I try register and call this task I get an error Couldn't apply scheduled task login_mb: login_mb() takes 0 positional arguments but 1 was given Is this because of self in the wrapper function imported? What could I do to get this to work with celerybeat? settings.py CELERY_BEAT_SCHEDULE = { 'login_mb': { 'task': 'backend.tasks.login_mb', 'schedule': timedelta(minutes=30), } , tasks.py from matchbook.apiclient import APIClient import logging from celery import task log = logging.getLogger(__name__) @shared_task(bind=True) def login_mb(): mb = APIClient('abc', '123') mb.login() mb.keep_alive() apiclient.py (wrapper library) from matchbook.baseclient import BaseClient from matchbook import endpoints class APIClient(BaseClient): def __init__(self, username, password=None): super(APIClient, self).__init__(username, password) self.login = endpoints.Login(self) self.keep_alive = endpoints.KeepAlive(self) self.logout = endpoints.Logout(self) self.betting = endpoints.Betting(self) self.account = endpoints.Account(self) self.market_data = endpoints.MarketData(self) self.reference_data = endpoints.ReferenceData(self) self.reporting = endpoints.Reporting(self) def __repr__(self): return '<APIClient [%s]>' % self.username def __str__(self): return 'APIClient' -
querying a CSV column that might contain any of the following F,M,T,S,U,X in Django
Before I create a separate model, I was wondering if it is possible to query such a model in Django 2.0? My model is like this: class Block(models.Model): kind=models.CharField() where kind can hold at least one of the options F,M,T,S,U,X I don't want to create them as boolean columns. For now, the way to go is to create another model: class BlockModel(models.Model): kind=models.CharField() block=Models.ForgienKey(Block) but since the CSV list is not big nor complex, I am thinking of storing as CSV but how would I query say for Blocks at that contain F or X? -
NoReverseMatch: Reverse for 'add_solution' with arguments '('',)' not found. 1 pattern(s) tried: ['share/(?P<pk>\\d+)/add_solution/$']
The point is, i have exercises + solutions And when i click on execsise there is add solution button,but... I'm getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'add_solution' with arguments '('',)' not found. 1 pattern(s) tried: ['share/(?P<pk>\\d+)/add_solution/$'] my urls.py: re_path(r'^(?P<pk>\d+)/add_solution/$', views.add_solution, name='add_solution'), My view: def add_solution(request, pk = None): if request.method == "POST": form = ShareForm(request.POST) if form.is_valid(): form.save() return redirect('Share:show_code') else: form = ShareForm() return render(request, 'share/add_solution.html', {'form': form}) my template: <form method="post" action="{% url 'Share:add_solution' pk%}"> {% csrf_token %} <button class="btn btn-success px-5">Add solution</button> </form> If i remove (?P\d+) from url, ir works, but i need to specify the exercise manually. But i want to get the id of exercise from url and autofill the exercise fill while adding solution. Thank you in advance. -
Retrieve tags used last month with number of times used (django-taggit)
I'm trying to retrieve the tags used last month with the number of times used (also last month) from django-taggit in order to create a tag cloud. The time filter is important for esthetic reasons. Looking at the django-taggit model it appears it doesn't include dates of any kind, so my approach has been to filter my model (Link) by date, and then retrieve all tags associated with the filtered Links. # filter links submitted last month last_month = datetime.today() - timedelta(days=30) links_ids = Link.objects.filter(date__gte=last_month) # retrieve TaggedItem objects related to those links tagged_item = TaggedItem.objects.filter(object_id__in=links_ids) # finally get Tag names related to TaggedItem tag_ids = tagged_item.values_list('tag_id', flat=True) # get tags tags = Tag.objects.filter(id__in=tag_ids).order_by('name') # annotate by num_times tags = tags.annotate(num_times=Count('taggit_taggeditem_items')) return tags With this approach I'm able to filter only tags used last month, but then to calculate num_times used it call to the whole 'taggit_taggeditem' table, so it gives me the num_times used at ALL TIMES, now could I get the num_times used for the last month ONLY?