Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django to display images
I am attempting to use Django to display 3 random images from a large list of user submitted images. Each image has other values associated with it like the author, so I've been making each image a model with the image field holding the image itself. Unfortunately, I can't figure out how to randomly pick from that list and pass it in to the .html page to display it correctly. So far, I've been able to get user submitted pictures to be saved as models and submitted to a folder /media/images/. My views.py will grab 3 random and unique pictures from that folder like so: def home_view(request): form = MForm(request.POST or None) if form.is_valid(): form.save() message_list = MModel.objects.all() #Get first random file file1choice = random.choice(os.listdir(DIR)) #Get second random file file2choice = random.choice(os.listdir(DIR)) while(file2choice == file1choice): file2choice = random.choice(os.listdir(DIR)) #Get third random file file3choice = random.choice(os.listdir(DIR)) while(file3choice == file1choice or file3choice == file2choice): file3choice = random.choice(os.listdir(DIR)) context = { 'file1': file1choice, 'file2': file2choice, 'file3': file3choice, } return render(request, "home.html", context) In my .html file that the user sees, I access each image passed like so: <img src="/media/images/{{ file1 }}" width="300" height="180" alt=""> Unfortunately, this doesn't allow me to actually access the … -
Why does django send_mail fails to send email with no errors?
I want to use send_mail in django, however it doesn't send any email. Here is my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'MY-GMAIL-USERNAME@gmail.com' EMAIL_HOST_PASSWORD = 'MY-GMAIL-PASSWORD' EMAIL_PORT = 465 EMAIL_USE_TLS = False EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = DEFAULT_FROM_EMAIL Then, I run python manage.py shell: from django.conf import settings from django.core.mail import send_mail subject = 'Test Subject' message = 'Test Message' email_from = settings.EMAIL_HOST_USER recipient_list = ['MY-YAHOO-USERNAME@yahoo.com'] send_mail(subject, message, email_from, recipient_list) It doesn't send the email and it prints: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Test Subject From: MY-GMAIL-USERNAME@gmail.com To: MY-YAHOO-USERNAME@yahoo.com Date: Mon, 09 Dec 2019 21:02:16 -0000 Message-ID: <157592533640.18842.5494330274157836181@thinkpad-e560> ------------------------------------------------------------------------------- 1 Test Message which seems to have no errors. Why doesn't it send the email? What is wrong? Why doesn't it log any errors? I've tried a pure python way and it works fine: import smtplib, ssl smtp_server = "smtp.gmail.com" port = 465 sender_email = "MY-GMAIL-USERNAME@gmail.com" password = 'MY-GMAIL-PASSWORD' receiver_email = 'MY-YAHOO-USERNAME@yahoo.com' context = ssl.create_default_context() server = smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) server.login(sender_email, password) server.sendmail(sender_email, receiver_email, 'Test Message') As I mentioned, this pure python way works fine! I'm confused. What did I do wrong? -
Why can't I PATCH Django REST Framework PrimaryKeyRelatedField to empty list?
I'm running into a weird issue in Django REST Framework. I'm attempting to add & remove groups to/from users using PATCH requests. I am able to PATCH to /api/users/:id/ to update the groups list, which is initially empty. For example, the following actions yield these results: PATCH /api/users/:id/ {"groups": [1]} -> Results in user with groups: [1] PATCH /api/users/:id/ {"groups": [1, 2]} -> Results in user with groups: [1,2] PATCH /api/users/:id/ {"groups": [1]} -> Results in user back to groups: [1] So I am successfully updating the state with PATCH requests. However the following fails to update accordingly: PATCH /api/users/:id/ {"groups": []} -> Results in user still at groups: [1] Here is my UserSerializer class: class UserSerializer(serializers.ModelSerializer): groups = serializers.PrimaryKeyRelatedField(many=True, queryset=Group.objects.all(), allow_empty=True, required=False) class Meta: model = User fields = ( 'id', 'username', 'first_name', 'last_name', 'is_staff', 'is_authenticated', 'is_superuser', 'email', 'groups' ) My suspicion is that it has something to do with PrimaryKeyRelatedField - I have tried many combinations of arguments to the constructor to no avail. -
My form does not send data to the db django
My form does not send data to the database. I have a form that after entering data and clicking 'Order' should send information to the database. However, this does not happen. It is a 'cart' which, after sending the data, should save in the Order table information provided by the user as well as data on ordered products. cart/views.py def cart_detail(request, total=0, counter=0, cart_items = None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) counter += cart_item.quantity except ObjectDoesNotExist: pass if request.method == 'POST': total = request.POST['total'] billingName = request.POST['billingName'] billingAddress1 = request.POST['billingAddress1'] billingCity = request.POST['billingCity'] billingPostcode = request.POST['billingPostcode'] billingCountry = request.POST['billingCountry'] shippingName = request.POST['shippingName'] shippingAddress1 = request.POST['shippingAddress1'] shippingCity = request.POST['shippingCity'] shippingPostcode = request.POST['shippingPostcode'] shippingCountry = request.POST['shippingCountry'] order_details = Order.objects.create(total=total, billingName=billingName, billingAddress1=billingAddress1, billingCity=billingCity, billingPostcode=billingPostcode,billingCountry=billingCountry, shippingName=shippingName, shippingAddress1=shippingAddress1, shippingCity=shippingCity, shippingPostcode=shippingPostcode, shippingCountry=shippingCountry) order_details.save() for order_item in cart_items: oi = OrderItem.objects.create( product = order_item.product.name, quantity = order_item.quantity, price = order_item.product.price, order = order_details ) oi.save() '''Reduce stock when order is placed or saved''' products = Product.objects.get(id=order_item.product.id) products.stock = int(order_item.product.stock - order_item.quantity) products.save() order_item.delete() '''The terminal will print this message when the order is saved''' print('The order has been created') return redirect('cart:cart_detail') return render(request, 'cart/cart.html', dict(cart_items … -
wagtail menus return an empty list menu_items
after added wagtailmenus to my wagtail project and it worked well, but when i add an item to my main menu and try to use it in my navbar it always return in empty list... it doesn't matter how many item in main menu it always give me empty list. this is my code in navbar. {% load menu_tags %} {% main_menu %} {% if main_menu %} {{ menu_items }} {% endif %} {% for item in menu_items %} and this is my code in base.html <!-- navbar --> {% load menu_tags %} {% main_menu template="base/navbar.html" %} -
Annotating data in Django Templates
I am attempting at rendering annotated data into my template My models looks like this class Content(models.Model): title = models.CharField(max_length=255) body = models.TextField() reviews_total = models.FloatField(null=True) def _str_(self): return self.title class Review(models.Model): content = models.ForeignKey(Content, null=True, on_delete=models.CASCADE) readability = models.CharField(max_length=500) readability_rating = models.IntegerField() actionability = models.CharField(max_length=500) actionability_rating = models.IntegerField() general_comments = models.CharField(max_length=500) avg_rating = models.IntegerField(null=True) And my template looks like this {% for content in content.all %} {{ content.title }} Reviews: {{ content.review_set.count }} Avg Rating: {{ ? }} {% endfor %} From the following query x = Content.objects.annotate(avg=Avg('review__avg_rating')) y = vars(x[pk]) y['avg'] Which will give me 4.0 for example. My goal is essentially to to insert y into Avg Rating {{ }} Is there a way similar to content.review_set.count? Or is it best to do in views? -
COPY failed: stat /var/lib/docker/tmp/docker-builder<num>/server/requirements.txt: no such file or directory
Appears to be some kind of context issue. I'm trying to figure out why this would work fine when spinning up a local Kubernetes cluser with Skaffold, but is failing to build the image properly when pushing to Azure. Basic structure is: test-app/ server/ requirements.txt Dockerfile azure-pipeline.yml skaffold.yaml I have the production server/Dockerfile as the following: FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 WORKDIR '/app' EXPOSE 5000 COPY ./server/requirements.txt . RUN pip install -r requirements.txt COPY ./server . CMD ["python", "manage.py", "collectstatic"] CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application"] I'm using the azure-pipelines.yml that was generated for me in the Pipelines section of Azure DevOps: # Docker # Build and push an image to Azure Container Registry # https://docs.microsoft.com/azure/devops/pipelines/languages/docker trigger: - master resources: - repo: self variables: # Container registry service connection established during pipeline creation dockerRegistryServiceConnection: '<connection-string>' imageRepository: 'testapp' containerRegistry: 'testappcontainers.azurecr.io' dockerfilePath: '$(Build.SourcesDirectory)/server/Dockerfile' tag: '$(Build.BuildId)' # Agent VM image name vmImageName: 'ubuntu-latest' stages: - stage: Build displayName: Build and push stage jobs: - job: Build displayName: Build pool: vmImage: $(vmImageName) steps: - task: Docker@2 displayName: Build and push an image to container registry inputs: command: buildAndPush repository: $(imageRepository) dockerfile: $(dockerfilePath) containerRegistry: $(dockerRegistryServiceConnection) tags: | $(tag) During the automated build it gets … -
Issue with question mark in Django url
Here is the example link: abc.com/Hi-Python? So, in the backend of Django, I need data "Hi-Python?", but I'm getting - "Hi-Python" url(r'^@(?P<title>[a-zA-Z0-9_\.!,\-\?\:\w\+]+)$', views.title, name='title'), Any hint, how to solve this issue -
ImportError: cannot import name 'python_2_unicode_compatible' when running migrations for Django-Invitations
First, I might want to mention I'm a beginner with Django. I'm trying to install Django-Invitations on my app to send sign up invitations. I followed their README instructions. pip install django-invitations # Add to settings.py, INSTALLED_APPS 'invitations', # Append to urls.py url(r'^invitations/', include('invitations.urls', namespace='invitations')), # Run migrations python manage.py migrate I also pip installed all the requirements from their requirements file: coverage==4.5.4 flake8==3.7.9 freezegun==0.3.12 mock==3.0.5 pytest==5.2.2 pytest-django==3.6.0 pytest-cov==2.8.1 tox==3.14.0 But I keep getting the same error when I run migrations for the first time: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\maxim\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\maxim\Desktop\Web … -
TemplateSyntaxError: Could not parse the remainder: '()' from 'size.toLowerCase()'
I am working through Python+Django on PythonAnywhere. I am attempting to AngularJS Options Groups to create dynamic web scripting that is dependent on drop down box selections. However, I am running into the error TemplateSyntaxError: Could not parse the remainder: '()'. Additionally, if I temporarily remove this trouble error in the html file to view the page, anything within brackets {{ }} does not show on screen. Why are these references not working? Does a Django web-app understand how to reference the .js file? I am using this sample tutorial as is. .html {% load static %} <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>Option Groups</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic"><link rel='stylesheet' href='https://gitcdn.xyz/cdn/angular/bower-material/v1.1.20/angular-material.css'> <link rel='stylesheet' href='https://material.angularjs.org/1.1.20/docs.css'><link rel="stylesheet" href="./style.css"> </head> <body> <!-- partial:index.partial.html --> <div ng-controller="SelectOptGroupController" class="md-padding selectdemoOptionGroups" ng-cloak="" ng-app="MyApp"> <div> <h1 class="md-title">Pick your pizza below</h1> <div layout="row"> <md-input-container style="margin-right: 10px;"> <label>Size</label> <md-select ng-model="size"> <md-option ng-repeat="size in sizes" value="{{size}}">{{size}}</md-option> </md-select> </md-input-container> <md-input-container> <label>Topping</label> <md-select ng-model="selectedToppings" multiple=""> <md-optgroup label="Meats"> <md-option ng-value="topping.name" ng-repeat="topping in toppings | filter: {category: 'meat' }">{{topping.name}}</md-option> </md-optgroup> <md-optgroup label="Veggies"> <md-option ng-value="topping.name" ng-repeat="topping in toppings | filter: {category: 'veg' }">{{topping.name}}</md-option> </md-optgroup> </md-select> </md-input-container> </div> <p ng-if="selectedToppings">You ordered a {{size}} pizza with {{printSelectedToppings}}.</p> </div> </div> <!-- Copyright 2018 Google LLC. All Rights … -
How to grant atomicity on clean() method in django Models
I'm currently using django's clean() method to implement custom validations in a Model. A have a DB for example that is 1:m and have the following structure: | Id | Foreign Key | Date | |:-----------|------------:|:------------:| | 1 | 1 | 20-11-2019 | | 2 | 1 | None | The custom validation grants that for the same Foreign Key, there is only one row where date = None As save() is not called in this method, @transaction.atomic would not work, hence, what is the best way to grant atomicity with this method? I'm using python 3.7, django 2.2.6 and Postgresql -
Django Cron, execute def from views
I have a problem. I needto implement a function that will be called cyclically this cron.py: from django_cron import CronJobBase, Schedule from django.shortcuts import get_object_or_404, render, redirect from django.http import HttpResponse, HttpResponseRedirect, Http404 class MyCronJob(CronJobBase): RUN_EVERY_MINS = 60 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'CRM.my_cron_job' def do(self): return redirect('dashboard/dashgenerate/') dashgenerate is a def from another app in project: def dashgenerate(request): ..... -
ModuleNotFoundError: No module named <module_name> although module was installed
I'm trying to run server for my django app, and I've used TinyMCE editor for admin panel. Although I've installed it with command pip3 install django-tinymce application returns me such error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/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 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'tinymce' -
How do I change the default Django engine database from db.sqlite3 to a mysql database populated with test data?
This is my first time doing this so please bear with me. What I am trying to do: Change the 'DATABASES' setting in my 'settings.py' from the 'ENGINE: 'django.db.backends.sqlite3' to a pre-populated mysql database with test username data. More specifically, I want to change the default django database from db.sqlite to a mysql database. The mysql database I am trying to use instead of the default already has user information which I want to use and test. What I have done so far: I have already authenticated a couple of users(using the default db.sqlite3) to be able to add blog posts on my website which is currently hosted on a domain. What I am not sure about: Was changing the settings.py DATABASE default something I should have done at the very beginning ?? Or can I change it at any time without risking previously made changes? Does replacing the DATABASE default settings with something like the one below affect already existing user data ?? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '{{projectName}}', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '3306', } } What is the proper way to go about this given that I already have my blog website … -
How to route to a url based on data entered in Django form?
At first , I would like to take an integer input from user . After getting the input , I would like to go to the url based on what the user has entered . However , I am not able to implement it . Here's my urls.py file: urls.py urlpatterns = [ path('',views.page1), re_path(r'^form/(?P<data>[1-4]{1})',views.page2), ] Here's my views.py file: views.py from django.shortcuts import render from .forms import CustomForm1 from django.http import HttpResponse import requests # Create your views here. def page1(request): if request.method == 'POST': form = CutsomForm1(request.POST) if form.is_valid(): data = form.cleaned_data['data'] else: form = CustomForm1 data = 0 return render(request,'homepage/base.html',{'form':form,'data':data}) This is my forms.py file: forms.py from django import forms class CustomForm1(forms.Form): data = forms.IntegerField(label='data',required=True) And here's the HTMl: HTML <form method="POST" action="form/{{ data }}"> {% csrf_token %} {{ form.as_p }} <ul class="actions"> <li><input type="submit" value="Send Message" class="primary" /></li> <li><input type="reset" value="Clear" /></li> </ul> </form> Initially , when the form is loaded , my data variable has value 0 , but I want to it get the value which is entered by user , hence , I can then route to the desired url as per the updated data variable which is passed as context . For … -
Django Webhook creates double database entries
I'm currently using Django to code a webhook application for google Dialogflow. It was working fine, I was basically done. For some reason, I now started encountering various randomly appearing problems, one of the worst being the following: Whenever the webhook executes the user account creation call, it creates a double-database entry, which crashes the program (because my .get suddenly returns multiple elements instead of a single user). I'm using the following simple models: # model to create user entries class TestUser(models.Model): name = models.CharField(max_length=200) userID = models.CharField(max_length=12, blank=True) registrationDate = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name # model to add watched movies to user class Movie(models.Model): username = models.ForeignKey(TestUser, on_delete=models.CASCADE) title = models.CharField(max_length=200, blank=True) genreID = models.IntegerField (blank=True) def __str__(self): return self.title def list_genre_id(self): return self.genreID The part that gets executed in my webhook while the problem occurs should be the following: if action == "account_creation": selection = req.get("queryResult").get("parameters").get("account_selection") if selection == "True": q = TestUser(name=f"{username}", userID=idgen()) q.save() userID = TestUser.objects.get(name=f"{username}").userID fullfillmenttext = {"fulfillment_text": "Alright, I created a new account for you! Would you like to add " "some of your favorite movies to your account?", "outputContexts": [ { "name": f"projects/nextflix-d48b9/agent/sessions/{userID}/contexts/create_add_movies", "lifespanCount": 1, "parameters": { "data": "{}" } }]} This … -
Django Custom Permissions not synced to DB
I am newbie to Python and Django. I am trying to addd custom permissions using Django documentation. I added new permissions to model meta data. class Project(models.Model): class Meta: permissions = [ ("create_project", "Can create project"), ("update_project", "Can update project"), ("view_project", "Can view project") ] Then I ran python3 manage.py makeintegrations [app_name] and output was app/migrations/0009_auto_20191209_1848.py - Change Meta options on project Then I ran python3 manage.py migrate [app_name] and output was Applying app.0009_auto_20191209_1848... OK But I do not see new permission added to auth_permission. I tried --run-syncdb option but that did not work as well. What I am doing wrong and how I can debug this issue? thanks, -
Django rest_ramework error "Object of type UserToken is not JSON serializable"
I use django_rest framework and do authorization manually. I use tokens, which I also generate myself. When trying to authorize an error occurs "Object of type UserToken is not JSON serializable". I know that there is a lot of what's wrong here, but still, what is the error? (password verification I will do later) My view class: class SinginUserView(generics.GenericAPIView): serializer_class = SigninUserSerializer model = get_user_model() def post(self, request): username = request.POST["username"] user_id = User.objects.get(username=username).id token = UserToken.objects.get(id=user_id) return Response({'token': token}) My Serializer class: class SigninUserSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = ("username", "password") -
Why does Django REST Framework PATCH add a list element but will not remove an element?
I'm writing a unit test for my /api/users/:id/ endpoint exposed using Django REST Framework. I know that PATCH works properly because the following test passes as expected: Successful Test: Add Group to User def test_add_group_to_user(self): self.client.login(username=self.admin.username, password=self.admin_password) url = f'/api/users/{self.user_a.id}/' groups_before = self.client.get(url).data['groups'] # Groups: [] self.client.patch(url, data={'groups': [self.group.id]}) groups_after = self.client.get(url).data['groups'] # Groups: [1] self.assertTrue(len(groups_after) == len(groups_before) + 1) However, when I attempt to remove the group from the user using the same PATCH endpoint, the response returns a 200 but the groups collection still contains the item. See the failing test below. Unsuccessful Test: Remove Group From User def test_remove_group_from_user(self): self.client.login(username=self.admin.username, password=self.admin_password) url = f'/api/users/{self.user_a.id}/' self.client.patch(url, data={'groups': [self.group.id]}) groups_before = self.client.get(url).data['groups'] # Groups: [1] self.assertTrue(self.group.id in groups_before) response = self.client.patch(url, data={'groups': [g for g in groups_before if g != self.group.id]}) groups_after = self.client.get(url).data['groups'] # Groups: [1] self.assertTrue(self.group.id not in groups_after) I know the list comprehension [g for g in groups_before if g != self.group_id] returns the expected value, [], and I have also tried passing [] directly into the PATCH data. Why won't PATCH update groups to the data I provide? -
Add custom log records in Django
I've added the following logging configuration to my Django App's settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } Now, I simply want to add some custom log records to one of my views in views.py, but it appears the logger is NOTSET, which means only levels of warning and higher are logged: import logging from django.http import JsonResponse logger = logging.getLogger(__name__) def testing(request): logger.info("Doesn't show...") logger.warning(f"Log Level: {logger.level} = {logging.getLevelName(logger.level)}") return JsonResponse({"Hello": "World"}) The snippet above logs the following: Log Level: 0 = NOTSET Am I doing something wrong? Why is the logger's level not set (even though I clearly set it in settings.py)? -
Django - save changes made to model objects and render when published
I am new to Django and working on my first project in Django. I am providing a simpler example for my application where - I have 3 different types of users for the application. Teacher's Assistant - Schedules/plans the timetable and courses for the teacher depending on day's agenda Teacher - approves the items on the agenda and marks if an item on the schedule is completed Student - views the schedule of an individual teacher Currently, I have this whole application ready with all its functionalities, where the assistant would create a timetable/schedule (ie., add/edit/delete various model objects which are subjects) for the teacher depending upon her courses and agenda for the class. Currently, when the assistant, makes changes to the schedule (such as deletes, or edits an existing model object) these changes directly update the model object. What I would want to achieve is that, only when the Assistant publishes the schedule, the teacher can approve and students should be able to view it, and the assistant should have his own version of the schedule where he can make changes and edits to it (These changes and edits should not be viewed by other two roles unless they … -
How to use Google Drive to save media files for a Django app that is deployed in Heroku?
Is it possible to use Google Drive to save all the media files (image files which users will upload) from a Django app? This app will be deployed in Heroku (free). I am also aware of Amazon S3 but I want to avoid it as its not free after 12 months. I noticed that after deploying the app in Heroku, the static images are loading fine (using whitenoise) but those which are uploaded using ImageField from a model are not loading. I do not have any experience with Google APIs or even with Heroku for that matter and I could not find much information on if this integration is possible. If yes, it would be really great if I can get more details on how to go about it. I am currently using the latest version of Django (V3.0) along with Python 3.7.5 (64 bit). -
How to transfer GeoQuerySet.distance(geom, **kwargs) from Django 1.8 to Django 3.0?
I found this example in the Django 1.8 documentation. And it’s very important for me to follow the same steps, but in Django 3.0 (or 2.2). class AustraliaCity(NamedModel): point = models.PointField() radius = models.IntegerField(default=10000) allowed_distance = models.FloatField(default=0.5) pnt = AustraliaCity.objects.get(name='Hobart').point for city in AustraliaCity.objects.distance(pnt): print(city.name, city.distance) But AustraliaCity.objects.distance(pnt) causes an error in Django 3.0. AttributeError: 'AustraliaCity' object has no attribute 'distance' I will be grateful for any advice. -
Is there a way to filter for more than one value in the same column of a table?
I am realy frustrated and don't know what to do. I build a Website, where you can filter for beverages with many parameters, for example for the name of an Item, for the brand usw... But I also want to add a checkbox field, where you can mark certain volumes and filter my database for them. So lets say, I want to filter by the name Cola, by brand Coca Cola and by Volume 0.7L and 1L. Now I want that all Items in my table get displayed, wich have the name Cola brand Coca Cola and wich have a volume of 0.7 liter and 1 liter This does not work, because I filter for two different values in one column, wich is not possible in this way, because the field "volume" cant be 0.7 and 1. qsf = Content.objects.all().filter(Q(products__icontains=Cola) & Q(volume=0.7) & Q(volume=1) & Q(brand=Coca Cola)) I cant use the or operator (|) eather, because than my filter don't work. This is like my 3 post, because I don't know how to solve this problem, I realy hope you guys can help me. -
Customizing JWT error exceptions using PyJWT library in django
How can I customize JWT exceptions in pyjwt? For instance normally in pyjwt the response that is returned when someone does not provide credentials would be: { "detail": "Authentication credentials were not provided." } But I want to customize the response to return something like this: { "success": False, "msg": "Authentication credentials were not provided.", "data": None }