Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get_decoded method show "Session data corrupted" in Django session
I have an application which using Django 2.0 and I'm facing with an issue about session data today. (SECRET_KEY is a static string, and consistent among the app so this might not is the issue) The command I've tried is: from django.contrib.sessions.models import Session session = Session.objects.first() session.get_decoded() # Session data corrupted # {} Even when I clear all the sessions, login again for a new session but still facing the same issue. I really want to read the session from the backend using manage.py shell and those script above. -
How to return user session id alongside Django rest serializer output
I'm writing a web application with Django. In one of my APIs which is using Django rest_framework, I want to return user's session ID alongside the default response. I know how to get the session ID but I don't know how to put it alongside the response(for example, in a JSON format) This is my code: class HouseInfoSerializer(serializers.ModelSerializer): class Meta: model = House fields = '__all__' class HouseViewSet(generics.ListAPIView): serializer_class = HouseInfoSerializer def get_queryset(self): postcode = self.kwargs['postcode'] print(self.request.session.session_key, "*"*10) return House.objects.filter(postcode=postcode) -
python - group values when generating a json
I am generating below JSON using a piece of code. Basically, I need to group my generated JSON group by continent, and then country and languages [ { "continent": "South America", "regions": [ { "region": "ar", "country": "Argentina", "languages": [ { "language": "en-us" } ] }, { "region": "ar", "country": "Argentina", "languages": [ { "language": "es-ar" } ] }, { "region": "bo", "country": "Bolivia", "languages": [ { "language": "es" } ] }, { "region": "bra", "country": "Brazil", "languages": [ { "language": "en-us" } ] }, { "region": "bra", "country": "Brazil", "languages": [ { "language": "pt-br" } ] } ] }} I am generating above JSON using the below code. def get_available_locales_json(): locales = [] for locale in get_available_locales(): append_locale = True for entry in locales: if entry['continent'] == locale.region.continent: entry['regions'].append({'region': locale.region.code, 'country': locale.region.name, 'languages': [ {'language': locale.language.code} ]}) append_locale = False break if append_locale: locales.append( { 'continent': locale.region.continent, 'regions': [{'region': locale.region.code, 'country': locale.region.name, 'languages': [ {'language': locale.language.code} ]}] } ) return locales However, I need to group languages together without having an extra node for the country. something like below, [ { "continent": "South America", "regions": [ { "region": "ar", "country": "Argentina", "languages": [ { "language": "en-us", "language": "es-ar" } … -
How can I convert a duration or a string to an integer in a queryset in Django views.py?
I need to calculate the time difference between two rows. This duration then needs to be adjusted up to 1 if the total is 0, or if the total is over 15 minutes, adjusted to 0--I was going to put this corrected amount in strtime. Unfortunately, my calculated times are not correct nor can I convert the extracted minutes to an integer in order to test if the duration is > 15 or < 1. The only reason I converted to a string was to see if I could then convert to an integer--it didn't work. I also tried to convert to a pandas dataframe in order to do the calculations, but I could not get it back into some format to display properly on the html page. How can I do an accurate calculation between rows and how can I adjust from 0 to 1 or > 15 to 0? I have tried many different versions--just not having much luck. I normally work in javascript--this is my first Django project. I have sanitized and shortened the data. This page will fit into an existing Django setup. Thank you in advance! Code is below. models.py class testmodels(models.Model): primary_key_id = models.CharField(max_length=150, … -
Django queryset caching with exists()
Let's say, I'm trying to change the name of all profiles whose name is John to Mike queryset = Profile.objects.filter(name='John') Method 1: if queryset: queryset.update(name='Mike') Method 2: if queryset.exists(): queryset.update(name='Mike') QUESTION: Which method is more efficient? Usually, I use exists() in the same line as my filter, so it queries once. However, I'm not sure if Method 2 will make another query to the database, making it less efficient. -
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)?