Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't figure out the Reverse for 'cart_add' with arguments '('',)' not found error. 1 pattern(s) tried: ['cart/add/(?P<product_id>[0-9]+)/\\Z']
There is a form in the product detail view template that doesn't work and throws an error. Here is my code: cart/cart.py from decimal import Decimal from django.conf import settings from TeaYardApp.models import Products class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): product_ids = self.cart.keys() product = Products.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in product: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.save() cart/Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from TeaYardApp.models import Products from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Products, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data … -
I am trying to deploy my website on Pythonanywhere.com but I having "ModuleNotFoundError". How do I debug?
Error running WSGI application ModuleNotFoundError: No module named 'starclone' File "/var/www/wholes_pythonanywhere_com_wsgi.py", line 16, in application = get_wsgi_application() -
Django ModelForm not displaying Model Verbose Name
I am trying to get my Django ModelForm to label my select dropdown boxes with the Model verbose names. According to the DjangoModel Form documentation "The form field’s label is set to the verbose_name of the model field, with the first character capitalized." # model.py class StLouisCitySale208(models.Model): landuse = models.CharField(max_length=254, blank=True, null=True, verbose_name="Land use") neighborho = models.CharField(max_length=254, blank=True, null=True, verbose_name="Neighborhood") # form.py class StLouisCitySale208Form(ModelForm): required_css_class = 'form-group' landuse = forms.ModelMultipleChoiceField(widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('landuse', flat=True).distinct()) neighborho =forms.ModelMultipleChoiceField(widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('neighborho', flat=True).distinct()) policedist = forms.ModelMultipleChoiceField(widget=forms.SelectMultiple,queryset=StLouisCitySale208.objects.values_list('policedist', flat=True).distinct()) class Meta: model = StLouisCitySale208 fields = ['landuse', 'neighborho', 'policedist', 'precinct20','vacantland', 'ward20', 'zip', 'zoning','asmtimprov', 'asmtland', 'asmttotal', 'frontage', 'landarea','numbldgs', 'numunits'] -
Django Template: Dynamic template variable inside another variable
I hope this makes sense... I am building a crypto asset list page (easy); however, in the {% for %} loop I would like to include a variable inside a variable. Showing the code will make more sense: Tempalte.html {% for crypto_asset in objects__list_cryptoAssets %} <tr role="row" class="body-row"> <td role="cell">{{ api_external_prices.bitcoin.usd }}</td> </tr> {% endfor %} So the {% for %} loop grabs all the crypto assets and then I can use Django template {{ asset_class.slug }} to grab all slugs... nothing exceptional here. This variable {{ api_external_prices.bitcoin.usd }} grabs external USD prices for Bitcoin, {{ api_external_prices.bitcoin.eur }} prices in EUR, and so forth... nothing exceptional here either. Here is where the question comes :: the idea would be to have something like {{ api_external_prices.{{ asset_class.slug }}.usd }}... so each crypto would have its own price FX fetched correctly. Is it possible to have a variable inside a variable? -
Django Subquery Sum with no results returns None instead of 0
I have a Django Subquery which returns a Sum. If the subquery finds at least one result, it works fine. But, if the subquery finds no records, it returns None which then causes any other calculations using this result (I use it later in my query in an F expression) to also result in None. I am trying to Sum all non-null 'consumed' values - sometimes, they are all null and therefore there are no rows upon which to sum. I would like this to result in a 0 instead of None ... annotate(tapx=Subquery(InvTrx.objects.filter(job=OuterRef('job')).\ filter(consumed__isnull=False).\ filter(inventory__inv_type='APX').\ values('job__job').\ annotate(tot_cons=Sum('consumed', default=0)).\ values('tot_cons') )).\ ... I've tried Coalesce with and without Value(0) annotate(tot_cons=Coalesce(Sum('consumed', default=0)), 0).\ annotate(tot_cons=Coalesce(Sum('consumed', default=0)), Value(0)).\ the value of tapx (which I reuse in F expressions in another part of the query) = None if no rows are returned. If at least one row is returned, this works fine. If no rows are returned, I would like the value of tapx to be 0 instead of None so that the value of fg_total in the following annotation results in a number and not None: annotate(fg_total=F('fg') + F('tapx')) Doing this outside a subquery, I have used "or 0" to force the value … -
Best Project Structure for Multisite (subdomain) in Django
We want to develop the software to be used in our university with Django. For web site we have one main domain and 150 subdomains. Please share your ideas and suggestions for the right project structure. For example, we will keep all our apps in a folder called apps. Do I need to do anything for the wsgi.py, settings.py and urls.py files of each subdomain? Best regards. -
Django Rest Framework Tests Failing When Using PostgreSQL
I'm new to Django and I recently changed the database from SQLite to PostgreSQL (first time using postgreSQL). I updated the settings with the below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'localhost' } } For the user, I'm not using the default postgress user, instead I created a new user (for which there is a User account on the OS) and added a password for it. I then gave that user permission to createdb: ALTER USER username CREATEDB; I've also installed psycopg2. When using the api normally, the PostgreSQL database updates just fine and works as expected. Originally when using SQLite, all the tests used to pass too. But when I changed to PostgreSQL using the above, 2 out of 9 tests fail. These are the tests that fail. The tests that fail are all under the same class. 6 of the tests are under a different class and they all pass fine. class APIDetailTest(APITestCase): items_url = reverse('site') item_url = reverse('site-item', args = [1]) def setUp(self): # Creating an initial entry to be tested. data = { "Name": "data name", "Description": "desc", "Date": "2022-06-11", "Time": "11:00:00", "Tag": "", } self.client.post(self.items_url, data, format='json') … -
How to use Admin Model as foreign key in django?
I try to develop a relationship as One admin can add one or many subscription plans. I try this but not worked from django.db import models from django.contrib import admin class SubscriptionPlansModel(models.Model): title = models.CharField(max_length=50) price = models.IntegerField() duraion = models.IntegerField() admin = models.ForeignKey(admin,on_delete=models.CASCADE) -
Problem in loading the logo in different URLs in Django
I have the same html for Tools.html and home.html but I realized the logo can be loaded in this URL: path('',views.home), But in this URL I do not see the logo and also the favicon: path('Tools/', views.Tools ), http://127.0.0.1:8000/ http://127.0.0.1:8000/Tools/ views: def Tools(request): p=product.objects.filter(category__name='Tools') return render(request,'Tools.html',{'p':p}) def home(request): p=product.objects.filter(category__name='home') return render(request,'home.html',{'p':p}) urls: urlpatterns = [ path('Tools/', views.Tools ), path('',views.home), ] the following codes are for favicon and logo in html file: <link rel="icon" type="image/x-icon" href="static/logo.png"> <img class="img" width="270px" src="static/logo.svg"> Why is this happening? -
Django - React - Google Cloud Storage SigedURL upload is not working
I have used signedURL with jquery/ajax and Django for uploading to Google Cloud Storage previously successfully. However with the Django - React setup I have not been able to establish a successful. upload yet. export const UploadVideo = async (form_data, file, signedurl, asset_uuid) => { let resultState = { state: '', data: {} }; let config = { method: 'HOST', url: signedurl, headers: { 'Content-Type': 'video/mp4', "Access-Control-Allow-Origin": "*", 'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS' }, data: form_data }; await axios(config).then(function (response) { console.log(JSON.stringify(response.data)); resultState.state = 'success'; }).catch(function (error) { resultState.state = 'error'; resultState.data.message = error.message; window.toastr.error(error.message); console.log(error) }) return resultState; } export const CreateAssets = async (data, key) => { let resultState = { state: '', data: {} }; await axios.get(`https://origin/asset/create/?category=1&title=%22` + data[key].title + `%22&size=1`) .then(res => { resultState.state = 'success'; resultState.data = res.data; }).catch((err) => { resultState.state = 'error'; resultState.data['message'] = err.message; }) return resultState; } The code for react js get singed url and calling signedurl with the file dialog is available. What shall I do for a succesful signedurl file upload to Google Cloud Storage ? -
Mypy complaining about Name "Optional" is not defined without the use of Optional
I've recently started using mypy, and have run into some weird problems that i cannot for the life of me seem to figure out. I'm using mypy 0.950, django-stubs 1.11.0, django 4.0.5 and python 3.10.2. Running mypy through the command line returns this: project/suppliers/models.py:6: error: Name "Optional" is not defined project/suppliers/models.py:6: note: Did you forget to import it from "typing"? (Suggestion: "from typing import Optional") project/users/models.py:6: error: Name "Optional" is not defined project/users/models.py:6: note: Did you forget to import it from "typing"? (Suggestion: "from typing import Optional") project/products/models.py:6: error: Name "Optional" is not defined project/products/models.py:6: note: Did you forget to import it from "typing"? (Suggestion: "from typing import Optional")(Suggestion: "from typing import Optional") However, line 6 in project/suppliers/models.py is completely empty: from django.contrib.sites.managers import CurrentSiteManager from django.contrib.sites.models import Site from django.db import models from django.utils.text import slugify from django.utils.translation import gettext_lazy as _ from django_countries.fields import CountryField from project.core.models import BaseImageModel, BaseModel from project.suppliers.managers import SupplierQuerySet _SupplierManager = models.Manager.from_queryset(SupplierQuerySet) class Supplier(BaseModel, BaseImageModel): ... Line 6 in project/users/models.py is a django import from django.contrib.contenttypes.models import ContentType: import random from typing import Any from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.contrib.contenttypes.models import ContentType from django.contrib.sites.managers import CurrentSiteManager from django.contrib.sites.models … -
How can i change the Name of my Django App shown in Browser Window?
I want to change the name of my Django app shown in Browser Window (at the top in the tab) when running my website on a server. For me is not required to change the entire project name, I just want to change the name shown in the Browser: enter image description here -
convert function based view to class based view django
I am tried to do get form data by POST method in a variable and then try to validate it. I have done it with django function based view. But now I want to convert it into django class based vied. So can any one help to convert my following code to django class based view. from .forms import contact_form def contact_us(request): if request.method == "POST": form = contact_form(request.POST) # return HttpResponse(form) if form.is_valid(): return HttpResponse("Data is valid") else: return HttpResponse("Data is invalid") -
Django - Use Django Validators as standalone
How can I use Django validators component as standalone component in non-Django applications ? Currently I use Django ORM in my applications. manager.py import os from dotenv import load_dotenv load_dotenv() def init_django(): import django from django.conf import settings if settings.configured: return settings.configure( TIME_ZONE=False, INSTALLED_APPS=[ 'db', ], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('db_name'), 'USER': os.environ.get('db_user'), 'PASSWORD': os.environ.get('db_password'), 'HOST': os.environ.get('db_host'), 'PORT': os.environ.get('db_port'), } } ) django.setup() if __name__ == "__main__": from django.core.management import execute_from_command_line init_django() execute_from_command_line() -
What is the best practice to write an API for an action that affects multiple tables?
Consider the example use case as below. You need to invite a Company as your connection. The sub actions that needs to happen in this situation is. A Company need to be created by adding an entry to the Company table. A User account needs to be created for the staff member to login by creating an entry in the User table. A Staff object is created to ensure that the User has access to the Company by creating an entry in the Staff table. The invited company is related to the invitee company, so a relation similar to friendship is created to connect the two companies by creating an entry in the Connection table. An Invitation object is created to store the information as to who invited who onto the system, with other information like invitation time, invite message etc. For this, and entry is created in the Invitation table. An email needs to be sent to the user to accept invitation and join by setting password. As you can see, entries are to be made in 5 Tables. Is it a good practice to do all this in a single API call? If not, what are the other … -
Change the django-rest-passwordrest confirm view
I've followed this tutorial to reset the user's password using the django-rest-passwordreset library and I was wondering if there's a way to update a user's field (called changed_password) once their password has been successfully changed. -
Deploy django react app to heroku: Migration error ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist
My deployed website right now just shows the Django Rest Framework Page with none of my css or data (https://ever-actor.herokuapp.com/api/lines/) I'm thinking it has something to do with the migrations because after running heroku run python manage.py migrate I get the following error: WARNINGS: ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. Here is my settings.py: from pathlib import Path import dotenv import dj_database_url import os from decouple import config BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1:8000', 'ever-actor.herokuapp', ] CSRF_TRUSTED_ORIGINS = ['http://localhost:8000'] CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'api.apps.ApiConfig', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' ROOT_URLCONF = 'ever_actor.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # BASE_DIR / 'ever-react/build' os.path.join(BASE_DIR, 'build'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ever_actor.wsgi.application' # Database DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600) # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Update api for a User Model and OnetoOne Profile model in Django Rest Framework
I have one model called profile which is related to Django User Model through one to one relationship. I want to create an api endpoint which will accept all the data and update both the tables whenever required. Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) manager = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True, related_name="manager" ) middle_name = models.CharField(max_length=50, blank=True) fpo = models.ForeignKey(Fpo, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField( upload_to="profile_images", blank=True, null=True, default=None, verbose_name="Profile Image", ) type = models.IntegerField( choices=UserTypeChoice.choices, default=UserTypeChoice.FARMER, verbose_name="User Type", ) gender = models.PositiveSmallIntegerField( choices=GenderChoice.choices, null=True, blank=True ) date_of_birth = models.DateField(null=True, blank=True) pincode = models.CharField( max_length=6, verbose_name="Pincode", blank=True, null=True, ) gat_no = models.CharField( max_length=20, verbose_name="GAT No", blank=True, null=True, ) landholding_in_acre = models.DecimalField( max_digits=10, decimal_places=2, default=0, ) is_member = models.BooleanField(default=False) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ( "middle_name", "manager", "fpo", "type", "date_of_birth", "gender", "gat_no", "landholding_in_acre", "landholding_registred_in_acre", "plotting_in_acre", "is_member", ) views.py class FarmersDetailView(generics.RetrieveUpdateDestroyAPIView): serializer_class = FarmerDetailsSerializer permission_classes = (permissions.IsAuthenticated,) authentication_classes = (TokenAuthentication,) def get_queryset(self): if self.request.user.is_authenticated: if self.request.user.profile.type == 3: return User.objects.filter(profile__type=4, manager=self.request.user) return User.objects.filter(profile__type=4) return User.objects.none() Not able to update with a single api. So here i want to update both profile and user models at the same time through a single endpoint. When I'll be … -
How to setup search in django-admin changelists in models related through ForeignKeys?
I have created the following four model classes: class InfrastructureModel(models.Model): ENTRY_ACTIVE_YES_NO_CHOICES = ( (True, 'Yes'), (False, 'No')) entryActiveYesNo = models.BooleanField(r"Is this database entry still active? (YES/NO)", null=False, blank=False, unique=False, choices=ENTRY_ACTIVE_YES_NO_CHOICES, help_text=r"Is this database entry still active? If it's been changed/modified to something else, mark this as False.") class AirportAdministrativeData(InfrastructureModel): officialAirportName=models.CharField(r"Airport's Official Name", max_length=100, null=False, blank=False, unique=True, help_text=r"Offical name of the Airport") def __str__(self): return self.officialAirportName class AirportAlternateName(InfrastructureModel): parentAirport=models.ForeignKey(AirportAdministrativeData,on_delete=models.RESTRICT,limit_choices_to={'entryActiveYesNo': True},verbose_name="Parent Airport",related_name='AirportOfficialName') alternateAirportName=models.CharField(r"Airport's Alternate Name", max_length=100, null=False, blank=False, unique=True, help_text=r"Alternate name of the Airport, if any.") class AirportLocation(InfrastructureModel): parentAirport=models.ForeignKey(AirportAdministrativeData,on_delete=models.RESTRICT,limit_choices_to={'entryActiveYesNo': True},verbose_name="Parent Airport") latitude=models.DecimalField(max_digits=9, decimal_places=6) longitude=models.DecimalField(max_digits=9, decimal_places=6) airportAddress=models.CharField(r"Airport's Address", max_length=200, null=False, blank=False, unique=True, help_text=r"Airport's Address") airportState=models.ForeignKey(State,on_delete=models.RESTRICT,limit_choices_to={'entryActiveYesNo': True},verbose_name="State") And their corresponding Admin classes are as follows: class AirportAdministrativeDataAdmin(admin.ModelAdmin): fields = ['officialAirportName', 'entryActiveYesNo'] list_display = ('officialAirportName', 'entryActiveYesNo') search_fields = ['officialAirportName'] search_help_text="Seach here for offical/alternate name of any airport in the Database." class AirportAlternateNameAdmin(admin.ModelAdmin): fields = ['parentAirport', 'alternateAirportName', 'entryActiveYesNo'] list_display = ('parentAirport', 'alternateAirportName', 'entryActiveYesNo') search_fields = ['alternateAirportName'] search_help_text="Seach here for offical/alternate name of any airport in the Database." class AirportLocationAdmin(admin.ModelAdmin): fields = ['parentAirport', 'latitude', 'longitude', 'airportAddress', 'airportState', 'entryActiveYesNo'] list_display = ('parentAirport', 'latitude', 'longitude', 'airportAddress', 'airportState', 'entryActiveYesNo') #search_fields = ['parentAirport'] search_help_text="Seach here for offical/alternate name of any airport in the Database." And their corresponding admin site registrations are … -
How to translate the name of permission in django
i have a question. When i add a group in django admin the permissions are displayed in English (can add, change etc) but i want to translate those permissions to in french since my website is based on django admin How can I do that? -
Django - Custom model cannot appear on User model
I have created a model in Django v4, and I want to show the information inside the User admin view. After migrating, a new table was created successfully and data is being stored. Here is the code: models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) address = models.CharField( max_length=20, blank=True, null=True ) def __str__(self): return self.user.username admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Profile class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'Extra Information' @admin.register(ProfileInline) class UserAdmin(admin.ModelAdmin): inlines = [ ProfileInline, ] The table that has been created has the following stored: id address user_id 3 Test 2 Where the user_id column, is a foreign key from the auth_user table, which is created automatically (I guess?). Now, when I try to run, makemigrations, etc, it shows me the following: AttributeError: type object 'ProfileInline' has no attribute '_meta' What is the proper way to have the information appended to the User, as the default sections do? -
Django + Caddy = CSRF protection issues
I deployed a Django 4 app with Daphne (ASGI) in a docker container. I use Caddy as a reverse proxy in front. It works, except I can't fill in any form because the CSRF protection kicks in. So no admin login, for example. I can currently access the admin interface in two ways: Directly through docker, via a SSH tunelled port Through Caddy, which is then forwarding to the Docker container. Option 1 works. I can log into the admin interface just as if I was running the development server locally. All is working as expected. However, option 2 (caddy reverse proxy) doesn't work. I can access Django and load pages, but any form submission will be blocked because the CSRF protection kicks in. CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed - https://<mydomain.com> does not match any trusted origins. My Caddyfile contains this: <mydomain.com> { reverse_proxy localhost:8088 } localhost:8088 is the port exposed by my docker container. In an effort to eliminate potential issues, I've set the following to false in my config file: SECURE_SSL_REDIRECT (causes a redirect loop, probably related to the reverse proxying) SESSION_COOKIE_SECURE (I'd rather have it set to True, but I … -
Django Tenants superuser creation
When we create a superuser per scheme via ./manage.py create_tenant_superuser --username=admin2 --schema=client2 The created super user can also login to "public" schema's admin page as well as other schema's admin pages. While it can NOT edit other tenants' data it can modify the other super tenants information such as password's created under other schemas. So is this the expected behavior? should each tenant have their own ,fully isolated admin page under /Admin? -
I have a problem with Django database. in model
I have specified that my bio and image fields can be empty, but why does it give me an error and say that I have to fill it in? class User_account(models.Model): email = models.EmailField() fullname = models.CharField(max_length=30) username = models.CharField(max_length=20) password = models.CharField(max_length=30) marital_status = models.BooleanField(default=False) bio = models.CharField(null=True, max_length=200) visitor = models.IntegerField(default=0) image = models.ImageField(null=True, upload_to='profile_img') -
react : unexpected token < in JSON at position 0 with api call to django restframework
I have a react app running ok when i put yarn start, but giving me this error when I do yarn build and serve -s build : Unexpected token < in JSON at position 0 The code in question is: fetch("/api/blog/tags/?format=json") .then(response=>{ if (response.ok){ return response; } else{ var error= new Error('Error '+response.status+': '+response.statusText) error.response = response; throw error; } }, I have tried to change the api call adding ?format=json like this : /api/blog/tags/?format=json But I still have this error. From the many posts on the subject, i have seen it is caused by a body page in html when the fetch method is expecting json. But i dont know where to investigate to debug this now. Thank you