Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django timezone in admin interface is not mine: how do I change it?
In my models I have this: created_at = models.DateTimeField(auto_now_add=True) If I display created_at in my django-admin dashboard, it is always lagging by 1 hour. How can I avoid this? How can I display the datetime in my timezone? My timezone is GMT+1 If I type date in my server terminal, I get the correct datetime. I've consulted the documentation and it says I have to use the activate() function, without specifying where I should actually use it and how: there are no examples and it's very confusing. -
Django filter manytomany relation
I spent a lot of time trying to filter out the entities related many to many, but the result really amazes me. I can’t understand how to solve this and why this happens. I have 2 models in Django: class Application(models.Model): ... forms = models.ManyToManyField(Form, related_name='applications', through='ApplicationForm', blank=True) ... class Form(models.Model): ... class ApplicationForm(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) form = models.ForeignKey(Form, on_delete=models.CASCADE) created_at = models.DateTimeField() updated_at = models.DateTimeField(auto_now=True) In ApplicationSerializer I want to return filtered forms related to my application. I try to do this on this way: forms = serializer.SerializerMethodField() def get_forms(self, obj): qs = obj.forms.filter(status=Form.COMPLETED) return FormSerializer(qs, many=True, context=self.context).data I have 2 forms and 3 applications which has both forms. But my function returns 6 forms [1, 2, 1, 2, 1, 2] for example. I try to debug this and found that obj.forms.all() return 2 forms, but if I add filter it returns 6. I try to use obj.forms.filter(status=Form.COMPLETED).distinct() but result the same. I can not create query like Forms.objects.filter(status=Form.COMPLETED).filter(pk__in=...) because i have many parameters prefetched and annotated on application manager level. So I want to know is there any way to filter manytomany relation objects related to my instance -
Getting “URL Blocked” error on Facebook login on production server using Nginx and Django
I'm using Django OAuth (social-auth-app-django) for Facebook login. It works on localhost but after some time it stopped working on a production server. When I push the Facebook login button (https:///oauth/login/facebook/ ) on production server, I get redirected to this URL: https://www.facebook.com/v3.2/dialog/oauth?client_id=2125271371046613&state=ngamzlnEBNjkivjZkZDJWyPi7MnyJ6z5&return_scopes=true&redirect_uri=https%3A%2F%2Flocalhost%2Foauth%2Fcomplete%2Ffacebook%2F with the following message: URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs. My Valid OAuth Redirect URIs is: https://<my domain>/oauth/complete/facebook/ It appears that Django generates redirect_uri=https://localhost/auth/complete/facebook/ instead of redirect_uri=https://<my domain>/auth/complete/facebook/ Also, if I add https://localhost/oauth/complete/facebook/ to Valid OAuth Redirect URIs and push Facebook login button, I am redirected to https://localhost/oauth/complete/facebook/?granted_scopes=public_profile&denied_scopes&code=AQDVoyWYftr-kU55VpWzUlyVOaFu80nWrdNhvnnakA-zxWRlGjwbBC4DMGyKasgDYtgtiPieqxO2H0H3z7mh-OxRuniJBDVOftCWnPNEKGfn8Tf-XExxYOcWdwAjhSUltgpm152fM13mgSDEGlzRvv6Dn_ccImV3c9Wsjr756jLdZr5cAdtIxv6tWLBsEBlynJmDZEYiucszOpain80WJCjAQAvyf3JdoCE0pb-YaxMFVa9c8KcN58s9Uif12trCc772AMQXnXDJxPauBl65bO5kRMJ4HPSj_-SXrMflWj5idehmM5OwsSGJakKsXgeYkshjnYycmc9bsy6NxAykV515&state=ngamzlnEBNjkivjZkZDJWyPi7MnyJ6z5#_=_ and (obviously) get “server not found” message. However, if I then manually change localhost to <my domain> like this: https://<my domain>/oauth/complete/facebook/?granted_scopes=public_profile&denied_scopes&code=AQDVoyWYftr-kU55VpWzUlyVOaFu80nWrdNhvnnakA-zxWRlGjwbBC4DMGyKasgDYtgtiPieqxO2H0H3z7mh-OxRuniJBDVOftCWnPNEKGfn8Tf-XExxYOcWdwAjhSUltgpm152fM13mgSDEGlzRvv6Dn_ccImV3c9Wsjr756jLdZr5cAdtIxv6tWLBsEBlynJmDZEYiucszOpain80WJCjAQAvyf3JdoCE0pb-YaxMFVa9c8KcN58s9Uif12trCc772AMQXnXDJxPauBl65bO5kRMJ4HPSj_-SXrMflWj5idehmM5OwsSGJakKsXgeYkshjnYycmc9bsy6NxAykV515&state=ngamzlnEBNjkivjZkZDJWyPi7MnyJ6z5#_=_ I then have a successful login. How to make Django (or probably Nginx) generate a redirect_uri with <my domain> instead … -
Django choices that change automatically based on male/female checkboxes
I want to have a model that will have a a set of choices of categories which will change based on whether the male or female checkbox/choice (whichever is more appropriate) was selected. In models.py, class MyModel(models.Model): MALE_CATEGORIES = { ('Male Category 1', 'Male Category 1'), ('Male Category 2', 'Male Category 2'), ('Male Category 3', 'Male Category 3'), } FEMALE_CATEGORIES = { ('Female Category 1', 'Female Category 1'), ('Female Category 2', 'Female Category 2'), ('Female Category 3', 'Female Category 3'), } # Male/Female option as either choices or checkboxes depending on whichever one is more suitable gender = # Either MALE_CATEGORIES or FEMALE_CATEGORIES # Depending on gender categories = models.CharField(max_length=18, choices=) In forms.py, class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = [ 'gender', 'categories', ] -
Django, How to put a form and data table on the same page?
I am new to django, I would like to know How Can I put a form and a data table on the same page. At the moment I have a form and my data table on two diferent page, I would like to put them on the same page. I searched online how but it didn't work. Thanks for helping! views.py def scrap(request): if request.method == "POST": form1 = Scrap(request.POST) if form1.is_valid(): scrapsave = form1.save(commit=False) scrapsave.save() return redirect(scrap) else: form1 = Scrap() context = { "form1": form1 } #The view to show my data table def home(request): all_items = List.objects.all return render(request, "data_list/home.html", {"all_items": all_items}) forms.py class Scrap(forms.ModelForm): url = forms.CharField() class Meta: model = List fields = ["item", "site"] models.py class List(models.Model): item = models.CharField(max_length=100) content = models.TextField() site = models.CharField(max_length=11, choices=THE_SITE) def __str__(self): return self.item urls.py urlpatterns = [ path("", views.add, name="add"), path("scrap/", views.scrap, name="scrap"), path("home/", views.home, name="home"), path("delete/<list_id>", views.delete, name="delete"), path("datacontent/<list_id>", views.datacontent, name="datacontent") ] home.html <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">Name</th> <th scope="col">Site</th> <th scope="col">Handle</th> </tr> </thead> <tbody> {% for things in all_items %} <tr> <td class="striker"><a href="{% url "datacontent" things.id %}" <center>{{ things.item }}</a></center></td> <td>{{ things.site }}</td> <td><a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url … -
Django redirect after login loses query string
I have a view that requires a user to login. It can optionally receive some querystring parameters. The problem is that the querystring is lost after the user successful login. My view: @ensure_csrf_cookie @login_required @permission_required('MyApp.view_usage',raise_exception=True) def pdfParser(request): return render(request,'MyApp/dashboard.html',{}) The url I am calling to get to that view (with the login redirect): http://127.0.0.1:8000/accounts/login/?next=/OldStyle/%3FDOCUMENT_ID%3Dlkpto%26SERIES%3D0001 Url that is generated after the login: http://127.0.0.1:8000/OldStyle Where/What should I do to intercept and fix it? -
Python-Django: __str__ returned non-string (type NoneType) (TypeError at /newUser/) Using Crispy Django Form
This is my first question I've posted. Please be kind. Thanks in advance. I absolutely have no idea why I'm getting this problem. I'm at my wit's end. This error occurs when I'm trying to add a New Organization, new Team or new Agile team in the newUser.html page. I'm using Crispy Forms to render the Django forms which I have added as an App in my settings.py To understand my problem better, here are some screenshots of how they look/work: Output This image is two images in one. The left side is listUser.html, the right side is NewUser.html If I add organizations or teams or agile teams from my Django admin, then I can add a new user with no problems. However, when I try to add a new Organization or new Team or new Agile Team from the buttons on the newUser.html page, I am getting this error. Here is the picture of the error I got: Error message on localhost Here is the traceback error that I got: Traceback message {% crispy_field field %} The line above is highlighted. My Code: Please see the links to understand better. urls.py from django.urls import path from scrapeComments import views … -
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!