Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inspect db Issue
I am working on a Django project but when I perform the database inspection in the app and try to run the project it fails with the following error. OSError: [WinError 123] The filename, directory name or volume tag syntax is not correct: '' What is the best way to handle this? This is my database config DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'pos_service', 'USER': 'demoLogin', 'PASSWORD': 'demoLogin', 'HOST': 'LAPTOP-EQ88J4ES\SQLLOCAL', 'PORT': '1433', 'OPTIONS': { 'driver' : 'ODBC Driver 13 for SQL Server' } } } How is the correct way to inspect a database in Django and how would be the best way to import each of the classes? -
Is the level of protection in Next js too high? [closed]
Is the level of protection in Next js too high if they are used as a ForntEnd in terms of uploading and receiving files and opening sessions with django rest APIs ? Knowing that the program contains financial correspondence and important data, and high protection is very necessary! Is the framework weak with attacks the CSRF and another attacks? What do you advise me to use from a framework, taking into account high security and speed at the same time؟ Is react js work with it? And final Thanks in advance. -
Django Rest Framework - adding permissions for views based on groups?
TLDR: How do you permit specific Groups access to views using Django Rest Framework? I'm in the process of building a web service with the Django Rest Framework. Only a (proper) subset of the views are intended to be available to customers. So far, I've: set the default permission to rest_framework.permissions.IsAdminUser created a permission called is_customer (using the Django admin website) created a Group called customers and added all relevant users to this group (using the admin website) added the is_customer permission to customers (again using the admin website) All of my views are function-based. To provide the appropriate permission to the customers group, I've tried from rest_framework.decorators import api_view from django.contrib.auth.decorators import permission_required @api_view(["POST"]) @permission_required(["is_customer"]) def my_func(request): # calculations return Response(...) and from rest_framework.decorators permission_classes, api_view @api_view(["POST"]) @permission_classes(["is_customer"]) def my_func(request): # calculations return Response(...) and neither seems to be working. What is the proper way to go about this? Thanks in advance for any advice! -
ASGI channels django
Пытаюсь запустить сервер с django framework, чтоб использовались каналы, т.е. должно быть так: Starting ASGI/Channels version 4.0.0 development server at http://127.0.0.1:8000/ а получается стандартный запуск такой: Starting development server at http://127.0.0.1:8000/ Что я делаю не так? asgi.py # import os from channels.routing import ProtocolTypeRouter from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SpareParts.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), }) settings.py INSTALLED_APPS = [ 'channels', ASGI_APPLICATION = "SpareParts.asgi.application" Перепробовал кучу всего. Если как-то выразился не так, дайте понять - добавлю информации -
Is there "non-lazy mode" or "strict mode" for "querysets" in Django?
When I use select_for_update() and update() of a queryset together as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): # Here # Here print(Person.objects.select_for_update().filter(id=1).update(name="Tom")) return HttpResponse("Test") Only UPDATE query is run without SELECT FOR UPDATE query as shown below. *I use PostgreSQL and these logs below are the queries of PostgreSQL and you can check on PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": But, when I use select_for_update() and update() of a queryset separately then put print(qs) between them as shown below: # "store/views.py" from django.db import transaction from .models import Person from django.http import HttpResponse @transaction.atomic def test(request): qs = Person.objects.select_for_update().filter(id=1) print(qs) # Here qs.update(name="Tom") return HttpResponse("Test") SELECT FOR UPDATE and UPDATE queries are run as shown below: Actually, this example above occurs because QuerySets are lazy according to the Django documentation below: QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated. But, this is not simple for me. I just want normal database behavior. Now, … -
Trying to connect from a docker container to docker host running Django in development mode gets connection refused
I'm running a django development server in my Debian GNU/Linux host machine with python manage.py runserver. After running a Debian docker container with $ docker run -it --add-host=host.docker.internal:host-gateway debian bash I expected I could make a curl in http://localhost:8000 with curl http://host.docker.internal:8000 but I get Failed to connect to host.docker.internal port 8000: Connection refused Is it something related to running Django with python manage.py runserver? -
Need help in Python Django for fetch the records from DB which will expire in 30 days
I wrote an application where there is a requirment to display only those records which will expire is next 30 day. models.py class SarnarLogs(models.Model): request_type_choice = ( ('NAR', 'NAR'), ) source = models.CharField(max_length=100) expiry_date = models.DateField() def __str__(self): return self.source Views.py @login_required(login_url=('/login')) def expiry_requests(request): Thirty_day = end_date = datetime.now().date() + timedelta(days=30) posts = SarnarLogs.expiry_date.filter(expiry_date = Thirty_day) context = {"console_data": posts, "user":request.user.full_name} return render(request, 'expiry_requests.html', context=context) -
how to select more options in "ManyToManyField()"?
i wanted to create a tag option for a a music model , well mainly musics accept more than one tag and there are amny kind of genres and tags ,so i wanted to make a ManyToManyField() that you can set more than 1 value ,also if you tag is not in add it in. to do that i thought maybe can make another CharField() then adding it to tag_name : #posts model name = models.CharField(max_length=200) band = models.CharField(max_length=200) release = models.DateTimeField() tag_add = models.CharField(max_length=100) tags = models.ManyToManyField(Tags) #cover = models.ImageField(upload_to='media/image') #file = models.FileField(upload_to='media/audio') class Meta(self): ordering = ['release'] def __str__(self): return self.name def get_absolute_url(self): return reverse('pages:music_detail',args=[str(self.id)]) class Tags(models.Model): tag_name = models.CharField(max_length=100) but i stuck here too ,i really dont know how to add a models field data to another models field ? i would appreciate if you guide me here -
I was running a test on my signal.py file and i am getting 'ValueError: seek of closed file' error
here is the signals.py file inside main app and here is the test_signals.py file enter image description here the full error is -
sqlite3.OperationalError: database is locked
travelers I am trying to run tests in order to to understand if my code is actually saving messages from telegram chat in database properly. The error says that sqlite3.OperationalError: database is locked everytime i am running test. ```settings.py```: ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'name', 'USER': 'me', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': `port', 'URL': 'postgres://username:password@host/database', } } Here is my `test_messages.py` which is the problem: ``` my_sqlalch_engine = sqlalchemy.create_engine('postgresql://user:password@localhost:5432/mydatabase') session_factory = orm.sessionmaker(bind=my_sqlalch_engine) session = session_factory() my_base = declarative_base() container = AlchemySessionContainer(session=session, table_base=my_base) session_fr = container.new_session('new_session') @pytest.mark.django_db def test_message_consumer(): # Setup test data api_id = '111231' api_hash = 'my_actual_hash' client = TelegramClient(session_fr, api_id, api_hash) #consumer = MessageConsumer() with transaction.atomic(): messages = client.get_messages('chatmessages') for text in messages: if text.slug not in Post.slug: post = Post( content = messages.text ) post.save() assert Post.objects.count() == len(messages) actual code for retrieving messages consumers.py: ``` api_id = '12391842' api_hash = 'api_hash' client = TelegramClient('news_session', api_id = api_id, api_hash = api_hash) class MessageConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, code): return super().disconnect(code) @transaction.atomic async def receive(self, client): messages = await client.get_messages('chat') async for text in messages: if text.slug not in Post.slug: post = Post( content = messages.text ) post.save() Hope i have provided all … -
Pass data to another html and save
can someone please tell me how to send all content of input.html to approve.html. I want the approve.html to validate input.html and then save it to the database. How can I do that? I'm a newbie, please help me, I've been trying to solve the problem for 7 days. <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">Name:</label> <input type="text" id="name" name="user_name" /> </li> <li> <label for="mail">Email:</label> <input type="email" id="mail" name="user_email" /> </li> <li> <label for="msg">Message:</label> <textarea id="msg" name="user_message"></textarea> </li> <li> <button class="menü_button"><b>send</b></button> </li> </ul> </form> <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">Name:</label> <input type="text" id="name" name="user_name" /> </li> <li> <label for="mail">Email:</label> <input type="email" id="mail" name="user_email" /> </li> <li> <label for="msg">Message:</label> <textarea id="msg" name="user_message"></textarea> </li> <li> <button class="menü_button"><b>save</b></button> </li> <li> <button class="menü_button"><b>remote</b></button> </li> </ul> </form> -
Post request to Djoser user registration route 'appName/v1/users/' throws 401 error
I'm new to Django and trying to build basic user authentication with REST API and a Vue.js frontend. To send the request, I am using axios, which is configured first in a seperate composable axios.js: import axios from 'axios' axios.defaults.withCredentials = true axios.defaults.baseURL = 'http://localhost:8000' and used inside a register.vue component: const submitRegistration = () => { axios.post('api/v1/users/', {username: 'userName', password: 'userPassword'}) .then(res => { console.log(res) }) } To make it simple, I'm sending a data-object with predefined strings, as you can see above. The request gets sent to one of the djoser routes in projectName/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), ] This however, throws a 401 Unauthorized Error: code: "ERR_BAD_REQUEST" config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message: "Request failed with status code 401" name: "AxiosError" request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …} response: {data: {…}, status: 401, statusText: 'Unauthorized', headers: AxiosHeaders, config: {…}, …} stack: "AxiosError: Request failed with status code 401\n at settle (http://localhost:3000/node_modules/.vite/deps/axios.js?v=a45c5ec0:1120:12)\n at XMLHttpRequest.onloadend (http://localhost:3000/node_modules/.vite/deps/axios.js?v=a45c5ec0:1331:7)" I've configured settings.py like so: INSTALLED_APPS = [ ..., 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'djoser' ] MIDDLEWARE = … -
How to get access to request inside custom class in django
customclass.py class MyCustomClass(): def __init__(self): if request.user.is_authenticated: // do somtehing custom_class = MyCustomClass() Hi A have an issue to get request data on "init". How to get it there? -
CS50w - Project 1
I try to solve cs50w project 1. But I faced an error in the project. enter image description here <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> This is the layout.html file. I have a form action: go to search, and the name is q. enter image description here urlpatterns = [ path("", views.index, name="index"), path("<str:title>/", views.title, name="title"), path("search/", views.search, name="search"), ] In my urls.py page I add a search path. enter image description here def search(request): if request.method == "POST": entry_search = request.POST['q'] html_content = markdown2.markdown(util.get_entry(entry_search)) if html_content is not None: return render(request, "encyclopedia/title.html", { "content": html_content, "title": entry_search, }) And in views.py i create a function named search. When I start my project and type something in the search bar, it sends me to the error.html page. enter image description here But it needs to take me to the title.html page. Can you help me with this problem? I need to face with title.html page, but it redirects to error.html -
cannot create new record in table django
I am trying to add new record into customer table via django forms but new records are not getting in the table also view function not redirecting to correct url. Here is my model.py class Customer(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) name = models.CharField(max_length=200) category = models.CharField(max_length=1) def __str__(self) -> str: return self.name here are my url patterns urlpatterns = [ path("create-customer" , views.create_customer , name = "create-customer"), path("<str:n>" , views.customer_index , name="cust_index"), path("" , views.home , name = "home"), ] here are my views def create_customer(response): if response.method == "POST": cust_form = createNewCustomer(response.POST) if cust_form.is_valid(): i = cust_form.cleaned_data["id"] n = cust_form.cleaned_data["name"] cat = cust_form.cleaned_data["category"] r = Customer(id = i , name = n , category = cat) r.save() return HttpResponseRedirect("%s" %r.n) else: cust_form = createNewCustomer() return render(response , "main/create-customer.html" , {"form" : cust_form}) def customer_index(response, n): cust = Customer.objects.get(name=n) return render(response , "main/display_cust_det.html" , {"cust":cust}) and here is my form class createNewCustomer(forms.Form): id = forms.IntegerField(label = "id") name = forms.CharField(label="name" , max_length=200) category = forms.CharField(label="category" , max_length=1) now when I am creating the customer it does not putting it into the customer table -
django select related not giving expected result
I am querying select related between two models Requirements and Badge Requirement has a related badge indicated by badge_id Models are, class Badge(models.Model): level = models.PositiveIntegerField(blank=False, unique=True) name = models.CharField(max_length=255, blank=False , unique=True) description = models.TextField(blank=True) class Meta: verbose_name = _("Badge") verbose_name_plural = _("Badges") def __str__(self): return self.name def get_absolute_url(self): return reverse("Badge_detail", kwargs={"pk": self.pk}) """ Requirement Model for requirements """ class Requirement(models.Model): number = models.PositiveIntegerField(blank=False) badge = models.ForeignKey(Badge, on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True) class Meta: verbose_name = _("Requirement") verbose_name_plural = _("Requirements") def __str__(self): return self.name def get_absolute_url(self): return reverse("Requirement_detail", kwargs={"pk": self.pk}) In My view I try to join both tables and retrieve. It is, """ ajax requirements in requirements table """ def get_requirements(request): requirements = Requirement.objects.all().select_related('badge').values() print(requirements) return JsonResponse(list(requirements), safe=False) The result is, to the frontend, to the backend, Why does it not give me both tables' values? -
Django Relational managers
I was trying to delete my Apllication model: class Application(models.Model): app_type = models.ForeignKey(ApplicationCategory, on_delete=models.CASCADE, related_name='applications') fio = models.CharField(max_length=40) phone_number = models.CharField(max_length=90) organisation_name = models.CharField(max_length=100, null=True, blank=True) aid_amount = models.PositiveIntegerField() pay_type = models.CharField(max_length=1, choices=PAY_CHOICES, default=PAY_CHOICES[0][0]) status = models.ForeignKey(AppStatus, on_delete=models.CASCADE, related_name='applications', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) benefactor = models.ForeignKey(Benefactor, on_delete=models.CASCADE, related_name='applications', null=True) def __str__(self): return f"id={self.id} li {self.fio} ning mablag\'i!" and this was my Benefactor model: class Benefactor(models.Model): fio = models.CharField(max_length=255) phone_number = models.CharField(max_length=9) image = models.ImageField(upload_to='media/') sponsory_money = models.IntegerField() organisation_name = models.CharField(max_length=55, null=True, blank=True) def __str__(self): return f"{self.fio}" But I got this message on superAdmin Panel: TypeError at /admin/api/benefactor/ create_reverse_many_to_one_manager.<locals>.RelatedManager.call() missing 1 required keyword-only argument: 'manager' I would expect delete smoothly!! -
How to use different content fro the database based on user's languages, in Django
Im building a Bible website. Let's say I have two versions of the Bible - one in English and one in Spanish. Im already using the en in my database and everything is working properly. How can I use the es Bible for Spanish speaking users? -
Django custom management command not found
app/ ├─ management/ │ ├─ commands/ │ │ ├─ customcommand.py myfunction.py site/ ├─ settings.py Contents of myfunction.py from django.core import management def funcA(): management.call_command('customcommand') funcA() On calling myfunction.py from terminal it throws raise CommandError("Unknown command: %r" % command_name) os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings' Inside myfunction.py I have tried setting this, but it still doesn't work. Can someone help me out here, probably I am missing out on some important config -
django migrate not updating on sql database tables therefor raising django.db.utils.OperationalError: (1054, "Unknown column 'field list'")
im having issues with my django project in development. it was working fine till i updated the model fields then it went haywire. here is my models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from multiselectfield import MultiSelectField equipment_choices = ( (1, "Contact Grill & Panini Grill"), (2, "Char Grill"), (3, "Griddle"), (4, "Salamender Grill"), (5, "Toaster Grill"), (6, "Boiling Top"), (7, "Gas Hob"), (8, "Freestanding Fryer"), (9, "Counter Top Fryer"), (10, "Filtration Fyrer"), (11, "Chip Scuttle"),) class Recipe(models.Model): title = models.CharField(max_length=40, unique=True) description = models.CharField(max_length=150, unique=True) prep_time = models.PositiveSmallIntegerField( validators=[ MinValueValidator(1), MaxValueValidator(500), ] ) cook_time = models.PositiveSmallIntegerField( validators=[ MinValueValidator(1), MaxValueValidator(500), ] ) additional_time = models.PositiveSmallIntegerField( validators=[ MinValueValidator(0), MaxValueValidator(200), ] ) total_time = models.PositiveSmallIntegerField( validators=[ MinValueValidator(1), MaxValueValidator(500), ] ) ingridients = models.CharField(max_length=200, unique=True) method = models.TextField(unique=True) equipment = MultiSelectField(choices=equipment_choices, max_choices=5, max_length=11) year = models.PositiveSmallIntegerField( validators=[ MinValueValidator(1), MaxValueValidator(500), ] ) rating = models.PositiveSmallIntegerField(choices=( (1, "★☆☆☆☆"), (2, "★★☆☆☆"), (3, "★★★☆☆"), (4, "★★★★☆"), (5, "★★★★★"), ) ) and when i press a button that works with the model i get the following error Internal Server Error: /recipes/list Traceback (most recent call last): File "/home/buddy/.virtualenvs/takein/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/buddy/.virtualenvs/takein/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) File … -
How to send QuerySet from HTML template to views via urldispatcher in django
I am trying to send QuerySet from index.html to views through urldispatcher. I searched through documentations but mostly have information on int:id, path:kjf, etc. There is some information on keyword args but i don't know much about them. I am beginner to Django and this is my first project, also my deadline for this project is near, so any help will be appreciable. index.html listing only necessary code... {% if datadict and datadict != "Sorry no data found" %} {% for item in datadict %} <tr> <th width="5%" scope="row"><a href="{% url 'index' datadict %}" class="btn btn-secondary">Generate</a></th> <td>{{ item.title }}<td> </tr> {% endfor %} {% endif %} urls.py urlpatterns = [ path('', views.index, name='index'), path('<datadict>', views.index, name='index') ] views.py def index(request, datadict=None): if (datadict): b = datadict[0] ### this is just testing to see if i am receiving the data in QuerySet from or not return render(request, 'dapp/index.html', {'b': b}) datadict have this data:- <QuerySet [{'id': 1002, 'year': '2000', 'sector': 'test', 'topic': 'test1', 'insight': 'dont no', 'url': 'localhost', 'start': '2000', 'impact': 'impaca', 'added': 'January 08 2001', 'published': 'August 03 2001', 'relevance': '4', 'pest': 'test2', 'source': 'CBSE', 'title': 'Adding test data', 'like': '5'}]> -
How to autofill user and slug fields in django form
I need two of the three form fields to be filled in automatically before submitting to the database. Slug is supposed to be filled based on test_name, and user have to be filled based on data about the current user. Now I can submit the form, but the database entry will not be created. models.py class Test(models.Model): test_name = models.CharField(max_length=100, db_index=True, verbose_name='Test name') slug = models.SlugField(max_length=100, unique=True, verbose_name='URL') author = models.ForeignKey(User, db_column="user", on_delete=models.PROTECT) forms.py class AddTestForm(forms.ModelForm): class Meta: model = Test fields = ['test_name', 'slug', 'author'] views.py def ask_test_name(request): form = AddTestForm(request.POST) if form.is_valid(): test = form.save(False) test.slug = slugify(test.test_name) test.author = request.user test.save() return render(request, 'app/ask_test_name.html', {'form': form}) ask_test_name.html <form action="{% url 'ask_test_name' %}" method="post"> {% csrf_token %} <p><input type="text" name="test_name" required></p> <p><input type="hidden" name="slug"></p> <p><input type="hidden" name="author"></p> <p><button type="submit">Create</button></p> </form> -
Django Show var as Label name
I'am learning Django and looking for a wat te get a variable shown as tekst I created the following model: ` class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) telefoon = models.CharField(max_length=10, blank=True) telefoon_mobiel = models.CharField(max_length=10, blank=True) woonplaats = models.CharField(max_length=20, blank=True) postcode = models.CharField(max_length=6, blank=True) straat = models.CharField(max_length=20, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() ` I created the following Form.py ` class ProfileForm(forms.ModelForm): straat = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) postcode = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) woonplaats = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) telefoon = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) telefoon_mobiel = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Profile fields = ('telefoon', 'telefoon_mobiel', 'woonplaats', 'postcode', 'straat') ` i Created the following views.py ` @login_required @transaction.atomic def profiel(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, ('Profiel aangepast')) return redirect('user') else: messages.error(request, ('Los ondestaande probleem op')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'public/profiel.html', { 'user_form': user_form, 'profile_form': profile_form, }) And created the following template: <div class="card-body"> <h5 class="card-title">Profiel {{ user.get_full_name }}</h5> <hr> <div class="container"> <div class="row"> <div class="col-sm"> {{ user.first_name }} {{ user.last_name }} </div> <div class="col-sm"> {{ straat }} </div> </div> <br/> … -
Reverse for 'detail_serial' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
I have this problem Reverse for 'detail_serial' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/\Z'] and problem is here {{ serial.title }} I don't know how it fix, cause im new in django.Please help html > ``` > <div class="container" style="grid-template-columns: repeat(auto-fill, 300px);"> > for serial in serials %} > <div class="item"> > <img src="{{ serial.poster.url }}" class="img-fluid" alt=""> > <p> > <a href="{% url 'detail_serial' serial.url %}">{{ serial.title }}</a> > </p> > </div> > endfor %} > </div> > ``` > views.py > ``` > class SerialDetailView(View): > def get(self, request): > serials = Serials.objects.all() > genres = Genre.objects.all() > return render(request, "serials/single_serial.html", {"serials": serials, "genres": genres}) > > ``` > > ``` urls.py urlpatterns = [ path('register/', views.Register.as_view(), name='register'), path('reg/', views.Reg.as_view(), name='reg'), path("serials_list/", views.SerialsView.as_view(), name='serials_list'), path("add/", views.AddView.as_view(), name='add'), path("single_serial/", views.SerialDetailView.as_view(), name='single_serial'), path("<slug:slug>/", views.SingleSerial.as_view(), name='detail_serial'), path("actor/<int:id>/", views.ActorView.as_view(), name='actor_detail'), ] models > ```` > class Serials(models.Model): > title = models.CharField('Name',max_length=100) > description = models.CharField('Description', max_length= 200) > poster = models.ImageField('Poster', upload_to='serials/') > date = models.DateField('Date') > country = models.CharField('Страна',max_length=100) > actors = models.ManyToManyField(Actor, verbose_name='actors', related_name='actor') > genre = models.ManyToManyField(Genre, verbose_name='genres') > category = models.ForeignKey(Category, verbose_name='category', on_delete=models.SET_NULL, null=True) > url = models.SlugField(unique=False) > link = models.URLField(max_length=200, blank=True) > ``` > … -
JavaScript fetch to Django view: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I have a JavaScript fetch to call a URL to pass data into my Django view to update a value for the user. Error in views.py: Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python310\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\rossw\Documents\Projects\Scry\apps\administration\views.py", line 47, in administration_users_page switchData = json.load(request)['switch'] File "C:\Python310\lib\json\__init__.py", line 293, in load return loads(fp.read(), File "C:\Python310\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) File "C:\Python310\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python310\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Error in browser: 0 PUT http://127.0.0.1:8000/administration/users/JM/ 500 (Internal Server Error) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON JavaScript: const changeAdminUserAction = (id,data) => { console.log(data) fetch(`/administration/users/${id}/`,{ method: 'PUT', body: JSON.stringify({type: "adminUser", switch: data}), headers: {'X-CSRFToken' : csrfToken, 'Content-Type': 'application/json'}, }) .then((response) => response.json()) .then((result) => {location.reload()}) .catch((err) => {console.log(err)}) } views.py: if request.method == 'PUT': user = CustomUser.objects.get(username=kwargs.get('username')) switchType = json.load(request)['type'] switchData = json.load(request)['switch'] print(switchType, switchData) if switchType == 'adminUser': user.admin_user = switchData elif switchType == 'admindata': …