Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / Rest Framework, AttributeError: 'list' object has no attribute id
I'm working with Django / Rest Framework, i would like to get the inserted record id i did : formSerializer = self.serializer_class(data = request.data, many=True, context={'request': request}) if formSerializer.is_valid(): newContact = formSerializer.save() print(newContact.id) but i'm getting an error : print(newContact.id) AttributeError: 'list' object has no attribute 'id' -
I can’t reproduce videos on Safari (Django App)
I have a Django app, when a reproduce videos on my desktop (Chrome) I can reproduce the video but when I reproduce the video on my mobile (iPhone - safari ) the video doesn’t work, the same problem with Safari on my Mac. In Chrome I can’t advance or rewind the video (the videos are in my computer), but when I change the source and I use a video of youtube (for example) I can advance or rewind the videos. I have this error when I try to reproduce videos on my phone: ------- Exception occurred during processing of request from ('192.168.1.7', 63287) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 720, in __init__ self.handle() File "/Users/edison/Documents/Python/Proyecto_10/venv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/edison/Documents/Python/Proyecto_10/venv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socket.py", line 714, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer My HTML code for the video: <div class="col-md-12"> <div class="d-flex justify-content-center"> <video width="960" height="540" poster="{{ scene.profile_pic.url }}" controls preload="none" controlsList="nodownload" playsinline> <source src="{{ scene.video_trailer.url }}" type="video/mp4"> </video> </div> </div> Thanks in advance. -
Tracking User Model Changes in Django's Default User Model with pghistory
I implemented your django-pghistory package in my college project. However, I am having trouble with tracking Django's default user model. I tried your "Tracking Third-Party Model Changes" suggested code in your documentation, as shown below in apps.py corresponding to "usuarios" app: user app.py However, I am not getting migrations done, so I think I am missing something that I am not aware of from the documentation. Would you mind helping me around with this? -
How do I filter a foreign key in models.py based on Groups
I'm new here. I just stared a project using Python/Django it is an idea that I want to show at my job. I have a django project and app already working Since I just started with it. I'm relying heavily on the default Django Admin Panel. My Problem is: I have this class in models.py class Sales(models.Model): order_number = models.CharField(max_length=50) order_date = models.DateField('digitado em', default=date.today) Sales_User = models.ForeignKey(User, on_delete=models.SET_DEFAULT) Now in my User db I have 50 Users. But only 15 of those are Sales People (all in the Group "Sales") When I go to create an order and have to select the sales user The dropdown shows all 50 Users. Is the a way to either filter those user by the group they are in? Or to replace the dropdown with on of those pop-up then search and select. I'm open to try different approaches as long as I can actually accomplish them. :-) Thank you all for the time. -
ImportError: Module "rest_framework.permissions" does not define a "isAuthenticated" attribute/class
Currently trying to add authentication to my app. Not sure if this has to do with my current problem, but I made an authentication application, and then had to change the name because it didn't play well with django.contrib.auth. Anyway, I just renamed the folder and the name in INSTALLED_APPS, since I didn't do any migrations yet. When I had finished up with that and tried to do ./manage.py makemigrations for the first time, I get this: ImportError: Could not import 'rest_framework.permissions.isAuthenticated' for API setting 'DEFAULT_PERMISSION_CLASSES'. ImportError: Module "rest_framework.permissions" does not define a "isAuthenticated" attribute/class. I also didn't install any new dependencies to my virtualenv since renaming my authentication app, so I don't think I missed anything in terms of renaming stuff in node_modules. Here's my settings.py: import os from datetime import timedelta # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'blah blah' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
how do I merge multiples datasources into one result?
lets say . I have the following models where I Have multiples store locations where it sends me all inventory to multiples tables its products e.g Collection1,Collection2,Collection3, n+1, so I need to merge the results to a centralized table or merge the results of all tables into a single response in the view. is there any way to perform .all() in a single result? class Collection1(models.Model): id = models.CharField(max_length=32, unique=True) products = models.ManyToManyField(Product, related_name='products') provider = models.ManyToManyField(Provider, related_name='provider') date = models.DateTimeField(default=timezone.now) class Collection2(models.Model): id = models.CharField(max_length=32, unique=True) products = models.ManyToManyField(Product, related_name='products') provider = models.ManyToManyField(Source, related_name='provider') date = models.DateTimeField(default=timezone.now) class Collection3(models.Model): id = models.CharField(max_length=32, unique=True) products = models.ManyToManyField(Product, related_name='products') provider = models.ManyToManyField(Provider, related_name='provider') date = models.DateTimeField(default=timezone.now) -
Django Runserver Error: "OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'"
The Problem Some friends and I were working on a project for class that we were never able to complete. We were using this tutorial by Dennis Ivy on YouTube to make a To-Do List using Django, but I was never able to finish my part thanks to an error I kept getting, listed below. I tried looking things up everywhere online, but none of it helped. I reinstalled Python, Django, VSCode, tried PyCharm, upgraded pip, tried VMs (OpenSUSE, Regolith, Ubuntu), and even a whole other Windows PC. but none if it seemed to help. The Error Tried to run the server: PS D:\Cloud\jvivar-nmsu\OneDrive - New Mexico State University\Documents\2021_Spring\ET458\ToDo_Project_Final\et458\todo> python manage.py runserver 8000 Error Output: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Program Files\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Program Files\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Program Files\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program … -
Problems with DjangoFilterView
I am trying to filter my models with the django-filter extension. The view wont work, and I am not sure why.. I currently have this code: models.py from django.db import models class defense_mechanism(models.Model): defense = models.CharField(max_length=100, blank=True) def __str__(self): return self.defense class attack(models.Model): actor = models.CharField(max_length=100, blank=True) action = models.CharField(max_length=100) asset = models.CharField(max_length=100) defense = models.ManyToManyField(defense_mechanism) def __str__(self): return self.action class security_incident(models.Model): security_inc = models.CharField(max_length=100, primary_key=True) def __str__(self): return self.security_inc class adtree(models.Model): goal = models.ForeignKey(security_incident, on_delete=models.CASCADE) attack = models.ManyToManyField(attack) defense_mechanism = models.ManyToManyField(defense_mechanism) filters.py import django_filters from django import forms from .models import adtree, security_incident, attack, defense_mechanism class ADTreeFilter(django_filters.FilterSet): goal = django_filters.CharFilter defense_mechanism = django_filters.CharFilter attack = django_filters.CharFilter class Meta: model = adtree fields = ['goal', 'defense_mechanism', 'attack'] views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.views.generic import View, FormView from django import forms from django_filters.views import FilterView from .models import adtree, security_incident, defense_mechanism, attack from .filters import ADTreeFilter class GenerateView(FilterView): model = adtree context_object_name = 'ad_tree' template_name = 'application/generate.html' filterset_class = ADTreeFilter def get_context_data(self, **kwargs): context = super(GenerateView, self).get_context_data(**kwargs) context['goals'] = adtree.objects.goal().order_by('pk') context['attacks'] = attack.objects.all().order_by('pk') context['defense_mechanisms'] = defense_mechanism.objects.all().order_by('pk') return context def get_form_kwargs(self): kwargs = super(GenerateView, self).get_form_kwargs() return kwargs generate.html <form method="get"> <div class="well"> <div class="row"> <div class="col-md-12"> … -
Detect Authentication Failure
I'm using the Django AllAuth package to authenticate my users. I used this tutorial to implement it. I am attempting to write a JS function that would change the display css property on the message element. The problem I'm having is detection the authentication failure event in order to place it into a function. Is it possible to do this? -
Django - File name '' includes path elements exception, isn't the name supposed to include the path relative to MEDIA_ROOT?
I am working through a Django/Vue tutorial. I have a url setup 'latest-products' that should show the serialized Products but I am getting an exception when the thumbnail doesn't exist and is created with the make_thumbnail function in the Product class of models.py. This is the exception: Exception Type: SuspiciousFileOperation at /api/v1/latest-products/ Exception Value: File name 'uploads/winter3.jpg' includes path elements This is the result I am expecting: screenshot From the Django File documentation , the name is supposed to be "The name of the file including the relative path from MEDIA_ROOT." So, my question is why am I getting a SuspiciousFileOperation exception? #models.py from io import BytesIO from PIL import Image from django.core.files import File from django.db import models class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.slug}/' class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.category.slug}/{self.slug}/' def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' def get_thumbnail(self): if … -
How do I change django's default sqlite3 database to a more advanced one like MySQL?
I want to use a better database with my Django like postgresql or mysql. what are the steps in doing that? -
Integrating postgres to django
im trying to install psycopg2 to use postgres on my django app. Seems like the first step is to run the sudo apt install python3-dev libpq-dev, but when i do it hits me with this funky error - Unable to locate an executable at "/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home/bin/apt" (-1). I'm confused as to why its showing me a java error when i'm installing python-dev. Any help would be greatly appreciated! -
Problem with django I get KeyError: 'carriage' when I restart the server
Estoy intentaldo hacer un proyecto pero no funciona y no me deja hacer nada me sale un error KeyError: 'carro' y estoy intentando pero no funciona esto se encuentra en un archivo llamado context_processor.py ya colo en settings esto def importe_total_carro(request): total = 0 if request.user.is_authenticated==True: for key,value in request.session['carro'].items(): total=total+(float(value["precio"])*value["cantidad"]) return {"importe_total_carro":total} y esto en views class Carro: def init(self, request): self.request=request self.session= request.session carro = self.session.get("carro") if not carro: carro=self.session["carro"]={} else: self.carro=carro def agregar(self, producto): if(str(producto.id) not in self.carro.keys()): self.carro[producto.id]={ "producto_id":producto.id, "nombre":producto.nombre, "precio":str(producto.precio), "cantidad":1, "imagen":producto.imagen.url } else: for key, value in self.carro.items(): if key == str(producto.id): value["cantidad"]=value["cantidad"]+1 break self.guardar_carro() def guardar_carro(self): self.session["carro"]=self.carro self.session.modified=True def eliminar(self, producto): producto.id= str(producto.id) if poducto.id in self.carro: del self.carro[producto.id] self.guardar_carro() def restar_producto(self,producto): for key, value in self.carro.items(): if key == str(producto.id): value["cantidad"]=value["cantidad"]-1 if value["cantidad"]<1: self.eliminar(producto) break self.guardar_carro() def limpiar_carro(self): self.session["carro"]={} self.session.modified=True -
How to view others profile just like instagram website
i am stuck in a situation while creating a social media website in django .the problem i face is .The website i am working is just like Instagram, a user can upload image and other user can view it.So i made a page where when a user is loged in he can view his profile and he can see all his uploaded images.Then the problem comes i want also a page in which the other user can see other peoples profile just like instagram ,clicking on the name we goes to the profile of the person who upload the post.i want this feature to be implimented in my website but i can filter the model and get all the upload pics of other user into the new page but i was not able to get the detial of the user such as their profile pic bio etc....... i tried looping but the profile card get into lot of card because of the modes the bellow link is my html page to show the logined person profil but i want to see the others profile also profile html page to show profile detial of loged in person this is my views … -
Error in Django project: (fields.E120) CharFields must define a 'max_length' attribute
I am currently changing the models in my Django App,and I am getting a new issue I am having problems with to solve. I am pretty sure I get the error due to my models.py file, but I cant solve the problem. I have not found a solution online and it is driving me crazy. models.py from django.db import models class defense_mechanism(models.Model): defense = models.CharField(max_length=100) def __str__(self): return self.defense class attack(models.Model): actor = models.CharField(max_length=100) action = models.CharField(max_length=100) asset = models.CharField(max_length=100) defense = models.CharField(defense_mechanism) def __str__(self): return self.action class security_incident(models.Model): security_inc = models.CharField(max_length=100, primary_key=True) def __str__(self): return self.security_inc class adtree(models.Model): goal = models.ForeignKey(security_incident, on_delete=models.CASCADE) defense_mechanism = models.ManyToManyField(defense_mechanism) attack = models.ManyToManyField(attack) def __str__(self): return self.goal here is the full output of the error message django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: application.attack.defense: (fields.E120) CharFields must define a 'max_length' attribute. System check identified 1 issue (0 silenced). C:\Users\Bruker\PycharmProjects\hri\attack_defense_tree_generator> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Bruker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line … -
Field 'id' expected a number but got ' '
I'm trying to get my item's id so I can save it in the user's profile. However, when I make the post request I get the error: Field 'id' expected a number but got ''. So how can I solve this so I can get the item's id and why is it not working in my code? if request.method=='POST' and 'anime_pk' in request.POST : anime_id = request.POST.get("anime_pk") anime = Anime.objects.get(id = anime_id) request.user.profile.animes.add(anime) messages.success(request,(f'{anime} added to wishlist.')) return redirect ('/search') animes = Anime.objects.all() The html: <form method="post"> {% csrf_token %} <section> <div class=row> <div class="col-md-4 col-sm-6 col-lg-3"> <div class="card"> <div class="card-body text-center"> <p class="card-title"> <b>{{anime.Title}}</b></p> <hr> <p class="card-text">Episodes: <b>{{anime.Episodes}}</b></p> <img src = {{anime.Image}} /> </div> </div> </section> <input type="hidden" value="{{anime.pk}}" name="anime_pk"> <button type="submit" class="btn btn-outline-primary" style="font-size:18px; border-radius: 50%">★</button> </form> -
JQuery ломает CSS стили
всем привет, сразу извиняюсь за возможно довольно глупый вопрос который скорее всего напрямую связан с моими кривыми руками, но, тем не менее есть проблема с тем что при подключении файлов JQuery в мой Django проект ломаются все стили на странице к которой подключаю, до подключения всё работает корректно. Я новичок и скорее всего просто чего-то не понимаю, и не могу уже какой день решить эту проблему, сразу скажу что я знаю про collect static и все те вещи которые нужно делать со статическими файлами, ибо стили работают нормально и в файле settings.py все пути указаны верно. код скрипта довольно простой и служит по большей части чисто для адаптивного меню, и скрытия некоторых тегов html по нажатию. JQuery код скрипта довольно простой и служит по большей части чисто для адаптивного меню, и скрытия некоторых тегов html по нажатию. $(document).ready(function() { // Менюшка и появляющиеся категории $('.nav_show_btn').click(function() { let display = $('.nav_show_links').css('display') if (display == 'none') { $('.nav_show_links').slideDown('100') } else { $('.nav_show_links').slideUp('100') } }) $('.category_btn').click(function() { let display = $('.categorys_container').css('display') if (display == 'none') { $('.categorys_container').slideDown('100') $('.category_btn').addClass('active') } else { $('.categorys_container').slideUp('100') $('.category_btn').removeClass('active') } }) // Профиль и его меню { let active; $('#main_inf_user').click(function() { if (active != 'off' | active == undefined) … -
Django model design for Shopping List. how to use ManytoMany relationship?
I am working on making django app to handle multiple shopping list. which should have ManytoMany field? Item model or List model? is this model optimal ? A list can have many items, many sublists, many associated store. And, except for List vs Sublist all the relationships are many to many. An item can be in many list, a store can be associated to many list. sublist is just putting the item in categories so I can also remove this model and add a category attribute to items. Item has m2m fields for List but should it also have m2m field for Sublist? a List need not have sublist so the item can be part of list or sublist in a list (like a folder/file structure) models.py: class List(models.Model): name = models.Charfield(max_length=125) date = models.DateField(default=django.utils.timezone.now) class Store(models.Model) : name = models.CharField(max_length=128) store = models.ManyToManyField(List) class Item(models.Model): item = models.CharField(max_length=128) price = models.FloatField(default=0.0) category = models.CharField(max_length=128, default=None) checked = models.BooleanField(default=None) store = models.ManyToManyField(List) class SubList(models.Model): name = models.Charfield(max_length=256) parent_list = models.ForeignKey(List) items = models.ManyToManyField(Item) -
UpdateView Doesn't Save Data, returns object field data in url
After a LOT, LOT, LOT of research, I COULD NOT FIND OUT why UpdateView in django wasn't saving form data upon being saved. Instead, it saved the data in a url when it redirected me back to an un-edited object detail view. I'm sharing the same template for CreateView and UpdateView Here's my Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from django.views import View from .models import Blog from .forms import BlogForm from django.views.generic import ( CreateView, ListView, DetailView, UpdateView, DeleteView ) class BlogListView(ListView): template_name = 'blogtemplates/blogs.html' queryset = Blog.objects.all() model = Blog paginate_by = 4 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['object_list'] = Blog.objects.all() return context class BlogDetailView(DetailView): model = Blog template_name = 'blogview.html' queryset = Blog.objects.all() def get_object(self): id_ = self.kwargs.get("pk") return get_object_or_404(Blog, id=id_) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['object_list'] = Blog.objects.all() return context class BlogCreateView(CreateView): template_name = 'blogpost.html' form_class = BlogForm queryset = Blog.objects.all() def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books context['object_list'] = Blog.objects.all() return context … -
matching query does not exist - how can I get an item from an API and save it to a user's profile?
I'm trying to add an item of a search result into a user's profile. The thing is, when I look for the items, they are not saved into my database unless the user saves them to their profile (that's my intention). My code is supposed to get the item by its id (which in my code was supposed to be the id it has on the API but that doesn't seem to work) but since the item is in the API and not in my database, it doesn't work. So how can I manage to get the item from the API and save it to the user's profile (and, that way, to my database)? These are the models: class Anime(models.Model): title = models.CharField('Title', max_length=150) episodes = models.IntegerField() image = models.ImageField() mal_id = models.IntegerField(null=True) def __str__(self): return self.title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Anime, related_name='favorited_by', null=True, 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() These are the views: def search(request): animes = [] if request.method=='POST' and 'search' in request.POST : animes_url = 'https://api.jikan.moe/v3/search/anime?q={}&limit=6&page=1' search_params = { 'animes' : 'title', 'q' : request.POST['search'] } r = requests.get(animes_url, params=search_params) results … -
OpenCV can't capture frames on production server (Nginx + uWSGI)
I'm building a production server on Raspberry Pi 4. Web app is written in Django. I used uWSGI as an application server and Nginx as a reverse proxy. I followed many tips from Digital Ocean. One of the tasks is to stream frames from USB camera connected to RPi. My inspirations was post from PyImageSearch, but I wanted to do it in Django. Code looks as follows: # views.py from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() if not self.grabbed: print("Can't open camera") threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def camera_usb(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: print("Something went wrong") and then I use code of 'camera_usb' view in urls.py and in template. It works fine both on my laptop and on RPi 4, but only on development server. After running on production server I get following message from sudo systemctl status uwsgi: uwsgi.service - uWSGI Emperor service Loaded: … -
Why am I getting ValueError in my Django REST view?
I am trying to send a POST request to my view to create an object using DRF. The GET request in the same view works fine, but I can't seem to create the object. Here is my view: class ProjectsListCreateAPIView(generics.ListCreateAPIView): serializer_class = ProjectSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): owned_projects = Project.objects.filter(owner=self.request.user) assigned_projects = self.request.user.project_set.all() return sorted( chain(owned_projects, assigned_projects), key=attrgetter('created') ) Here is my serializer: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ['id', 'created', 'owner', 'title', 'slug'] Here is the error that I am getting: ValueError at /projects/ Cannot force both insert and updating in model saving. What am I doing wrong here? -
how to get json send from fetch in django view
I send value of an input field (one email or more seprated by ',')to an api view : var emails_list = document.getElementById('members_email').value; fetch(url, { method: 'POST', headers: { 'Content-type': 'application/json', 'X-CSRFtoken': csrftoken, }, body: JSON.stringify({ 'emails_list': emails_list }) }) .then(response => response.json()) .then(data => { console.log('Success:', data); send_prefered_times_to_time_api(data); }) and this the api view: @api_view(http_method_names=['POST']) def get_prefer_times(request): if request.method=='post': serializer = EmailsListSerializer(data=request.data) if serializer.is_valid(): invited_users_email = serializer['emails_list'].split(',') print(invited_users_email) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and this is serializer.py: class EmailsListSerializer(serializers.Serializer): emails_list = serializers.ListField(child=serializers.CharField()) but i get this error: Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data -
Trying to retrieve the data having specific id value by applying joining select_related query using DJANGO ORM
I want to retrieve the specific subtopic id's questions along with its options and answer.(Eg i want to retrieve all questions and their choices,answer whose subtopic id is 2) but when i apply the query it provides me all the subtopics questions and answers that are present in DB. here is my models.py from django.db import models from django.db.models import Model # Create your models here. class Teacher_Signup(models.Model): username = models.CharField(max_length=122) email = models.EmailField(max_length=40) password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) def __str__(self): return self.username class Meta: db_table = 'Teacher_Signup' class Add_Grade(models.Model): grade = models.CharField(max_length=40) username = models.ForeignKey(Teacher_Signup,on_delete=models.CASCADE, default = 1) #teacher_name = models.CharField(max_length=40) def __int__(self): return id class Meta: db_table = 'Add_Grade' class Student_Signup(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) username = models.CharField(max_length=70) father_name = models.EmailField(max_length=70) #grade = models.PositiveIntegerField () age =models.PositiveIntegerField () phone_no =models.IntegerField () password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) def __str__(self): return self.username class Meta: db_table = 'Student_Signup' class Add_Topics(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.CharField(max_length=40) def __int__(self): return id class Meta: db_table = 'Add_Topics' class Sub_Topics(models.Model): grade = models.ForeignKey(Add_Grade,on_delete=models.CASCADE, default = 1) topic = models.ForeignKey(Add_Topics,on_delete=models.CASCADE, default = 1) videofile = models.FileField(upload_to='videos/', null=True, verbose_name="") subtopic = models.CharField(max_length=40, default = 1) def __str__(self): return self.subtopic … -
Set Dataframe index in jinja template
In a Django app, I have following template: detail.html: <select name="indexColumn" id="selectIndexOptions"> <option>Set Index</option> {% for k, v in data.items %} <option>{{ k }}</option> {% endfor %} </select> I want to give users options to set index of the dataframe. I don't know how to set index of a dataframe in jinja.