Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Issue for user from an existing database to login in a Django website
There is my problem, so I need to create a Django app and I think I have to use an already existing database with users in. So I did some research and figured out some issues. So Django store the password with the salt and use it to check the password.But no one says that there will be salt + hashed type password in the database, but we can get read of this issue with the proper check function (related to the encryption function) I think, like this guy Django check_password() always returning False who used bcrypt.checkpw(password, hashedPassword) because in his database passwords are encrypted with bcrypt. The solution proposed was to create a custom authentification backend (even if I don't really see how we can do this I may be able to find out a tuto to do so) but the main issue is that how I can save a user password who register through the Django web site with the same type of hash that the one already existing in the database (with no salt). I'm a really sorry for not be able to give you more precision about how the password are stored in the database because … -
Django structure
I really need a way to print the structure of my Django app So I have an almost finished app and I need to print something like this: ~/projects/project_name/ docs/ # documentation scripts/ manage.py # installed to PATH via setup.py project_name/ # project dir (the one which django-admin.py creates) apps/ # project-specific applications accounts/ # most frequent app, with custom user model __init__.py ... settings/ # settings for different environments, see below __init__.py production.py development.py ... __init__.py # contains project version urls.py wsgi.py static/ # site-specific static files templates/ # site-specific templates tests/ # site-specific tests (mostly in-browser ones) tmp/ # excluded from git setup.py requirements.txt requirements_dev.txt pytest.ini Is this possible? I only can find a way to create an app based in other structure. I need the same but in the other way... Getting the structure of my app... Thanks!!!! -
Got an unexpected keyword argument 'my_id' (Dynamic URL Routing)
django 3.2.2 urls.py from django.contrib import admin from django.urls import path from pages.views import home_view, contact_view, about_view from products.views import product_detail_view, product_create_view, render_initial_data, dynamic_lookup_view urlpatterns = [ path('products/<int:my_id>/', dynamic_lookup_view, name='product'), path('', home_view, name='home'), path('about/', about_view), path('contact/', contact_view), path('create/', product_create_view), path('initial/', render_initial_data), path('product/', product_detail_view), path('admin/', admin.site.urls), ] views.py from django.shortcuts import render, get_object_or_404 from .forms import ProductForm, RawProducForm from .models import Product # Create your views here. def dynamic_lookup_view(request, my_id): obj = Product.objects.get(id=my_id) context = { "object": obj } return render(request, "products/product_detail.html", context) I want to see the products with the following link: http://127.0.0.1:8000/products/2/ this returns me: TypeError at / products / 2 / dynamic_lookup_view () got an unexpected keyword argument 'my_id' -
Django model class with multiple objects from other model class
I want to create a Django model schema to track yacht racing results. This is a highly simplified version, but want to only focus on the relationships and schema first; class Yacht(models.Model): name = models.CharField(max_length=50) class Event(models.Model): event_number = models.IntegerField() class Result(models.Model): yacht = models.ForeignKey(Yacht, on_delete = models.CASCADE) event_number = models.ForeignKey(Event, on_delete = models.CASCADE) result = models.IntegerField(default=0) Question: How would you approach this problem where I want to create an Event, and have it list all the yachts where I can enter their time? I'd like to be able to do this in the Admin 'all at once' instead of going to each yacht. Eventually, I want this to display as a form for a user. For example, if a user clicks on a race event, it loads a page with all the yachts and their time slot. Julien -
Inserting data from an array into a WORD document table
I have two arrays ['2021-04-30', '2021-05-02', '2021-05-04', '2021-05-06'] [1500, 450, 750, 900] There is a document template How do I insert data from the date array into {{ date }} and data from the price array into the {{ price }} variable?In this case, each new record in the table must start with a new cell doc = Document('Шаблон.docx') date = post_data.get('date', False) price = post_data.get('price', False) context = {'date': date, 'price': price} doc.render(context) doc.save('restyled.docx') This works when the data is not an array -
Django not detecting changes in app model
I have created an app called base and added a new model to it. However, whenever I run python3 manage.py makemigrations base It says no changes detected. I have already added my in installed apps INSTALLED_APPS = [ ... 'base.apps.BaseConfig', ... ] And it does have the migrations folder inside the app containing and __init__.py file. I was wondering what is causing this issue. This is my model: from django.db import models # Create your models here. class BaseModel(models.Model): created_at = models.DateTimeField(auto_now=True) modified_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True And my settings contains 4 files: settings: --__init__.py -- dev.py -- prod.py -- staging.py -- common.py My __init__.py: import os from .common import * from decouple import config environment = config('DEV_ENV', cast=str) if environment == "dev": from .dev import * elif environment == "staging": from .staging import * elif environment == "prod": from .prod import * I have also already tried running python3 manage.py makemigration base --settings=project.settings.dev and it still says no changes detected -
Issues, the courses appear to everyone and not to the users who purchased the course
Issues, the courses appear to everyone and not to the users who purchased the course , the problem is any one can access to the course if he type the url for course views.py : def coursePage(request,slug): course = Course.objects.get(slug = slug) serial_number = request.GET.get('lecture') videos = course.video_set.all().order_by('serial_number') if serial_number is None: serial_number = 1 video = Video.objects.get(serial_number = serial_number , course = course) # print("priview", video.is_preview) # print(request.user.is_authenticated) # print(request.user) if (video.is_preview is False): if (request.user.is_authenticated is False): return redirect('login') else: user = request.user try: user_course = UserCourse.objects.get(user = user , course = course) except: return redirect('checkout',slug = course.slug) data = { "course":course, "video":video, "videos":videos } return render(request,'courses\courses.html',data) how to fix this problem , i want user who purchased the course can see it not all also i want to ask how to store videos private in db and no body can access videos if he not purchased i mean like udemy -
Formset saving any decimal except 0 even though formset is saved and is_valid() passes
I have created a formset to let users log hours on a weekly basis. The issue I'm having is that I can't save "0" in the input fields - any decimal works but 0 (see gif at the end for illustration) TLDR: Formset saves any input except 0, see gif here for illustration: https://imgur.com/a/iCMexQk My Timesheet and TimesheetEntry models looks as following: class Timesheet(Model): year = PositiveIntegerField(validators=[MaxValueValidator(2500), MinValueValidator(1900)]) week = PositiveIntegerField() project = ForeignKey("projects.Project", on_delete=CASCADE) user = ForeignKey(User, on_delete=CASCADE) status = CharField( max_length=15, choices=STATUS_CHOICES, blank=True, default=STATUS_OPEN ) objects = TimesheetManager() class Meta: db_table = 'timesheet' ordering = ('id',) unique_together = (('year', 'week', 'user', 'project',),) def __getattr__(self, attr): allowed_days = ( 'day_1', 'day_2', 'day_3', 'day_4', 'day_5', 'day_6', 'day_7' ) if attr in allowed_days: day = int(attr[-1]) - 1 entry = self.timesheetentry_set.filter( date=Week(self.year, self.week).day(day) ).first() if entry: return entry.hours return None return super().__getattr__(attr) def total_duration(self): return self.timesheetentry_set.aggregate( total_duration=Coalesce(Sum('hours'), 0) ).get('total_duration') class TimesheetEntry(Model): timesheet = ForeignKey(Timesheet, on_delete=CASCADE) hours = DecimalField(max_digits=4, decimal_places=1, null=True, blank=True) date = DateField() class Meta: db_table = 'timesheet_entry' ordering = ('date',) And the forms.py looks as following: DAYS = ( 'day_1', 'day_2', 'day_3', 'day_4', 'day_5', 'day_6', 'day_7' ) class TimesheetModelForm(ModelForm): class Meta: model = Timesheet exclude = ("user", "status") class … -
How can i override, Django Rest Auth Registration?
I'm working on a small project using Django / Rest Auth, and I would like to know how can I override the registration, I would like to add some other fields in the registration, as I want to do some other things during the registration. PS: I checked already some questions here but I couldn't use them because each one explains a different approach that's why -
Django rest framework - serializer is not valid
Good day. I'm trying to create an entity by POST method. I have Serializer, and some javascript code - that sends me FormData , which I'm trying to serialize. This is my view: @api_view(['POST']) @parser_classes([MultiPartParser, FormParser]) def cocktail_create(request): """Создание коктейля""" pprint(request.data) serializer = CocktailCreateSerializer(data=request.data) pprint(serializer.fields) if serializer.is_valid(): serializer.create(serializer.validated_data) else: pprint(serializer.errors) request.data: {'author': '4', 'cocktail_tool': '[{"tool":"1","amount":"1"}, {"tool":"2","amount":"1"}]', 'csrfmiddlewaretoken': 'KFb9ZEBwWViF4Sm9pQxZn5KcfXpfu7t6OigeqsXZri9hoQQ1RPuS1lQDF3NJ3Aq5', 'description': 'asdasd', 'img': <InMemoryUploadedFile: pp,504x498-pad,600x600,f8f8f8.jpg (image/jpeg)>, 'name': 'Danya', 'recipe': '[{"ingredient":"1","amount":"1"},{"ingredient":"2","amount":"1"}]', 'recipe_text': '{"1":"asdasd","2":"asdasd"}', 'small_img': <InMemoryUploadedFile: pp,504x498-pad,600x600,f8f8f8.jpg (image/jpeg)>} serializer.fields : {'img': ImageField(allow_null=True, max_length=100, required=False), 'small_img': ImageField(allow_null=True, max_length=100, required=False), 'cocktail_tool': CocktailToolsForCocktailCreateSerializer(many=True): amount = IntegerField(max_value=2147483647, min_value=-2147483648) tool = PrimaryKeyRelatedField(queryset=BarTool.objects.all()), 'description': CharField(style={'base_template': 'textarea.html'}), 'name': CharField(max_length=255, validators=[<UniqueValidator(queryset=Cocktail.objects.all())>]), 'recipe': RecipeForCocktailCreateSerializer(many=True): amount = IntegerField(max_value=2147483647, min_value=-2147483648) ingredient = PrimaryKeyRelatedField(queryset=Ingredient.objects.all()), 'recipe_text': JSONField(decoder=None, encoder=None, style={'base_template': 'textarea.html'}), 'author': PrimaryKeyRelatedField(allow_null=True, queryset=BarbookUser.objects.all(), required=False)} serializer.errors: {'cocktail_tool': [ErrorDetail(string='This field is required.', code='required')], 'recipe': [ErrorDetail(string='This field is required.', code='required')]} my serializers : class CocktailToolsForCocktailCreateSerializer(serializers.ModelSerializer): class Meta: model = CocktailTool fields = ("amount", "tool") class RecipeForCocktailCreateSerializer(serializers.ModelSerializer): class Meta: model = CocktailRecipe fields = ("amount", "ingredient") class CocktailCreateSerializer(serializers.ModelSerializer): cocktail_tool = CocktailToolsForCocktailCreateSerializer(many=True) recipe = RecipeForCocktailCreateSerializer(many=True) class Meta: model = Cocktail fields = ("img", "small_img", "cocktail_tool", "description", "name", "recipe", "recipe_text", "author") my models: I have a cocktail model , ingredient model and bartool model, and many to many tables such as: class CocktailRecipe(models.Model): … -
refreshing audios makes them impossible to listen to
I want to make a whatsapp like message app but only with audios. I can get them in my vue app the by refreshing regularly the store, to see if new audios arrived: refresh() { this.$store.dispatch("audio/getAudios"); }, }, created() { setInterval(this.refresh, 1000); }, and I display them the following way in my vue app: <div class="audios" v-for="audio in audios" :key="audio"> <audio controls v-if="audio.rooms.split(',').includes(room)"> <source :src= "'http://localhost:8000'+audio.audiofile" type="audio/wav"> </audio> </div> </div> The problem is that by refreshing every second, all audios that are displayed are 're'-displayed and it makes impossible to listen to them. How can I use the v-for differently to avoid this trouble ? -
django not saving data to model
I am working on the cs50w commerce project. The page I am making should create an auction listing for an item the user wants to sell. After entering the info into the form and clicking the button the data is not saved to the model. going to the admin page shows that my listings model has 0 listings. I can not find the issue. I have been working on this portion of the code for 2 days. any help would be appreciated. HTML {% extends "auctions/layout.html" %} {% block body %} <h2>Create Listing</h2> <div class="text-left"> <form action="{% url 'createlisting' %}" method="POST"> {% csrf_token %} <div class="form-group"> <input class="form-control" autofocus type="text" name="title" placeholder="Title"> </div> <div class="form-group"> <textarea class="form-control" name="description" rows="4" placeholder="Add a Description"></textarea> </div> <div class="form-group"> <select class="form-control" name="category" placeholder="Category" required> <option value="">Select a Category</option> <option value="books">Books</option> <option value="clothes">Clothes</option> <option value="electronics">Electronics</option> <option value="games">Games</option> <option value="movies">Movies</option> <option value="tools">Tools</option> <option value="toys">Toys</option> <option value="other">Other</option> </select> </div> <div class="form-group"> <input class="form-control" type="text" name="starting_price" placeholder="Starting Price"> </div> <div class="form-group"> <input class="form-control" type="text" name="image_link" placeholder="Link to Image"> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Create"> </div> </form> </div> </div> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), …