Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Doc string from parent class to children class functions
I have a Django==2.2.3 app with djangorestframework==3.9.4 and django-rest-swagger==2.2.0. I wanted to have a single source of truth (for data validation as well as api-docs) for my api endpoints. I have a JSON that looks something like this { "get": { "query_param1" : { "type": "string", "required": "false", "message": "what does it do/what is it for?" }, "query_param2" : {...}, "responseMessages": { "code: 401": "Not authenticated", "code: 403": "Insufficient rights to call this procedure" } }, "delete": { "query_param1" : {...}, "query_param2" : {...}, "responseMessages": {...}, }, "put": {...}, "post": {...}, } I created a json schema from this and the validation is working. This json is converted to a yaml string which is used by django-rest-swagger. How it uses the yaml is, you need to put the yaml in the doc strings. But I don't want to go and write the same thing for every thing. There will be many endpoints and writing the same thing for all those endpoints doesn't feel right. So I figured if I make a base class and just send the json to that base class, it can create all the doc strings for me, using the json and put it dynamically to the … -
nested dictionaries in django
In python, data = { {0 : {kill : 1}}, {1 : {kill : 3}}, {2 : {kill : 8}} } for i in data: print(data[i]['kill']) print 1,3,8 nomarlly but in Django template {% for i in data %} {{ data.i.kill }} It's making error. However, using an integer instead of variable i will operate normally. like {{ data.0.kill}} I found solution in How to iterate over nested dictionaries in django templates but it have to use double for loop. is there solution to solve without it? -
How to calculate count in Django through two m2m levels?
I have 3 models like: class Customer(models.Model): hobby_groups=models.ManyToManyField( 'HobbyGroup', blank=True, related_name='group_customers', ) class HobbyGroup(models.Model): hobbies = models.ManyToManyField( 'Hobby', blank=True, related_name='hobby_groups', ) class Hobby(models.Model): title = models.CharField(max_length=255, default='football') And I need to calculate count of hobbies for each customer. qs = Customer.objects.annotate( hobbies_count=Count('hobby_groups__hobbies', distinct=True) ) With distinct it works fine, but very slow. I've tried to use Subquery. hobbies = Hobby.objects.filter(hobby_groups__group_customers=OuterRef('pk')).values('pk') hobbies_count = hobbies.annotate(count=Count('*')).values('count') qs = Customer.objects.annotate( hobbies_count=Subquery(hobbies_count) ) But it returns exception 'More than one row returned by a subquery used as an expression' Is there any way to calculate it faster or fix second solution? Because I did similar for backward related models and it worked fine and fast. Thanks in advance for help. -
502 log into django admin gunicorn nginx
I manage to deploy my django application with this tutorial from digitalocean but I have problem to log into application with django admin panel. I get 502 Bad Gateway when I write correct login and password, gunicorn workers reboots and then I can go into admin panel logged in, sometimes after this error occurs again. Application has one view/template outside of admin use and it works correctly. Did someone have similar problem? -
Easily integrate model changes to existing app in Django
I have an existing app with several models- I'd like to begin tracking updates and changes to the django model and use that data in the UI. I saw several Django plugins (django-reversion, django-model-utils, django-simple-history) though I'm unsure which of these will be easiest to integrate, least disruptive to the current app and also least taxing on my system. Can anyone please advise to which solution (maybe none of the above) has the best track record? Thanks!! -
Django-filter and Django-tables2 ModelChoice not filtering
I have a model that have these columns: Names and Last Name, the model has an string representation that joins the columns, using django-filter with ModelChoice I see the choices like 'John Doe' which is expected, but I have not found a way to filter the table, I think is because it searches for the field Name and not Name and Last Name together. models.py class Conductores(models.Model): nombres = models.CharField(max_length=25) apellidos = models.CharField(max_length=25) edad = models.IntegerField() phone_regex = RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") # validators should be a list telefono = models.CharField( validators=[phone_regex], max_length=17, blank=True) ine = models.FileField(upload_to='INE/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('nombres', 'apellidos') verbose_name_plural = "Conductores" def __str__(self): return '%s %s' % (self.nombres, self.apellidos) def get_absolute_url(self): return reverse('conductores') @property def full_name(self): return '{0} {1}'.format(self.nombres, self.apellidos) tables.py class ConductoresTable(tables.Table): ine = ImageColumn() class Meta: model = Conductores template_name = "django_tables2/bootstrap-responsive.html" fields = ('full_name', 'telefono', 'edad') attrs = {"class": "table table-hover table-sm"} filters.py class ConductoresFilter(django_filters.FilterSet): nombres = django_filters.ModelChoiceFilter(queryset=Conductores.objects.order_by( 'nombres').distinct('nombres')) class Meta: model = Conductores fields = ['nombres', ] urls.py path('drivers/', views.ConductoresListView.as_view(model=Conductores), name='conductores') I tried adding a function with a property in the … -
ModelForm not saving any data
I am a django beginner and trying to build a to-do list app. I am creating a ModelForm which adds a new task in the app. However upon trying to save the data, nothing is happening. No data is being saved, no errors being displayed. models.py: class Task(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) start_date = models.DateTimeField() end_date = models.DateTimeField() priority = models.BooleanField(default=True) completed = models.BooleanField(default=False) def __str__(self): return self.title ModelForm: class TaskForm(forms.ModelForm): class Meta: model = Task fields = ('title', 'description', 'start_date', 'end_date', 'priority') views.py: def task(request): task = Task.objects.filter(user=request.user, completed=False) queryset = task.order_by('-start_date') form = TaskForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.instance.user = request.user form.save() redirect('task:task-list') else: print('error') context = { 'task': queryset, 'form': form, } return render(request, 'task-list.html', context) template: <form action="." method="POST"> {% csrf_token %} {{ form }} <button type="submit">Add task</button> </form> any help would be appreciated! -
django 3 - how to set Article model foreign key as logged in user id?
am a new learner of django 3. trying to build a blog app where user can create article & article author foreign key will be logged in user id. To do it my model.py is from django.db import models # Create your models here. class Author(models.Model): name = models.CharField(max_length=50) bio = models.TextField() def __str__(self): return self.name class Category(models.Model): category = models.CharField( max_length=50) description = models.TextField() def __str__(self): return self.category class Article(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to="images/") content = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title according to model I made a form by forms.py from django import forms from django.forms import ModelForm from .models import * class ArticleForm(forms.ModelForm): class Meta: model = Article fields = '__all__' To present this form my views function is... from django.shortcuts import render, redirect from .models import * from .forms import * # Create your views here. def index(request): articles = Article.objects.all() form = ArticleForm() if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): form.save() return redirect('bloglist') context = {'articles':articles, 'form': form} return render(request, 'bloglist.html', context) and template code is... <form method="POST" action="" class="form-inline"> {% csrf_token %} {{form }} <input class="btn btn-primary mb-2" type="submit" name="Submit"> </form> In this … -
Is there a way to create instant messages using django?
So, I spent a few hours browsing through github repositories and through the internet for a possible way to create a messaging app using django But I can't seem to find any .. The only thing i could find was ways to create chatrooms but nothing about creating a one-to-one convos Is it possible to do this in django at all? -
i need help and advice about django admin
I'm new with python and Django. I know a lot about the Codeigniter framework and there if you want to create a project like an eCommerce you must create an admin panel with template and function for the backend. when I was creating backend I was adding functions for the admin panel where all functions were for adding some informations in the database. so when I start with Django I saw that there was an integrated admin panel which can be modified but I have a question can I create app for Django which will be admin panel of my project and can I deactivate or delete integrated admin panel or can I add some functions and redesign integrated one -
React app not communicating with my Django API on heroku
I deployed my react app and Django app to Heroku. Django serves the API and React serves as frontend. The frontend part is working quite well but just seems not to be communicating with the Django side. My project is set up as. If I try to access the database it . Now, I'm confused if I'm to use http://127.0.0.1:8000/graphql/ to access it or its meant to be a Herokuapp domain/8000 to fetch the API. I've done allowed Host on the Django side as well as whitelist, CorsMiddleware and CORS_ORIGIN_WHITELIST also used proxy on the package.json but everything still looks messed up and not communicating between each other -
Installing ibm-db==2.0.9 failing with Files/directories not found
pip -v install ibm-db==2.0.9 Running setup.py (path:/tmp/pip-install-xurqh5wv/ibm-db/setup.py) egg_info for package ibm-db Running command python setup.py egg_info Detected 64-bit Python Cannot find /home/ssss/myVirtualEnvironments/metaProj/dsdriver/clidriver/lib directory. Check if you have set the IBM_DB_HOME environment variable's value correctly Cleaning up... Removing source in /tmp/pip-install-xurqh5wv/ibm-db Removed ibm-db==2.0.9 from https://files.pythonhosted.org/packages/3f/61/389c6decacfed61c2724005b8c2be61f2c699f731b53af13517e5a0e6e98/ibm_db-2.0.9.tar.gz#sha256=72a5b1911125311bfa53dab40cf6684965abf4a548181f4af53dbe7d527f68c6 from build tracker '/tmp/pip-req-tracker-hldr2v7l' Removed build tracker: '/tmp/pip-req-tracker-hldr2v7l' ERROR: Files/directories not found in /tmp/pip-install-xurqh5wv/ibm-db/pip-egg-info -
Django 'NoneType' object has no attribute 'amount'
I keep getting the same error 'NoneType' object has no attribute 'amount' over and over ever since I added an an amount field to my coupon code script. This is my code; class Coupon(models.Model): code = models.CharField(max_length=15) amount = models.FloatField() def __str__(self): return self.code And here's the get_total code; def get_total(self): total = 0 amount = models.FloatField() for order_item in self.items.all(): total += order_item.get_final_price() total -= self.coupon.amount return total I have been trying to solve this with numerous solutions that didn't work. I would really appreciate it if anyone could tell me what I am doing wrong here -
Accessing TCP connection on django channels 2
I am working on a django project, there is a device that make TCP connection (not websocket connection) on a specific port. I need to ask that, how can I implement TCP and websocket (django channels) so that when data comes from TCP I can send it to Websocket connection Note: device is a TCP client. I have achieved it in Nodejs but need to implement in django. -
Using Youtube-dl convert Youtube videos into mp3 and getting the URL from the Django form
The Following the views.py file from Django. Where I simply get the input from the text box after the submit button is pressed I have no problems with getting the value because when I print the "url_value" variable it prints the right value. Then I have the functions called "convert" and I pass in the "url_value" variable into that but I keep getting the following error: [0;31mERROR:[0m 'None' is not a valid URL. Set --default-search "ytsearch" (or run youtube-dl "ytsearch:None" ) to search YouTube import youtube_dl from urllib.parse import unquote from django.shortcuts import render from django.http import HttpResponse from main import forms def index(request): # Get the Value inside the input box after btn pressed url_value = request.GET.get("url_value") print('inputted value is: ', data) # mp3 convert function def convert(url): ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) convert(str(url_value)) return render(request, 'index.html') Here is the HTML form <form action='' method='GET'> <input type='text' name='url_value' placeholder='Paste the URL...'/> <input type='submit' value='submit'/> </form> -
How to get access to directory in Django
In media/json I have JSON files and I want to read them with a JavaScript file which is in static/js without hardcoding. How can I do it? -
Why the .mo and .po files are in the .gitignore
Why the .mo and .po files are part of the .gitignore file, these files must be translated, but what I don't understand is why they are ignored, so we won't have to translate again? I searched on githubgitignore and found a list of .gitignore files for projects, python and django too but I don't understand why .mo and .po files are part of -
How to create a custom serializer for a django rest framework model with translations
I'm using django-rest-framework and I have a model "TextElement" with attribute "text" translated using django-modeltranslation. I need to create a generic serializer that takes translated fields and returns as data a dictionary with language as the key and the translated attribute as value. Example: text_element = TextElement.objects.get(id=1) text_element_serializer = TextElementSerializer(text_element) text_element_serializer.data >> {"text": {"en": "Something", "es": "Algo"}, "other_attribute": "Something else"} I could do it using the following serializer: class TextElementSerializer(serializer.ModelSerializer): text = serializer.SerializerMethodField() class Meta: model = TextElement fields = ('text', 'other_attribute') def get_text(self, instance): return { 'en': instance.text_en, 'es': instance.text_es } But I would like to know if it's possible to create a genereic serializer that checks automatically all the translated attributes in "fields", using available languages in settings.LANGUAGES and returning the same data structure. Thanks in advance! -
Python Django Linking URLS
I am working on an online school project, I just linked subjects, with classes so when you click on a class you get it's subjects page, and in the subject page there are lessons(lessons use IDs not slugs), My problem is at linking the lesson URL in the HTML page My codes: HTML PAGE: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Name</title> <link rel="stylesheet" href="/static/css/style.css"> </head> <body> <div> <nav> <div class="logo"><img src="/static/images/Logo.png" width=50px></div> <ul class="navul"> <li class="navli"><a class="nava" href="404.html">حول الموقع</a></li> <li class="navli"><a class="nava" href="404.html">المكتبة</a></li> <li class="navli"><a class="nava" href="404.html">الدورات</a></li> <li class="navli"><a class="nava" href="/classes">الصفوف</a></li> <li class="navli"><a class="nava" href="/">الصفحة الرئيسية</a></li> </ul> </nav> <div class="div1"> <img src="/static/images/Logo.png" width="90" class="logo2"> <h1 class="t1">المواد </h1> </div> <div class="cardrow"> {% for material in material.all %} <div class="cardcolumn"> {% for Lesson in Materials.vedio_set.all %} <a href="{% url 'vedio' lesson.id %}" > lesson1</a> {% endfor %} <div class="card"> <img class="imgcls" src="{{ material.image.url }}"> <h1>{{ material.title }}</h1> </div> </a> {% endfor %} </div> </div> </div> </body> </html> MODELS.py: from django.db import models from users.models import * # Create your models here. class Class(models.Model): image= models.ImageField(upload_to="images") name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) def __str__(self): return self.title class Material(models.Model): name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) classes= models.ForeignKey(Class, default=1, on_delete=models.SET_DEFAULT) def __str__(self): return self.name class Lesson(models.Model): slug=models.SlugField() … -
How to fix TypeError: FilterIPMiddleware() takes no arguments in django
I face the problem of TypeError: FilterIPMiddleware() takes no arguments when I applied to my project python version 3.7.2. here is the code raising the error from django.http import HttpResponseForbidden class FilterIPMiddleware(object): #Check if client IP is allowed def process_request(self, request): allowed_ips = ['111.111.111.111'] # Authorized ip's ip = request.META.get('REMOTE_ADDR') # Get client IP print(ip) if ip not in allowed_ips and request.user.username=="example_name": return HttpResponseForbidden() # If user is not allowed raise Error # If IP is allowed we don't do anything return None Here is the Traceback: Exception in thread django-main-thread: Traceback (most recent call last): File "/root/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/root/.pyenv/versions/3.7.2/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/www/wwwroot/grammarine/grammarine_venv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, … -
Django support multi language for just one html file
I wonder if there is a fast way to make multilangauge(almost 30 languages) support for just one simple html file. I tried django multilangauge support but it took so long time to do it since this project is python2 and has so many apps. -
Save Binary Data Using Django Rest Framework Viewset method
I have a viewset method save that accepts formdata and should save the instance and return it. @action(methods=['put'], detail=False) def save(self, request): user = request.user if not user.is_staff: raise PermissionDenied("You must be a staff member or superuser to edit app settings.") settings = Globaloptions.objects.first() data = json.loads(request.body, encoding='utf-8') if not settings.guestEnabled: if 'guestDashboard' in data: del data['guestDashboard'] [setattr(settings, k, v) for k, v in data.items()] settings.save() serializer = self.get_serializer(settings, many=False) return Response(serializer.data) I recently added a file field to the model. So now when I try to save it, I get an error because it fails to parse the data in utf-8. What is the correct method for saving a form with binary data when using a viewset? -
Django: Trying to populate a dropdown using Javascript
I have two dropdowns and I'm trying to populate the second one using Javascript when the first one changes. It should be populated from the database values contained in 'departements' variable of my views.py file. I found some code on the web but it didn't work when I tried to apply it to my case. I have next to 0 knowledge in Javascript, so no idea if I'm even on the right path. Below are more details about my files: models.py class data_immo(models.Model): id = models.AutoField(primary_key=True) insee_dep = models.IntegerField(db_column='INSEE_DEP', blank=True, null=True) nom_reg = models.TextField(db_column='NOM_REG', blank=True, null=True) class Meta: managed = True db_table = 'immo' views.py def MyView(request): query_results = data_immo.objects.all() regions = data_immo.objects.values_list("nom_reg", flat=True).distinct() departements = data_immo.objects.values_list("insee_dep", flat=True).distinct() query_results_dict = { 'query_results': query_results, 'regions': regions, 'departements': departements, } return render(request,'home.html', query_results_dict) home.html <select id="reg" name="reg" onChange="populate2()"> {% for item in regions %} <option val="{{ item.nom_reg }}"> {{ item.nom_reg }} </option> {% endfor %} </select> <select id="dep" name="dep"></select> <script type="text/javascript"> function populate2(){ $('.dep').append('<option>' + departements[0].insee_dep + '</option'); } </script> I need the populate2() function to update the 'dep' dropdown. The function is obviously wrong, but I don't know where exactly. Thanks in advance! -
TemplateDoesNotExist at http://127.0.0.1:8000/
I don't know why I am getting this error. Below is the code I am using. settings.py TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "mysite", "static", "templates"),) urls.py from django.urls import path from django.conf.urls import include, url from django.contrib.auth import views as auth_views from notes import views as notes_views urlpatterns = [ url(r'^$', notes_views.home, name='home'), url(r'^admin/', admin.site.urls), ]``` **views.py** `def home(request): notes = Note.objects template = loader.get_template('note.html') context = {'notes': notes} return render(request, 'templates/note.html', context)` NOTE : I am following this tutorial - https://pythonspot.com/django-tutorial-building-a-note-taking-app/ -
how can i send a file from django into a script of python?
I have a python script that processes an excel or csv document, in the python script I write the specific path of the file, locally. this is my code in Python ''' url_rsso = r'file:///C:/Users/Mata/Desktop/RSSO.xlsx' ''' df_rsso = pd.read_excel(url_rsso) this is my code in django def upload(request): context = {} if request.method == 'POST': df_rsso = request.FILES['document'] fs = FileSystemStorage() name = fs.save(df_rsso.name, df_rsso) context['url'] = fs.url(name) return render(request, 'upload.html', context) I also have a web page with django that is very simple, it has a ChooseFile, a button whose action will process the file and one to download the modified file. What I want to do is: the file that I store using django can send it to the script I have in python. If the file is sent to the script, it processes it and exports it in excel which I have to send to django for the user to download the new modified file. here is my github https://github.com/mata-2p/codelweb i am very new in python and django