Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configure & enable OpenID Connect in DJango+Wagtail app?
I'm currently using the python-social-auth/social-core lib with a DJango app, which is configured (and working) to authenticate Wagtail CMS users with our (free) Azure Active Directory Tenant. Our NFRs stipulate that authentication should occur using OpenID Connect and to this end we've installed "social-auth-core" with the "openidconnect" extra like this in requirements.txt: ... social-auth-core[openidconnect] social-auth-app-django ... Again, things seem to work A-OK and users can login, but here's my problem - and I know I'm missing something here: As far as I know, OpenID Connect is simply a modification/addition to OAuth2.0 that gives OAuth super powers of authentication - not just authorisation - but I don't know if my DJango+Wagtail app is now just automagically configured to "just work" as/with OpenID Connect, or whether there's some additional logic/validation/config/whatever that I need to apply to the app. I don't see anything relevant in the official python-social-auth docs for Azure AD, and I don't see how/if I need to explicitly enable OpenID within Azure AD itself. Can anyone help? Thank you. -
Django/DRF: How can I get more than one slug_field from serializers.SlugRelatedField?
I have a serializer to populate an AJAX table that looks something like this: class BookSerializer(seralizers.ModelSerializer): author = serializers.SlugRelatedField( many=True, read_only=True, slug_field="name" ) class Meta: model = Book fields = ( "name", "author", "slug" ) author can contain any number of authors, which is why I need to handle it this way. Currently I can print out the name of the book and link it with its slug. I also get a list of author names rather than the IDs. My question is how I can also get the slugs for each author page? I would like to link each author to its own page, but using something like author.slug doesn't work, nor did adding this: author_slugs = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name="slug" ) Then I added author_slugs to fields -- this threw an error that author_slugs is not a valid field in the Book model. Is there a way to access more than field for each author? -
How to add multiple css file in django3 in a single html file?
I have a html file named index.html in template folder and two css file computer.css and mobile.css both are in static folder. How can i use them in a single index.html file. -
django channel_layer.send not sync even use async_to_sync
class ChatConsumer(WebsocketConsumer): def connect(self): print(self.channel_name) self.accept() def disconnect(self, close_code): pass def receive(self, text_data): async_to_sync(self.channel_layer.send)(self.channel_name, { "type": "chat.message", "text": "1", }) print("=============channel================") async_to_sync(self.channel_layer.send)(self.channel_name, { "type": "chat.message", "text": "2", }) def chat_message(self, event): message = event["text"] print(message) self.send(text_data=json.dumps({'message': message})) i call channel_layer.send twice in receive function , suppose should print like 1 ========channel======== 2 but it print =========channel======= 1 2 anyone could help to tell me where have problem ? -
Using the select_related function in Django
Hi so i'm trying to display table retailer_book, but instead of a seller_id, i want it to display the retailer instead. These are the tables class retailer(models.Model): sellerID = models.IntegerField(primary_key=True) retailer = models.CharField(max_length=255) def __str__(self): return self.retailer class retailer_book(models.Model): ISBN = models.ForeignKey(books, on_delete = models.CASCADE) sellerID = models.ForeignKey(retailer, on_delete = models.CASCADE) condition = models.CharField(max_length=255) price = models.FloatField() reviews= models.CharField(max_length=255) ID = models.IntegerField(primary_key=True) bookType = models.CharField(max_length=255) I've tried : object_list1 = retailer_book.objects.filter(ISBN_id = query).select_related("sellerID_id") but it doesn't display retailer when i try to display it. Here's my views.py class SearchResultsView1(ListView): model = books template_name = 'TextSearch/search_results.html' context_object_name = "object_list" def get_queryset(self): # new query = self.request.GET.get('q') object_list1 = retailer_book.objects.filter(ISBN_id = query).select_related("sellerID_id") return object_list and here's my HTML code <h1>Book Options: </h1> <table border="1"> <tr> <th> ID </th> <th> Retailer </th> <th> condition </th> <th> Book Type </th> <th> Reviews </th> <th> Price </th> </tr> {% for result in object_list %} <tr> <td> {{result.ID}} </td> <td> {{result.retailer}} </td> <td> {{result.condition}} </td> <td> {{result.bookType}} </td> <td> {{result.reviews}} </td> <td> {{result.price}} </td> </tr> {% endfor %} </table> -
Django displays tow different timezones for the same model attribute when viewing in admin site vs a query for the model in a script
How to make consistant timezone across Django. In my settings.py I have TIME_ZONE = 'America/New_York' and USE_TZ = True. I have a model def MyModel(models.Model): date_time = models.DateTimeField(auto_now_add=True) if I view a field from that model (say pk=1) it correctly displays value for an eastern timezone. From my terminal, when I run python manage.py shell and make a query for that same field (pk=1), it will print the date_time attribute of that field in UTC format as follows: datetime.datetime(2020, 10, 22, 0, 19, 28, 696739, tzinfo=<UTC>) Why is this happening? And how can I make it so that all queries use the correct timezone when filtering by date? -
OperationalError Django admin
I'm using a legacy mysql database on django. I need to display another table on the "bibliografias" admin page, it is referenced by the db with foreign keys. I get this error: OperationalError at /admin/accounts/bibrest51/ (1054, "Unknown column 'bibrest51.tema_f_id' in 'field list'") admin.py def get_tema(self, obj): return obj.tema_f.tema_nome get_tema.short_description = 'Tema' models.py class Tema(models.Model): tema_id = models.AutoField(primary_key=True) tema_nome = models.CharField(max_length=150, blank=True, null=True) datacriado = models.DateTimeField(db_column='dataCriado') # Field name made lowercase. @property def tema_id(self): return self.tema_id def __str__(self): return str(self.tema_id) class Meta: managed = False db_table = 'tema_table' class Bibrest51(models.Model): cadastro_id = models.AutoField(primary_key=True) tema_f = models.ForeignKey(Tema,on_delete=models.CASCADE) tema_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'bibrest51' verbose_name = "Bibliografia" verbose_name_plural = "Bibliografias" -
Serializing Nested foreign key objects
whoever is reading this, hope you're doing well. I am creating a social media application which includes post in it and likes and comments just like any other social media site, I am trying to send the data from my backend to front end via serializers, the problem I am getting through is I am not able to get the output of whole data but partial data. Following represents my models.py for the objects I am trying to serialize models.py class User(AbstractUser): contact_no = models.CharField(max_length=15,null=True,blank=True) profile_picture=models.ImageField(upload_to=to_upload,default="defaultprofile.jpg") class Post(models.Model): posted_by=models.ForeignKey(User,on_delete=models.CASCADE) date= models.DateField(auto_now=True) time=models.TimeField(auto_now=True) content=models.CharField(max_length=2000) media=models.ImageField(default=None,blank=True,upload_to=to_upload_post) class Like(models.Model): Liked_by=models.ForeignKey(User,on_delete=models.CASCADE,related_name="likes") post=models.ForeignKey(Post,on_delete=models.CASCADE) date = models.DateField(auto_now=True) time = models.TimeField(auto_now=True) and the serializers that I'm using is serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields=['id','username','first_name','last_name','profile_picture'] class LikeSerializer(serializers.ModelSerializer): Liked_by=UserSerializer() class Meta: model=Like fields=['Liked_by'] class PostSerializer(serializers.ModelSerializer): posted_by=UserSerializer() likes=LikeSerializer(many=True) class Meta: model=Post fields=['posted_by','id','content','date','time','media','likes'] This does not raise any errors while importing it but it doesn't give complete data. The output I'm getting is { 'posted_by': OrderedDict([ ('id', 7), ('username', 'user'), ('first_name', ''), ('last_name', ''), ('profile_picture', '/media/defaultprofile.jpg')]), 'id': 4, 'content': 'This is a test post for likes', 'date': '2020-10-22', 'time': '05:34:55.979863', 'media': None } but what I'm trying to get is Desired Output { 'posted_by': OrderedDict([ ('id', 7), ('username', 'user'), ('first_name', … -
Django: How to override the display of ModelForm fields in UpdateView, specifically
I have a function-based view that is currently working successfully. However, I want to learn how to create the equivalent Class Based View version of this function, using the generic UpdateView class -- though I imagine the solution, whatever it is, will be the exact same for CreateView, as well. I know how to create and use Class Based Views generally, but there is one line of my function-based view that I have not been able to work into the corresponding UpdateView -- as usual with the Generic Editing Class Based Views, it's not immediately clear which method I need to override to insert the desired functionality. The specific task that I can't port-over to the CBV, so to speak, is a line that overrides the queryset that will be used for the display of a specific field, one that is defined as ForeignKey to another model in my database. First, the working function-based view, with highlight at the specific bit of code I can't get working in the CVB version: @login_required def update_details(request, pk): """update details of an existing record""" umd_object = UserMovieDetail.objects.select_related('movie').get(pk=pk) movie = umd_object.movie if umd_object.user != request.user: raise Http404 if request.method != 'POST': form = UserMovieDetailForm(instance=umd_object) … -
Django Template Query Set and filters
In my view, I have a model that returns all instances of a model that has a foreign key to user. This view renders a profile page where the model.user is checked against the request.user, if it matches, it prints out information on that model on the profile page. This is what I have in my views.: @login_required(login_url='loginpage_company') @allowed_users_company(allowed_roles=['company']) def profile_company(request): print(request.user) companies = Company.objects.all() responses = Response.objects.all() context = { 'companies': companies, #'company_reviews': company_reviews, #'total_reviews': total_reviews, 'responses': responses, 'info': "No company claimed yet", 'infor': 'Not Available', } return render(request, 'companyusers/profile_company.html', context) for my models I have the following. class Company(models.Model): Online_Merchant = 'merch' Education = 'edu' Transportation = 'trans' Hospitalism = 'hosp' Healthcare = 'health' Construction = 'const' Blog = 'blog' Finance = 'fin' Media = 'media' Government_Agency = 'agency' Other = 'other' Manufacturing = 'manufacturing' sector = [ (Online_Merchant, 'Online Merchant'), (Education, 'Education'), (Transportation, 'Transportation'), (Hospitalism, 'Hospitalism'), (Healthcare, 'Healthcare'), (Construction, 'Construction'), (Blog, 'Blog'), (Finance, 'Finance'), (Media, 'Media'), (Manufacturing, 'Manufacturing'), (Government_Agency, 'Government Agency'), (Other, 'Other') ] Free = 'Free' Premium = 'Premium' package = [ (Free, 'Free'), (Premium, 'Premium') ] Abuja = 'Abuja' Abia = 'Abia' Adamawa = 'Adamawa' Akwa_Ibom = 'Akwa Ibom' Anambra = 'Anambra' Bauchi = 'Bauchi' … -
How to download a file from a Django template?
Hello Community! I'm working on a small Django project that consists of creating a website that allows you to download multimedia content from YouTube, through the "youtube-dl" library. I summarized the code as much as possible, remaining with the following directory structure: In the file "views.py": from django.shortcuts import render import youtube_dl def home(request): return render(request, 'TestApp/index.html') def download_success(request): url = request.GET.get('url') obj = Media(url) return render(request, 'TestApp/thanks.html', {'content': obj}) class Media(object): '''Class where the logic implemented with "youtube-dl" is found ''' def __init__(self, url): self.url = url ydl_opts = { 'format': 'best' } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([self.url]) In the file "urls.py": from django.urls import path from TestApp import views urlpatterns = [ path('', views.home, name='Home'), path('Thanks', views.download_success, name='thanks'), ] In the directory "/templates/TestApp" are the HTML templates, which have the following structure: "index.html": <!DOCTYPE html> <html lang="es"> <head> {% block title %} <title>misiteweb.com</title> {% endblock %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1"> {% load static %} <!-- CSS --> <link rel="stylesheet" type="text/css" href="{% static 'TestApp/css/styles.css' %}"> <!-- BOOTSTRAP --> <link rel="stylesheet" href="{% static 'TestApp/vendor/css/bootstrap.min.css' %}"> </head> <body> {% block content %} <div class="container"> <br></br> <center><h1> Download Panel </h1></center> <form action="Thanks" method="get"> <br> <div class="form-group"> <input … -
I am using Django password reset view but I am getting error after the password confirm page
Error Page accounts/urls.py password_reset_complete.html -
Python-Pulp: How to store the objective function and constraints in a database for user modification/recall?
I'm building a Django app that allows a user to save their models as different "Scenarios" where they can use a web interface to manually adjust the objective function and some of the constraints. The whole app is built and functioning fine, except for figuring out how to store the OBJ/Cons in the db/table and how to show them back to the user. For the sake of example, let's use the Two stage production program found in the docs. Right now, the model is hardcoded as a .py file and that should transition somehow into a DB. My question becomes, how would you design the table to store the objective function and constraints for access, review, modification, and run by the user? -
How to adjust datatables fonts in Django
Does anybody know how to adjust the field size of Show xx entries in DataTables? Recently my datatables started showing a larger font for the number and for the life of me I can't figure out the CSS to control the size of the field. Is it possible? -
What happens if I run django migrations multiple times in parallel?
So, I often am working with projects where there will be multiple dockerized django application servers behind a loadbalancer, and frequently I will need to deploy to them. I frequently use Watchtower to do pull-based deploys. I build a new image, push it to dockerhub, and watchtower is responsible for pulling those images down to the servers and replacing the running containers. That all works pretty well. I would like to start automating the running of django migrations. One way I could accomplish this would be to simply add a run of the manage.py migrate to the entrypoint, and have every container automatically attempt a migration when the container comes online. This would work, and it would avoid the hassle of needing to come up with a way to do a lockout or leader election; but without some sort of way to prevent multiple runs, there is a risk that multiple instances of the migration could run at the same time. If I went this route, is there any chance that multiple migrations running at the same time could cause problems? Should I be looking for some other way to kick off these migrations once and only once? -
MySQL connection problem using Python/Django
Working on a Python(Django web framework, PyCharm Professional IDE) application and having a difficult time trying to resolve why I cannot connect to my DB when I execute the application. Here is the error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on....) Oddly enough this works fine in my Windows Environment, but for some reason not working on my Mac. Same code, same DB server (MySQL Community server 8.0.16), and same MySQL workbench(also 8.0.16). Something else that is odd, when using the DB Pane in my PyCharm IDE I can see my DB, can run queries, can refresh my DB and log in with my root password with no problem. The following is a code snippet from my Settings.py file... # Local: 'default': { # MySQL database engine class. 'ENGINE': 'django.db.backends.mysql', # MySQL database host ip. 'HOST': '127.0.0.1', # port number. 'PORT': '3306', # database name. 'NAME': 'my_db', # user name. 'USER': 'root', # password 'PASSWORD': 'password', # connect options 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", } }, } Python 3.7.3 Django==2.2.2 mysqlclient==1.4.4 mysql==0.0.2 mysql-connector-python==8.0.22 PyMySQL==0.10.1 MySQL Community server 8.0.16 MySQL workbench 8.0.16 Note: In regards to Python packages, I prefer to stick mysqlclient since that is what I'm using on my … -
New Apache Server is causing Ajax 500 internal error
So the ajax call worked perfectly before I tried to replace the Django Dev Server with the Apache server. This Apache server is being set up in a docker-compose container along with the website source code. The Ajax Error: I'm going to list all the changes I made to the previously working code. Partial Dockerfile: ... RUN apt-get -qq update && \ apt-get install --yes apache2 apache2-dev && \ pip install mod_wsgi && \ cat httpd.conf >> /etc/apache2/httpd.conf && \ cat envvars >> /etc/apache2/envvars I'm not sure if that's the correct path for the configuration files though. Partial docker-compose.yml: ... web_service: ... command: bash -c "mod_wsgi-express start-server /jackwu_ca/jackwu_ca/wsgi.py --port=80 --user www-data --group www-data" In local httpd.conf: Alias /static/ /jackwu_ca/static/ <Directory /jackwu_ca/static> Require all granted </Directory> WSGIScriptAlias / /jackwu_ca/jackwu_ca/wsgi.py WSGIPythonHome /jackwu_ca/venv WSGIPythonPath /jackwu_ca WSGIDaemonProcess jackwu_ca python-home=/jackwu_ca/venv python-path=/jackwu_ca WSGIProcessGroup jackwu_ca <Directory /jackwu_ca/jackwu_ca> <Files wsgi.py> Require all granted </Files> </Directory> In local envvars: export LANG="en_US.UTF-8" export LC_ALL="en_US.UTF-8" I'm fairly certain I did not set up the Apache server properly, thus, the error. But the site is running, and I can navigate around it. -
Django Test for tutorial not working as expected
I am working on going through the tutorial at - https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing.I am working on AuthorCreateViewTest to create a test for the AuthorCreate view and I have an issue that I can't figure out. Please see the issue that I facing below. I have attached the code from the project also that I think is relevant to this issue. I am sure that it is simple but I am new at coding with Python and Django. Please help if you can so I can continue my training. Issue/Result C:\Project\django_projects\locallibrary>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ...............[(41, 'Set book as returned')] F[(41, 'Set book as returned')] .[(41, 'Set book as returned')] .......... ====================================================================== FAIL: test_logged_in_with_permission (catalog.tests.test_views.AuthorCreateViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Project\django_projects\locallibrary\catalog\tests\test_views.py", line 459, in test_logged_in_with_permission self.assertEqual(response.status_code, 200) AssertionError: 403 != 200 ---------------------------------------------------------------------- Ran 27 tests in 5.632s FAILED (failures=1) Destroying test database for alias 'default'... Views.py class AuthorCreate(PermissionRequiredMixin, CreateView): model = Author fields = '__all__' ###################################################### # You can set the initial values like this ###################################################### initial = {'date_of_death': '05/01/2018'} ###################################################### permission_required = 'catalog.can_mark_returned' test_views.py class AuthorCreateViewTest(TestCase): """Test case for the AuthorCreate view (Created as Challenge).""" def setUp(self): # Create … -
Sum an array of integers found in a JSONField in a Django query
I've got a JSONField in Django and Postgres that looks something like this: { "abc": [1, 3, 2, 1, 0], "bcd": [2, 3, 1], } This is in the data field of a Person model. I'd like to get the total of abc and annotate that total on the query. Something like this: people = Person.objects.annotate(abc_sum=Sum('data__abc')) Such that I have an annotation on my people results that provides the sum of the array value. -
DJANGO - class Meta / varibales db_table
I would like to get a variable in my meta class class Meta: abstract = True db_table = 'bikes_table' managed = False I want to get a variable from self like above : class Meta: abstract = True db_table = 'bikes_table' if self.customers=True else 'cars_table' managed = False Is it possible de get variable ? Thank you -
How to fetch time from database as local time
I created a model in django for postgresql this is my models.py class Other(models.Model): poster = models.ImageField(upload_to="articlepic", blank=True) text = models.CharField(max_length=300, blank=False) created_at = models.DateTimeField("created at", auto_now_add=True) I fetched the date(created at) by using axios in react.when I used below code <p className="mb-0"><small>{item.created_at.toLocaleString()}</small></p></div> then I am getting this 2020-10-21T19:14:34.864421Z But I need in format (Ex:- 2 June 2020).Then how should I write it? -
How i can change the name of the variable in Django?
i added 'Avaliação' to my test site, and, when i migrate the new function i noticed that the name of the variable that receives the TextField, appears in the site, so 'cause of aesthetics reasons, i try change the name of the variable. before: from django.db import models class Avaliação(models.Model): ava = models.TextField(max_length=250) data_ava = models.DateTimeField(auto_now_add=True) after: from django.db import models class Avaliação(models.Model): Deixe_sua_sugestão = models.TextField(max_length=250) #leave_your_suggest in pt-br# data_ava = models.DateTimeField(auto_now_add=True) And gave an OperationalError 'cause "no such columns" or something like that. Someone know how i can change the name of the variable WITHOUT open the file django.db and delecting the tables? -
ican't correct the error no such column in django
my directory What do i have to do? from django.db import models class Product(models.Model): a = models.CharField(max_length=200) b = models.CharField(max_length=200) c = models.CharField(max_length=200) d = models.CharField(max_length=200) my error is no such column and i"ve tried several times. -
Dynamically setting path to static file in Django
In Django, I'm trying to dynamically set the path to a static JavaScript file in a subfolder parsed from the URL. Not sure if this a good way to do it in Django (i.e. best practice), or if I am completely off. It seems like way too many steps and not very DRY, especially the views.py code. Will Django allow me to parse the request in the view (base.html) template and bypass the views.py step? I could use JavaScript, but is it possible in Django? Static file configuration has been defined in myproject/myproject/settings.py as: STATIC_URL = '/static/' My static files are set up as follows Note: each main.js file contains scripts specific to that page. /static/ └── js/ ├── global.js ├── home/ │ └── main.js ├── projects/ │ └── main.js └── users/ └── main.js If this is my URL: http://example.com/projects Views.py: I set a file path relative to my STATIC_URL path def projects(request): context={'js_file':'js/projects/main.js'} return render(request, 'pages/projects.html',{'context':context}) Which I use in my base.html layout template to set the JavaScript path {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- template head content --> </head> <body> <!-- template content --> <script src="{% static context.js_file %}"></script> </body> </html> This renders the … -
Using django-stripe's built-in webhook support
I'm using Django 3.0, Django-Stripe 2.0, and the Stripe CLI. django-stripe provides native support for Stripe webhooks, and their documentation says to include the following in my django project's main urls.py file to expose the webhook endpoint: url(r"^stripe/", include("djstripe.urls", namespace="djstripe")), I have done this, but how do I now leverage the endpoint? As a separate experiment, I created a payments app, setup the URL conf, and successfully called the view when triggering the non django-stripe webhook endpoint via the Stripe CLI. But it doesn't use any djstripe functionality: # project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('stripe/', include("djstripe.urls", namespace="djstripe")), path('payments/', include("payments.urls", namespace="payments")), ] # payments/urls.py from django.urls import path from . import views app_name="payments" urlpatterns = [ path("", views.my_handler, name="my-handler"), ] # payments/views.py from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_handler(request, **kwargs): print(request.body) return HttpResponse(status=200) Running stripe listen --forward-to localhost:8000/payments/ and, in a separate window, stripe trigger product.created returns a 200 response. But stripe listen --forward-to localhost:8000/stripe/webhook/ and stripe trigger product.created returns a 500. Thank you in advance for your help.