Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is python-dotenv not working properly in Django project
I'm trying to send django form data via email using emails module and python-dotenv for environment variables. The .env file is along settings.py and it's loading the envs in settings.py accordingly, but I try this in views.py where I'm trying to set the aws ses credentials as environment variables, and everything seems to work, but the email is not sent, but then I re-enter the aws ses creds in plain back into views.py and everything works great again. Any ideas why with envs the email is not sent? Code in views.py import os import emails from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv(), verbose=True) ... part of code with creds: ... try: # Send the email r = message.send( to= os.environ.get("RECEIPIENT"), smtp={ "host": os.environ.get("HOST"), "port": 587, "timeout": 5, "user": os.environ.get("USER"), "password": os.environ.get("PASSWORD"), "tls": True, }, ) except BadHeaderError: return HttpResponse(f"response{r.status_code == 250}") I also tried this following the example in the official python-dotenv site using os.getenv(): ... try: # Send the email r = message.send( to=os.getenv("RECEIPIENT"), smtp={ "host": os.getenv("HOST"), "port": 587, "timeout": 5, "user": os.getenv("USER"), "password": os.environ.get("PASSWORD"), "tls": True, }, ) except BadHeaderError: return HttpResponse(f"response{r.status_code == 250}") -
Moving a Django Foreign Key to another model while preserving data?
I have a Django application where I have a basic user model and user profile model. class Office(models.Model): name = models.CharField() class User(models.Model): email = models.EmailField() offices = models.ManyToManyField(Office) class Profile(models.Model): user = models.OneToOneField(User) Each user has a profile and can be assigned to many different offices. What I am looking to do is have it so that a User can have many profiles, but the profiles can be assigned to different offices. At the moment, this isn't possible as the Office field is assigned at the User level and not the Profile level. I envision 2 ways to solve this: Find some way to move the offices field over to the Profile field. Create a new model something along the lines of ProfileNoUser that has a foreign key to the user model as well as have an offices foreign key within it. Which option do you think is best? If #1, how can I do that? -
Django - How to declare variable in template depending on condition
I'm looking to do something really basic but against all odds it seems like it's not as easy as it should be. I need to transcribe the following into django template syntax : p = '&' if '?' in request.path else '?' All I found so far to create variable is the with statement but I can't get what I need : {% if '?' in request.path %} {% with p='&' %}{% endwith %} {% else %} {% with p='?' %}{% endwith %} {% endif %} p needs to be available in all the template, and since I use a condition here, I can't afford to duplicate the html structure twice to put it inside the with statement. It has to be an easy way to do this that I'm missing... -
How to deploy a Django and React web application
Hi I've never deployed a full stack application, how can I deploy a django application with react in it onto the web? Do I need to seperate the frontend from backend? Do I need a cloud and virtual machine or just a hosting plan from popular hosting companies? -
Django can i reverse a parameterized url without passing any arguments?
app_name = 'app_name' path('url/<uuid:uuid>',someview.as_view(),name='somename') def get_url(): return reverse('app_name:somename',args=None) I want get_url to return 'url/' Is it possible? -
PasswordResetView in Django Allauth throwing invalid lookup error
I'm trying to override the PasswordResetView template. I've done so successfully by just creating a directory called account and placing password_reset.html My url looks liek this: url(r'^recover/$', PasswordResetView.as_view(), name='account_reset_password') Everything works fine, however, when I submit an email to have the password reset, I get the following error: Related Field got invalid lookup: is_active I'm not sure why this is happening. I'm using allauth and also Django's auth but for this particular instance i'm using the allauth views. -
Looking for help to make npm/pdfjs-dist work with Webpack and Django
I've been trying for a few hours replacing a link-based pdf.js with an npm install of pdfjs-dist, since I noticed that my links were not meant to be used as cdns and could become unstable as described here. I could not find much documentation on how to make that work other than a few examples, and when Webpack is involved they are mostly with React, while I am simply using ES6 in a Django framework (static compiling on the desired django directory, without using the webpack-plugin.) After exchanging several messages with one of the guys that work on pdf.js it seemed that my compiling errors were probably due to how Webpack handles internally the library. Here's what I am seeing: WARNING in ./node_modules/worker-loader/dist/index.js Module not found: Error: Can't resolve 'webpack/lib/web/FetchCompileAsyncWasmPlugin' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/worker-loader/dist' @ ./node_modules/worker-loader/dist/index.js @ ./node_modules/worker-loader/dist/cjs.js @ ./node_modules/pdfjs-dist/webpack.js @ ./src/js/views/pdfViews.js @ ./src/js/index.js WARNING in ./node_modules/worker-loader/dist/index.js Module not found: Error: Can't resolve 'webpack/lib/web/FetchCompileWasmPlugin' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/worker-loader/dist' @ ./node_modules/worker-loader/dist/index.js @ ./node_modules/worker-loader/dist/cjs.js @ ./node_modules/pdfjs-dist/webpack.js @ ./src/js/views/pdfViews.js @ ./src/js/index.js ERROR in (webpack)/lib/node/NodeTargetPlugin.js Module not found: Error: Can't resolve 'module' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/webpack/lib/node' @ (webpack)/lib/node/NodeTargetPlugin.js 11:1-18 @ ./node_modules/worker-loader/dist/index.js @ ./node_modules/worker-loader/dist/cjs.js @ ./node_modules/pdfjs-dist/webpack.js @ ./src/js/views/pdfViews.js @ ./src/js/index.js Child HtmlWebpackCompiler: 1 asset Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0 [./node_modules/html-webpack-plugin/lib/loader.js!./src/src-select.html] 4.57 KiB … -
Django Admin - How to embed View from Foreign Key
I have a simple relationship with a Question that contains a Label. class Label(models.Model): text = models.CharField(max_length=200) subtext = models.CharField(max_length=50) class Question(models.Model): title = models.ForeignKey(Label, on_delete=models.CASCADE) question = models.CharField(max_length=200) If I open up the admin panel to edit a Label, it shows 2 text fields to update the text and subtext. However, if I attempt to edit the Question, it'll be a dropdown list of all Labels. What is the best way to make it straightforward to edit the Question and it's child Label? In the example above, I would want all 3 text fields ( text, subtext and question ) in the same view and editing them will update the correct tables in the database. -
Django order_by('-id') is extremely slow
I have a model Line with a group Foreign key. I want to get the last 30 Lines under a certain id, within in a single group. To do that, I use this query: Line.objects.filter(group_id=8460, id__lt=10333449).order_by("-id")[:30] My problem is that this query takes 1.5s to get executed, whereas these two are done almost instantly (<30ms): Without the ordering: Line.objects.filter(group_id=8460, id__lt=10333449)[:30] Without the id__lt: Line.objects.filter(group_id=8460).order_by("-id")[:30] For info, I have 10M+ lines in total and about 13k lines in this group alone. How can I make the query faster when both using id__lt and order_by('-id')? -
How to joins multiple tables in Django
** I just need one more table join in my query ** I want to get sales of logged-in users with order detail and shipping address. I tried this queries but not getting desired results. orderitems = OrderItem.objects.filter( product__user=request.user, order__complete=1).order_by('-date_orderd') Now i want to get also address, city and state from the Shippingaddress model. I attached the models below. this is my current result. My models: Order Model: class Order(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) date_orderd = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) # product = models.ManyToManyField(OrderItem) def __str__(self): return str(self.id) Order items Model: class OrderItem(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, blank=True, null=True) order = models.ForeignKey( Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_orderd = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) price = models.FloatField(blank=True, null=True) def __str__(self): return str(self.product) Shipping Address Model: class ShippingAddress(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) order = models.ForeignKey( Order, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=150) address = models.CharField(max_length=150) city = models.CharField(max_length=150) state = models.CharField(max_length=150) zipcode = models.CharField(max_length=150) date_orderd = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address -
Django Display multipe categories on page
I have this model.py file: class Category(models.Model): title = models.CharField(max_length=255, verbose_name="Title") class Meta: verbose_name_plural = "Categories" def __str__(self): return self.title class Video(models.Model): title = models.CharField(max_length=128) description = models.TextField(default='') thumbnail = models.ImageField(default='default_thumbnail.png', upload_to='thumbnails') date_posted = models.DateTimeField(default=timezone.now) category = models.ForeignKey( Category, on_delete=models.SET_DEFAULT, #null=True, default=1, verbose_name="Category" ) def __str__(self): return self.title Each video has its own category and I want to display on one page a given number of films in each category. Currently, I'm only showing the last 5 videos on the page: def home(request): latest_videos = Video.objects.all().order_by('-date_posted')[:5] categories = Category.objects.all() context = { 'latest_videos': latest_videos, #'categories': categories, } return render(request, 'videos/home.html', context) I have no idea how to display a given number of movies in each category. I tried to send all the videos and query them on the template, but this is probably impossible. Any ideas? I'm still learning Django, but this time I found a problem I can't solve all day. Thanks -
Что надо знать Backend разработчику?
Я начал изучать языка программирования Python и двинулсч глубже и изучал фреймворков и наткнулся на Django и изучаю его и он мне понравился . Суть вопроса в том что , можно ли с помощью Django произвести или работать с Backend ? У меня просто путаница знаком с SQL . -
How to run Django and Node Server at the same time
I'll try to be as concise as possible. Here's what I've done so far: I processed some NLP data using textblob, tweepy, etc. I serialized the data using Django REST API. I'm using axios to do a GET request from my Django server and display on my express app (not using a fancy JS framework) Things seems to be going ok, except I'm trying to figure out if running two servers (Django and Express) is the most efficient way of running this app. Is there a way to simplify this? eventually I intend to put this on Github and allow people to view the application on their own machine. Any tips or links would be greatly appreciated!!! Kind regards. -
Django REST Framework Testing and Token Authentication
I have a REST API working and accessible via Postman with token authentication. I'm trying now to write tests for the API. This test case set up will work fine, though it returns a 401 status (as expected): class ModelCRUDTests(TestCase): def setUp(self): self.thing = TestThingFactory.create() self.client = APIClient() self.response = self.client.get( reverse('appname:things-detail', kwargs={'pk': self.thing.pk}), ) When I add credentials, I get an error from the GET request (debugging shows that the authentication is stored in the client correctly). Modified code: class ModelCRUDTests(TestCase): def setUp(self): self.thing = TestThingFactory.create() self.admin_user = TestUserFactory(is_staff=True) self.token = Token.objects.get_or_create(user=self.admin_user) self.client = APIClient() self.client.credentials(HTTP_AUTHORIZATION='Token '+self.token[0].key) self.response = self.client.get( reverse('appname:things-detail', kwargs={'pk': self.thing.pk}), ) Stack trace: Traceback (most recent call last): File ".../venv2/lib/python3.8/site-packages/rest_framework/relations.py", line 393, in to_representation url = self.get_url(value, self.view_name, request, format) File ".../venv2/lib/python3.8/site-packages/rest_framework/relations.py", line 331, in get_url return self.reverse(view_name, kwargs=kwargs, request=request, format=format) File ".../venv2/lib/python3.8/site-packages/rest_framework/reverse.py", line 47, in reverse url = _reverse(viewname, args, kwargs, request, format, **extra) File ".../venv2/lib/python3.8/site-packages/rest_framework/reverse.py", line 60, in _reverse url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) File ".../venv2/lib/python3.8/site-packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File ".../venv2/lib/python3.8/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'thing-detail' not found. 'thing-detail' is not a valid view function or pattern name. During handling of the … -
My form doesn't add data to database - Django
I've just started my journey with django. Form is displayed on page, data typing works well, but data doesnt go to database. Form is about registation system on page. models.py: from django.db import models from datetime import date class Users(models.Model): login = models.CharField(max_length=30) password = models.CharField(max_length=30) mail = models.CharField(max_length=40) create_date = models.DateTimeField(default = date.today(), blank=True) forms.py: from django import forms from .models import Users class Register(forms.ModelForm): password = forms.CharField(max_length=32, min_length = 8, widget=forms.PasswordInput) login = forms.CharField(min_length=4, max_length=30) mail = forms.EmailField() class Meta: model = Users fields = ['login','password','mail'] register.html: {% extends 'base.html' %} {% block content %} <div id="form-user"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="SAVE" /> </form> </div> {% endblock %} views.py: from django.shortcuts import render from .forms import Register from .models import Users def register(request): if request.method == "POST": form = Register(request.POST) if form.is_valid(): form.save(commit = True) form = Register() form = Register() return render(request, "register.html", {'form': form}) -
How to use node modules with Django?
I wish to use date-fns in my django project but not entirely sure how to proceed - I cannot rely on a CDN and need to somehow get it installed. I have run npm init in my root folder followed by npm install date-fns. This generated a node_modules folder and a package.json file. Not entirely sure how to proceed after this. What are the necessary steps? Do I just use <script src="{% static 'node_modules/date-fns' %}"></script> in my base.html file? -
Exclude a file from Django's autoreload in runserver
I have a particular module that takes a little long to load, and is unlikely to change when running my Django server (let's call it badmodule/badfile.py). However, when I run python manage.py runserver, the Django server will autoreload when any file changes (including badmodule/badfile.py). I'd like to keep the autoreload behavior, but just exclude it from watching anything in badmodule. -
Make POST request to my index route fetch API
In my "/" route I have a form with an input textarea field, when the form is submitted, it should dynamically show the content of the textarea, without reloading the page. I'm trying to implement this with fetch API on my Django app. I'm working on http://127.0.0.1:8000/ I have two problems: With the code down here, the console.log doesn't print anything, and If I change response.json() for response.text(), I'm getting the whole html code, not the thing I want to fetch I'm getting Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 2 in my js console when posting the form This is my js code: document.querySelector('form').onsubmit = (event) => { fetch("", { method: 'POST', body: JSON.stringify({ body: document.querySelector('#new_message').value }), headers: { "X-Requested-With": "XMLHttpRequest", "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { // Print result console.log(result) let div = document.createElement('div') div.innerHTML = (result.body); div.style.cssText = "border: 1px solid lightblue; padding: 10px; margin: 5px;"; document.querySelector('#posts').append(div); document.querySelector('#new_message').value = "" }); event.preventDefault(); } The POST method is being sent to the server, but the console throws this uncaught error. #new_messageis my textarea field id -
Gmail Schedule Send Email in Django
I want to mimic the functionality that Gmail has, where you can choose to send an email at a certain time (maybe 3:34 am tomorrow) in Django. I looked at something like django-crontab (https://pypi.org/project/django-crontab/). I came up with an idea to use django-crontab to achieve this: Make a crontab that runs every minute Every minute, check if there are any emails that need to be sent Send out those emails This feels a bit hacky and over-engineered. Is there a better way? Thanks! -
Multiple <slug:slug> urlpatterns on the root
Manual type in of URLs are super important for the website I'm working on. Almost all traffic will come from people going directly to domain.com/some-string/. Minimal traffic will come from search engines. This means making URLs as easy to remember as for people is very important. Is there a way to have multiple path('<slug:slug>/', ...) URL patterns in the root directory? For example my models: from django.db import models class Category(models.Model): class Meta: verbose_name_plural = 'categories' title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) description = models.TextField() parent = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True) def __str__(self): return self.title class Widget(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) # and various other parameters specific to Widget category = models.ForeignKey('Category', on_delete=models.PROTECT, related_name = 'widgets', null=True) def __str__(self): return self.title And my views: from django.views.generic import ListView, DetailView from .models import Category, Widget class WidgetDetailView(DetailView): model = Widget slug_field = 'slug' slug_url_kwarg = 'slug' class CategoryListView(ListView): model = Category slug_field = 'slug' slug_url_kwarg = 'slug' And my URLs: from django.urls import path from .views import WidgetDetailView, CategoryListView urlpatterns = [ path('<slug:slug>/', WidgetDetailView.as_view(), name='widget-detail') path('<slug:slug>/', CategoryListView.as_view(), name='category-list') ] But obviously this works for domain.com/widget-slug/ but not domain.com/category-slug/ because only the first URL pattern gets called and results in … -
Is there a way for URL to be only accessed through the same origin
I have a URL in my Django application. url(r'^settings/$', views.SettingsView.as_view(), name='settings') This url is just a TemplateView that shows an HTML page. I don't want this page accessed to the public. Is there a way for only the application can access it? For example, the application can call this URL and retrieve data, but any outside user can't. Is there a way to do this? -
Django if and elif statements not working (Integer field)
So I'm in development and I have an IntegerField representing the followers of a user and I'm trying to make (within the templates) different things happen visually depending on the amount of followers in this field. It isn't working though? It only works if all the user.followers in question have the condition instead of a single one This is generally what I'm trying to do {% if user.followers < 50000 %} {% include blahblahblah %} {% elif user.followers >= 50000 %} {% include blehblehbleh %} {% elif user.followers >= 100000 %} {% include bleubleubleu %} {% else %} {% endif %} I had this problem when trying to use the profile photo inside a button as the background image, it would just use the most recently added profile's, profile photo, over and over again for every button background image. Is there a way I can make a list of say 20 items, and just manually go through writing if statements for each item in the list? -
How to display all the available results to a search query in HTML
I have this search engine in django that when you look for let's say "release date" only displays one result with that date, but not all the available results with it. I was wondering how I can manage that, so that if I look for something that has more than one result, it will show all of them and not a random unique result. This is the search function in my view: def films(request): movies = [] if request.method == 'POST': film_url = 'https://ghibliapi.herokuapp.com/films/' search_params = { 'films' : 'title', 'films' : 'description', 'films' : 'director', 'films' : 'release_date', 'q' : request.POST['search'] } r = requests.get(film_url, params=search_params) results = r.json() if len(results): for result in results: movie_data = { 'Title' : result['title'], 'Release_date': result['release_date'], 'Director' : result['director'], 'Producer' : result['producer'], 'Description' : result['description'] } movies.append(movie_data) else: message = print('No results found') context = { 'movies' : movies } return render(request,'core/films.html', context) This is my html: {% load static %} <!DOCTYPE html> <html> <head> <title>Ghibli Studio | Movies</title> <link rel="stylesheet" href="{% static 'core/films.css' %}"> </head> <body> <div class="layer"> <div class=" header"> </div> <div class="wrap"> <form action='/films' method="POST"> {% csrf_token %} <div class="search"> <input type="text" name="search" class="searchTerm" placeholder=" Type movie name"> <link … -
Django permissions not working properly even when adding permissions
Python 3.7, Django 3.0 Hello everyone, I'm facing an issue with Django permissions. I have a simple Article class as a model, as shown below: class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField() active = models.BooleanField() borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) class Meta: permissions = [("can_mark_owned", "Set article as owned")] In my views.py, I have a view that's supposed to be available for users with the "can_mark_owned" permission only. Shown below: class AssignOwnerLibrarian(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): permission_required = ('article.can_mark_owned') template_name = 'articles/article_assign_owner.html' form_class = AssignArticleOwnerForm queryset = Article.objects.all() My problem is that I can only access this view when I'm logged in as a SuperUser, not with a user who has the permission(added the permission through the Admin page), where I get 403 Forbidden. In my testing file, I have the following code: class RenewBookInstancesViewTest(TestCase): def setUp(self): # Create a user test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD') test_user2.save() permission = Permission.objects.get(name='Set article as owned') test_user2.user_permissions.add(permission) test_user2.save() test_user2 = get_object_or_404(User, pk=test_user2.id) print(test_user2.has_perm('article.can_mark_owned')) # returns False For some reason the print on the last line returns False. Help would be highly appreciated, I've spent multiple hours now on this problem. Thank you! -
How to implement product variations on the same product as cookie in Javascript?
Working on an eCommerce app and I'm now able to add products to a shopping cart using Pure JS. For unauthenticated users, I'm storing the product details in a cookie/Local Storage and reading it in Django to display on the cart page. Here is what the cart cookie/LS looks like with productIds 1 & 2 and no product variation cart = {1: {'quantity': 2}, 2: {'quantity': 4}} I now want to add a product variation for size and the ability to add to cart the same product with different variations Desired output cart = {1: {'quantity': 1, 'size': 'S'}, 1: {'quantity': 1, 'size': 'M'}} Real output. The last is overwriting the first cartItems = {1: {'quantity': 1, 'size': 'M'}} Code var cart = JSON.parse(localStorage.getItem('cart')) if(cart == undefined ) { cart = {} localStorage.setItem('cart', JSON.stringify(cart)); } //productId is recorded on button click //size is recorded on button click if (cart[productId] == undefined) { cart[productId] = {'quantity': 1} cart[productId]['size'] = size } else if (size != cart[productId]['size']) { //If new size is added cart[productId] = {'quantity': 1} cart[productId]['size'] = size } else { cart[id]['quantity'] += 1 } localStorage.setItem('cart', JSON.stringify(cart))