Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should we use `from __future__ import annotations` in python 3.10+?
I know that this question might have more than one correct answer but I would love to get what y'all think. With the discussion going around PEP 563 and PEP 649 and the deprecation of the future, I'm still confused on what the best practice is. Looking at the two examples below: what would be future proof? What would be more performant? Which one is better supported by tools such as pyupgrade, ruff, or flake8-type-checking? In example 2, which syntax is preferred between queries and queries_2? Example 1: from __future__ import annotations from typing import TYPE_CHECKING from collections.abc import Iterable from django.contrib.auth.models import User if TYPE_CHECKING: from django.db.models import QuerySet users: QuerySet[User] = User.objects.all() queries: Iterable[QuerySet] = ... Example 2: from typing import TYPE_CHECKING from collections.abc import Iterable from django.contrib.auth.models import User if TYPE_CHECKING: from django.db.models import QuerySet users: "QuerySet[User]" = User.objects.all() queries: Iterable["QuerySet"] queries_2: "Iterable[QuerySet]" in the examples above, we can assume Iterable is not in TYPE_CHECKING because it is used elsewhere in the file. -
In Django how to use request to retrieve a selected value in a dropdown and split it into two separate values?
Currently I recover the selected value of the third dropdown (Extract_single_city) like this: city = request.GET.get("extract_single_city") I would like to do the same to recover the values of the second dropdown (Trip), using request, but creating two values (for example create departure to recover Madrid, and create destination to recover Barcelona). I'm using this solution with global, but I don't like it, I would like to use something with request global departure, destination departure = trip.city_departure.name, destination = trip.city_destination.name views.py def trip_selector(request): if "Hx-Request" in request.headers: trips = FullRecord.objects.none() #Dropdown 1: Country if request.headers["Hx-Trigger"] == "id_trip": country_id = request.GET.get("country") #Dropdown 2: Trips if country_id != "": trips = FullRecord.objects.filter(country_id=country_id) return render(request, "trips.html", {"trips": trips}) #Dropdown 3: Single City elif request.headers["Hx-Trigger"] == "id_extract_single_city": selected_trip = request.GET.get("trips") extracted_cities = [] #Extract single city if selected_trip != "": trip = FullRecord.objects.get(id=int(selected_trip)) trip_with_combined_names = trip.departure_destination split_trip = trip_with_combined_names.split("-") extracted_cities = split_trip return render(request, "extract_single_city.html", {"options": extracted_cities}) else: countries = Country.objects.all() return render(request, "form.html", {"countries": countries}) forms.html {% extends 'base.html' %} {% block main-content %} <div class="flex justify-between px-10 gap-5 mt-5"> <div class="flex flex-col w-full"> <!-- First Combobox --> <label for="id_country">Country</label> <select name="country" id="id_country"> <option value="">Please select</option> {% for country in countries %} <option value="{{ … -
Proxy database conection fails in django application running in ECS
I deployed both a django app and a ngnix proxy containers in ECS. The app container is running without errors. I could also connect to the database using a bastion instance and create a superuser. However, the proxy container has given me an error. Currently, it throws: django.db.utils.OperationalError: could not connect to server Should this error happen in the proxy? I'm confused. It looks like the connection to the database is working for Django. Here is the entrypoint bash using in the Django container: set -e python manage.py collectstatic --noinput python manage.py wait_for_db python manage.py migrate uwsgi --socket :9000 --workers 4 --master --enable-threads --module app.wsgi and here are the django container logs: spawned uWSGI worker 1 (pid: 11, cores: 1) spawned uWSGI worker 2 (pid: 12, cores: 1) spawned uWSGI worker 3 (pid: 13, cores: 1) spawned uWSGI worker 4 (pid: 14, cores: 1) WSGI app 0 (mountpoint='') ready in 2 seconds on interpreter 0x7f2e0c0b9980 pid: 10 (default app) | *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 10) mapped 364600 bytes (356 KB) for 4 cores *** Operational MODE: preforking *** Python main interpreter initialized at 0x7f2e0c0b9980 python threads support enabled your server … -
Problem with applying CSP policy for Google fonts file
I'm working on Django site (upgrade from version 2 to version 4), where I have to apply Content Security Policy. In other projects I did it with django-csp using project's settings, but in this case I only add 'csp.middleware.CSPMiddleware', to MIDDLEWARE settings, and all CSP is done by <meta http-equiv="Content-Security-Policy" ... tags. That's the first strange thing. After rendering the code of my home page looks like this: The error is: Refused to load the stylesheet 'https://fonts.googleapis.com/css?family=Roboto:wght@300' because it violates the following Content Security Policy directive: "default-src 'self' 'nonce-d0R7xtS9JR5LNg6UqQ5FCg=='". Note that 'style-src-elem' was not explicitly set, so 'default-src' is used as a fallback. The second strange thing is that I set the style-src-elem, but the error says I didn't. And information from DevTools: Why is it blocked? The fonts are available here I used the hints from the official CSP site on Google fonts here and everything seems to be OK, but the problem still exists. -
do not show the dynamic data in the tag list
[enter image description here](https://i.stack.imgur.com/g5sdk.jpg) in the image Turkish words: Kategori = category , Etiket = Tag I want to dynamically see the categories and tags I marked from the admin panel from the category and tag template, but they do not appear. I do not understand where I dıd wrong. topics html codes html {% extends 'partials/_base.html' %} {% load static %} {% block content %} <div class="all-title-box"> <div class="container text-center"> <h1>Courses</span></h1> </div> </div> <div id="overviews" class="section wb"> <div class="container"> <div class="row"> <div class="col-lg-9 blog-post-single"> <div class="row" style=""> {% for topic in topics %} <div class="col-lg-6 col-md-6 col-12 mb-4"> <div class="course-item"> <div class="image-blog"> <img src="{{topic.image.url}}" alt="" class="img-fluid"> </div> <div class="course-br"> <div class="course-title"> <h2><a href="{% url 'topic_detail' topic.category.slug topic.id %}" title="">{{topic.name}}</a></h2> </div> <div class="course-desc"> <p>{{topic.description | truncatechars:100}}</p> </div> </div> <div class="course-meta-bot"> <ul> <li><i class="fa fa-calendar" aria-hidden="true"></i> {{topic.date|date:"d M Y"}}</li> <li><i class="fa fa-book" aria-hidden="true"></i> {{topic.writer}}</li> </ul> </div> </div> </div><!-- end col --> {% endfor %} </div><!-- end row --> </div><!-- end col --> <div class="col-lg-3 col-12 right-single"> <div class="widget-search"> <div class="site-search-area"> <form method="get" id="site-searchform" action="#"> <div> <input class="input-text form-control" name="search" placeholder="Anahtarkelime ara..." type="text"> <input id="searchsubmit" value="Search" type="submit"> </div> </form> </div> </div> <div class="widget-categories"> <h3 class="widget-title">Kategori</h3> <ul> {% for category in categorys %} … -
Python Django Json Data Serialization
I've got an issue where I want to pass the whole data set of the profile page using data serialization as below, however the issue is that I get the output data with single quotes instead of double and I cannot parse it later on: View: def profile_page(request): if request.method == 'POST': form = WeightLogForm(request.POST) if form.is_valid(): weight_log = form.save(commit=False) weight_log.profile = Profile.objects.get(user=request.user) weight_log.save() return redirect('profile') else: form = WeightLogForm() user_weight_log = WeightRecord.objects.filter(profile__user=request.user).order_by('-entry_date') paginator = Paginator(user_weight_log, 10) page = request.GET.get('page') try: user_weight_log = paginator.page(page) except PageNotAnInteger: user_weight_log = paginator.page(1) except EmptyPage: user_weight_log = paginator.page(paginator.num_pages) serialized_data = [{'weight': str(record.weight), 'entry_date': record.entry_date.strftime('%Y-%m-%d')} for record in user_weight_log] return render(request, 'profile.html', { 'user_weight_log': user_weight_log, 'form': form, 'weight_data': serialized_data }) Html Template: <div id="weight-data" data-weight-data="{{ weight_data|safe }}"></div> Data output: [{'weight': '122.00', 'entry_date': '2023-09-28'}, {'weight': '123.00', 'entry_date': '2023-09-18'}, {'weight': '44.00', 'entry_date': '2023-09-15'}, {'weight': '85.00', 'entry_date': '2023-09-06'}, {'weight': '11.00', 'entry_date': '2023-09-06'}, {'weight': '12.00', 'entry_date': '2023-09-05'}, {'weight': '17.00', 'entry_date': '2023-09-05'}, {'weight': '44.00', 'entry_date': '2023-08-08'}, {'weight': '17.00', 'entry_date': '2023-06-08'}, {'weight': '33.00', 'entry_date': '2023-06-07'}] Javascript: var weightDataElement = document.getElementById('weight-data'); var weightDataJSON = weightDataElement.getAttribute('data-weight-data'); var weightData = JSON.parse(weightDataJSON); The error I get: Uncaught SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data -
Creating a link in ReactJS that will go to the Django admin site
I am looking for a way to link the Django admin site from ReactJS. Initially the domain of Django admin site is '127.0.0.1/admin' but the domain '127.0.0.1' will eventually change. Is there a way to make a dynamic code for this? -
Using prefix_default_language=False disable javascript translations
I have implemented javascript translations, following exactly the documentation. It works perfectly when I use prefix_default_language=True in my i18n_patterns fonction. But when prefix_default_language is set to False, all of the translations in javascript code are not working : document.write(gettext("this is to be translated")) Is this a know issue? Is there something Im missing? -
DRF Shows incorrect schema
I have a following viewset: class MyViewSet: @action(detail=False) def statuses(self, *args, **kwargs): serializer = self.get_serializer(MyModel.Statuses, many=True) return Response(serializer.data) And serializer for it: class LabelValueSerializer(serializers.Serializer): label = serializers.CharField() value = serializers.CharField() class Meta: fields = ("label", "value") I get the correct API response: [ { "label": "New", "value": "new" }, { "label": "Processing", "value": "processing" }, { "label": "Finished", "value": "finished" } ] But the Swagger API suggest that the model is like this suggesting only 1 object is returned and not the list of them. How can I fix this and get the documentation like: [ { "label": string, "value": string } ] -
Huey Monitor - Error occurred sending signal "executing" - database kills the connection
In a Django 4.1 project I have huey (2.4.5) with django-huey (1.1.1) and django-huey-monitor (0.7.1) set up. Redis broker. 5 queues, including default, and are run in docker containers: PYTHONBUFFERED=1 python manage.py djangohuey --queue queue_name --no-periodic --force-color The monitor is initialised as such in tasks/__init__.py: for queue_name in settings.DJANGO_HUEY["queues"].keys(): signal(queue=queue_name)(store_signals) on_startup(queue=queue_name)(startup_handler) Since adding django-huey-monitor Sentry has started to catch exceptions in @db_task tasks Error occurred sending signal "executing" OperationalError server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. Now, I've experienced something like that in the past (5+ years ago) and usually, it helped to add connection.close() at the end of the task imported from django.db thous @db_task should do it anyway. Now everything was running smoothly, @db_task and all, until I added signal monitoring. I tested one @db_task that should be closing the connection anyway, added the connection.close() - that one seems to go silent but another one started acting up. I'd like to solve it globally and have run out of ideas. Are the signals misconfigured? -
error: SMTP AUTH extension not supported by server
I want to send an email to change the password by using this module: from django.contrib.auth import views as auth_views and these are the detail in setting.py: # google account setting EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'MY EMAIL ADDRESS' EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = 'MY PSSWORD' EMAIL_USER_TLS = True DEFAULT_FROM_EMAIL = 'TEST site' I read that I should change the PORT to 465. When I changed that I got another error: SMTPServerDisconnected at /account/reset/ Connection unexpectedly closed What can I do to fix the problem? -
How to show django-allauth errors in my form
I have overrode django-allauth login page and signup page templates. But how can I show their errors? (errors like "your password is wrong", "passwords doesn't match", etc.) -
python django ,i got error in doing registrion for new account
Manager isn't available; 'auth.User' has been swapped for 'user.CustomUser' Request Method: POST Request URL: http://localhost:8000/auth/register/ Django Version: 4.2.5 Exception Type: AttributeError Exception Value: Manager isn't available; 'auth.User' has been swapped for 'user.CustomUser' Exception Location: /home/greyhack199926/Downloads/django/env/lib/python3.11/site-packages/django/db/models/manager.py, line 196, in __get__ Raised during: user.views.register_view Python Executable: /home/greyhack199926/Downloads/django/env/bin/python Python Version: 3.11.4 Python Path: ['/home/greyhack199926/Downloads/django/Main', '/usr/lib/python311.zip', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', '/home/greyhack199926/Downloads/django/env/lib/python3.11/site-packages'] Server time: Fri, 08 Sep 2023 08:01:22 +0000 i can not register account -
How to Import data from json to SQL database using django
I am in need of a guidance, any help would be much appreciated. I'm new to django ,and right now I am designing a web application based on django framework, The application uses SQL database, However the data that the application needs is being provided through a json file that's being regenerated every few seconds,now my question is, how can I export the json file into sql database using django.. How can I do it? The web application is a financial application , so the accuracy of the data and the data being updated as soon as being generated is a must. -
Efficiency and Challenges in a Multi-Layered Testing Platform with Microservices Transition
enter image description here First, let me introduce my platform. The platform is divided into three layers, as shown below: Piece Layer: It consists of a single user interaction action (e.g., click, input, keyword entry), followed by waiting for a specific element to load (or waiting for a fixed duration), and finally capturing a screenshot of the element for text validation. This combination is referred to as a "piece." It is the smallest operational unit and cannot be further divided. Process Layer: Multiple pieces are combined to form a process. A dataset can be added to a process, which can generate multiple test cases (referred to as "cases"). Case Layer: This layer manages the execution of test cases and allows viewing of execution results. Result Validation: Text validation is done through direct text comparison, while image validation utilizes AI for image comparison. Technology Stack: Python, Django, Playwright, TensorFlow, Docker, GitLab CI/CD. Questions: I am currently running 200+ test cases using a thread pool with 8 threads, and the execution is quite slow. I am in the process of refactoring the code and transitioning to a microservices architecture. Previously, everything was handled by a single Docker image, but now I want … -
django_filter, integrate form in classview
I have a Listview class that show a table (working), I also have a django_filter for filtering the table (working). I want a button in template Listview , that open the django_filter_form ( not working, only show submit buttom), how do that ? views.py from django.shortcuts import render from django.views.generic import ListView from django.views.generic.edit import FormView from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import Cmsexport from .filters import CmsFilter from django.contrib.auth.decorators import login_required class Cms(ListView): queryset = Cmsexport.objects.all().values() model = Cmsexport template_name = 'table.html' context_object_name = 'cms' paginate_by = 10 def get_queryset(self): queryset = super().get_queryset() self.filterset = CmsFilter(self.request.GET, queryset=queryset) return self.filterset.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.filterset.form return context filters.py: from django_filters import FilterSet from .models import Cmsexport class CmsFilter(FilterSet): class Meta: model = Cmsexport fields = { 'name': ['icontains'], 'state_text': ['icontains'], 'is_virtual': ['icontains'], } urls.py: from django.urls import path from django.views.generic import TemplateView from . import views from .views import Cms urlpatterns = [ path('', views.dashboard, name='dashboard'), path('table/', views.table_view, name='table_view'), path('cms/', Cms.as_view(), name='cms'), path('filters_form/', TemplateView.as_view(template_name='filters_form.html'), name='filters_form'), path('search/', views.search, name='search'), ] template/table.html: {% extends 'base.html' %} {% load crispy_forms_filters %} {% load crispy_forms_tags %} {% block content %} {% include 'filters_form.html' %} <a href="{% url 'filters_form' … -
django-corsheaders, No 'Access-Control-Allow-Origin
Let me appreciate your help in advance. I deployed FE and BE in different servers on different domains. django-corsheaders is in use in django to deal with CORS, but the response does not include Access-Control-Allow-Origin. I searched and tested out a lot but nothing worked. Also, I read this article "https://developer.mozilla.org/ja/docs/Web/HTTP/CORS" I understood the logic, so I couldn't get why my case was not working. The weirdest point is that some requests to specific endpoints return a response with Access-Control-Allow-Origin which makes me confused. Thank you for your advice. DJANGO settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddtriede', //tried to set corsheaders.middleware above here 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = getenv( 'CORS_ALLOWED_ORIGINS', 'http://localhost:3000,http://127.0.0.1:3000' ).split(',') CORS_ALLOW_CREDENTIALS = True Here is okay case response and request Response Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: "here is FE origin" Allow: POST, OPTIONS Cache-Control: public, max-age=0, must-revalidate Content-Length: 37 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Fri, 08 Sep 2023 04:39:17 GMT Referrer-Policy: same-origin Server: Vercel Strict-Transport-Security: max-age=63072000; includeSubDomains; preload Vary: Accept, origin X-Content-Type-Options: nosniff X-Frame-Options: DENY X-Vercel-Cache: MISS X-Vercel-Id: syd1::iad1::ssnw2-1694147954133-6c4eee9047a5 Request :authority: "here is FE origin" :method: POST :path: /api/jwt/verify/ :scheme: https Accept: */* Accept-Encoding: gzip, deflate, … -
django-crontab not working for background tasks on Django app
I am developing a django application in which I want to perform some automatic tasks from time to time. I was looking for different ways to perform my task and I found some solutions like using celery, django-background-tasks or django-crontab. I discarded the celery option because it would complicate a lot the infrastructure of the project and the idea is to keep it as simple as possible. For that reason, I wanted to try django-crontab. I based on this video and made a test task to test this library, but I do not get the desired results. This is the test task: import datetime def test_task(): file = open("test_output.txt", "a") file.write(str(datetime.datetime.now())+"\n") file.close() The previous code is on a cron.py file. As the video and the documentation says, add the necessary in the setting.py file: INSTALLED_APPS = [ 'validator', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_crontab', ] CRONJOBS = [ ('*/1 * * * *', 'validator.cron.test_task') ] The desired result is a test_output.txt file, with datetimes with ranges of 1 minute apart. I don't know what I'm doing wrong or what I need to do to make it work properly. If someone knows another simple way to automate tasks in django, … -
Django Model Validation to ensure a Object can't be Child of itself and parent of its children/ grand Children
I have a case where I have a WBS, which has a parent_wbs field as Foreign key. I am trying to ensure that User don't keep adding child of a WBS so a Limit of Max 4 dept. Secondly I also want to ensure, that on edit I am not saving an object as parent of itself or an object shouldn't be set as parent who is also child/ grand child of current Object. class WBS(models.Model): name = models.CharField(max_length=100) project = models.ForeignKey(Project, on_delete=models.CASCADE) num = models.IntegerField(default=0) parent_wbs = models.ForeignKey('WBS', on_delete=models.CASCADE, null=True, blank=True, related_name='children') created_on = models.DateTimeField(auto_now_add=True) created_by = models.IntegerField(blank=True, default=0) modified_on = models.DateTimeField(auto_now=True) # This field will be automatically updated on each save modified_by = models.IntegerField(blank=True, default=0) # You can specify your own logic for updating this field def is_valid_descendant(self, parent_wbs, max_depth=4): """ Check if this WBS is a valid descendant (child or grandchild) of the provided WBS, and also ensure that the depth of the relationship is not greater than max_depth. """ current_wbs = self depth = 0 while current_wbs and depth <= max_depth: if current_wbs == parent_wbs: return False current_wbs = current_wbs.parent_wbs depth += 1 return True def __str__(self): return self.name Here is my form validation class WBSForm(forms.ModelForm): … -
SerializedMethodField vs overriding save() method : What is the best choice to deal with calculated fields in django?
I develop a django app with a lot of calculated properties for business logic. For example, let us take model Task, that is just an ordinary task for students. It is necessary to obtain the number of users that likes this task, that solved it, attempted to solve it, etc Now I am using to approaches to this challenge. The first is to use SerializedMethodField solved_users_number = serializers.SerializerMethodField(method_name='get_solved_users_number') def get_solved_users_number(self, object): #business logic return 42 The second is to provide a field in the model I use and update it every time the model changes. Overriden save() method suits for such purposes. def save(self, *args, **kwargs): if not self.id: self.solved_users_number = 0 else: self.solved_users_number += 1 return super(Task, self).save(*args, **kwargs) What is the best choice to deal with calculated fields in django? I tried both and still not sure -
Ajax not displaying data on a web page in my Django app--and instead shows this >>> <cart.cart.Cart object at 0x0000014D574B3AD0>
I'm following VeryAcademy's Django E commerce tutorial on YouTube and I encountered and issue. I followed the tutorial precisely and reach the Ajax part where we pass the add_to_cart data to the cart page to be displayed--and instead of seeing the data--I see this <cart.cart.Cart object at 0x0000014D574B3AD0> what is this? I'm supposed to see the product details of the current items in cart--not this. Here is my Ajax code. I'm running Django: function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); $(document).on('click', '#add_button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: "{% url 'inventory:single_product_add_to_cart' %}", data: { productid: $('#add_button').val(), productqty: $('#select option:selected').text(), csrfmiddlewaretoken: csrftoken, action: 'post' datatype: 'json', }, success: function (json) { document.getElementById("basket-qty").innerHTML = json.qty }, error: function (xhr, errmsg, err) {} }); }) settings.py """ Django settings for ds_mp project. Generated by 'django-admin startproject' using Django 4.2.3. … -
Django AttributeError: 'ForeignObjectRel' object has no attribute 'through'
I have two django apps, app1 and app2. app1 has a ScenesConfig table, and then app2 has a Task. Their definitions are as follows: class ScenesConfig(models.Model): id = models.AutoField(auto_created=True, primary_key=True) name = models.CharField(max_length=128, null=True) class Meta: db_table = 'scenes_config' from django.db import models from app_1.models import ScenesConfig class Task(models.Model): task_name = models.CharField(max_length=100, db_index=True) source_type = models.CharField(max_length=100, default="") scenes = models.ForeignObject(ScenesConfig, from_fields=['source_type'], to_fields=['id'], null=True, related_name='task_scenes_config', on_delete=models.DO_NOTHING) def __str__(self): return self.task_name At this point, I conducted my first migration and there were no errors. When I added a blank=True attribute to the scenes field of the task table the next time, an error occurred during the migration: Applying app_2.0003_auto_20230908_0256...Traceback (most recent call last): File "/Users/donghao/test/test_migations/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 202, in handle post_migrate_state = executor.migrate( File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Users/donghao/.pyenv/versions/3.9.1/envs/weicai/lib/python3.9/site-packages/django/db/migrations/migration.py", line 129, in apply … -
Model's ImageField returning different results in viewset vs function-based view
I have a model for representing user ratings in a sample app I'm building using Django Rest Framework, and I'm weirdly getting different results for the ImageField depending on the kind of view I use to request the data. Here is my model: class Rating(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) rating = models.IntegerField() review = models.CharField(max_length=500) recipe = models.ForeignKey(Recipe,on_delete=models.CASCADE, related_name='ratings') published_date = models.DateField(default=date.today) updated_date = models.DateField(default=date.today) photo = models.ImageField(upload_to='images/ratings/', blank=True) I have the following Viewset set up for this model: class RatingViewSet(viewsets.ModelViewSet): serializer_class = RatingSerializer lookup_fields = ('id', 'recipe') filter_backends = [DjangoFilterBackend] filterset_class = RatingFilter queryset = Rating.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) def perform_update(self, serializer): serializer.save(updated_date=date.today()) and a separate simple function-based view to grab just the latest rating for the logged in user: @api_view(['GET']) def UserRating(request): recipe_id = request.query_params.get('recipe_id') try: rating = Rating.objects.filter(recipe=recipe_id, user=request.user).latest('updated_date') serializer = RatingSerializer(rating) return Response(serializer.data, status=status.HTTP_200_OK) except Rating.DoesNotExist: return Response({}) When I use the viewset to request the Ratings objects, the photo field is represented in each object like this: "photo": "http://127.0.0.1:8000/media/images/ratings/SuperKofBros64.jpg" but when I use the function-based view the field doesn't show the server address, like this: "photo": "/media/images/ratings/SuperKofBros64.jpg" Why would this field show up differently depending on the kind of view I'm using? Is there a … -
Google Cloud: Access to image has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I deployed a website on Google Cloud via Cloud Run. The site uses Django and Webpack. The resources are automatically loaded to a Google Cloud Storage bucket. However, when I try to load the website some resources are not loaded correctly: Access to image at 'https://storage.googleapis.com/<bucket-name>/bcf8ff28514bad926b0c.png' from origin '<URL of my website>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If I try to access the request just by copy-pasting the URL into the browser it works fine (I can see the image). By looking at the Request Header for the resources that do not load correctly, their Origin is set to the URL of my website, e.g. https://example.com. The resources that do load correctly don't have Origin in the Request Header. Moreover, this issue only appears on Chrome and Safari but not on Firefox. When I inspect the Request Header on Firefox, the origin is actually set to https://storage.googleapis.com/ (instead of https://example.com), which I assume it's the reason why the resources load correctly. I guess there are two ways to solve the problem, though I don't know what solution should be preferred and how to implement it: Find a way to set … -
Login method in DJango throwing table or view does not exist
I am trying to customize the login by writing backend authentication, but login is throwing error "table or view does not exist". when I am running code below error was throwing return self.cursor.execute(query, self._param_generator(params)) django.db.utils.DatabaseError: ORA-00942: table or view does not exist settings.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', # This is the default that allows us to log in via username 'App_CPL.authentication.AuthBackend' ] authentication.py from django.contrib.auth.models import User from App_CPL.models import GainsUsers class AuthBackend: """ Custom authentication backend. Allows users to log in using their email address. """ def authenticate( request, username, password): """ Overrides the authenticate method to allow users to log in using their email address. """ try: print("hit authenticate model"+ username + password) user = GainsUsers.objects.get(user_id=username) print(user) print("password "+password) print(user.real_name) if str(user.real_name)==password: print("hit authenticate model"+ str(user)) return user return None except User.DoesNotExist: return None def get_user(self, user_id): """ Overrides the get_user method to allow users to log in using their email address. """ try: return GainsUsers.objects.get(pk=user_id) except User.DoesNotExist: return None views.py def Login_user(request,Username1,Password1): print(Username1) print(Password1) Gains_Users=AuthBackend.authenticate(request,Username1,Password1) print("back to main funtion"+str(Gains_Users)) if Gains_Users is not None: print("main if condition") login(request,Gains_Users) return JsonResponse(str('1'),safe=False) else: return JsonResponse(str('0'),safe=False)