Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove a django _like index from a primary key
I am using a CharField in django to store a primary key. I have defined this as: id = models.CharField( max_length=64, default=create_id, primary_key=True, null=False, editable=False ) This results in my table having the following two indexes: CREATE UNIQUE INDEX api_participant_pkey ON public.api_participant USING btree (id) CREATE INDEX api_participant_id_cb12634b_like ON public.api_participant USING btree (id varchar_pattern_ops) The text in the id is meaningless, I am always going to query that field through an exact match, never using LIKE. Is there an easy way to remove the _like index? I've seen How to remove index varchar_pattern_ops in a django (1.8) migration? on how to remove the index when it is a field being indexed, but I am not sure how to do this for a primary or foreign key. I'm using postgresql and Django==2.2.13 and this is a live database I cannot just recreate. -
Cant see any return values using requests.post REST Django
So I am trying to communicate with an external API. The GET request is working fine but when I use the POST request I do not see any values in return. I know for a fact that everything up to the return is working fine because that if I use the shell, I can print the values of the serializer. I also know that the body of the message is correct because I am using Postman as well. Here is the views.py (I am using modelviewset): class Creating_Account(viewsets.ModelViewSet): queryset = GetInfo.objects.all() serializer_class = GetInfo_Modelserializers def create(self, request): URL = 'https://example.com/api' body = {'authenticationKy': settings.KEY} r = requests.post(url, json=body) json = r.json() serializer = GetInfo_Modelserializers(data=json) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) What I am supposed to see: What I am supposed to see What I see when I run the server: What I see when I run the server -
CSS file not affecting page in Django
I have created a navigation bar in html and css and want to implement it into a page. The HTML works fine, but the CSS is not effecting the HTML at all. I have setup my static files correctly and messed around with loads of settings to try and get it working. Any help would be great. I am pretty new to HTML and CSS so if I have made any mistakes, please highlight them. Thanks settings.py """ Django settings for completestudent project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'siv&qzku5zi8b!2d=%0@z2i34eje)$-t#ezbdot1-e9^zahgg@' # 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', 'django.contrib.staticfiles', #own apps 'expendetures', 'pages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] … -
Ec2 not properly reflecting github changes
I deployed my Django project to an ec2 server successfully but the code doesn't necessarily update properly. My first code pull worked successfully initially, but for some reason maybe depending on the browser, there's a 50/50 chance I'll have to refresh that page I updating to see the changes. Also, my second pull wasn't acknowledged at all. I added some tag links and they just don't show up? What could be going on here? -
Filter queryset for foreign key field in django admin
I have a built-in User model which is related to Profile model through one-to-one relation. Profile model has active_group field which is a ForeignKey field related to a built-in Group model. class Profile(models.Model): user = models.OneToOneField( User, ... ) ... active_group = models.ForeignKey( Group, ... ) ... Any user can belong to multiple groups and active_group represents what group is currently selected. In the admin section those models are represented as following. class ProfileInline(admin.StackedInline): model = Profile can_delete = False ... def get_fields(self, request, obj=None): fields = [..., 'active_group'] ... @admin.register(User) class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm add_form = CustomUserCreateForm ... inlines = [ProfileInline, ...] CustomUserChangeForm and CustomUserCreateFrom are heirs of UserCreationForm and UserChangeForm. I want to limit selection in active_group field to only those groups, which user belongs to instead of all existing groups. I tried to use render_change_form and formfield_for_foreignkey but neither worked. -
Rendering multiple dataframes from API calls in Django Views
I have a page that is meant to show company financials based on customers input(they input which company they're looking for). Once they submit, in the view function I want to create 5 API urls which then get the json data, create a list with the dates from 1 API result (they will all contain the same dates, so I will use the same list for all), then create new dictionaries with specific data from each api call, as well as the list of dates. I then want to create dataframes for each dictionary, then render each as html to the template. My first attempt at this I attempted to do all requests.get and jsons.load calls one after another in a try block within " if request.method == 'POST' " block. This worked well when only grabbing data from one API call, but did not work with 5. I would get the local variable referenced before assigned error, which makes me think either the multiple requests.get or json.loads was creating the error. My current attempt(which was created out of curiosity to see if it worked this way) does work as expected, but is obv not correct as it is calling … -
How to implement token authentication using httponly cookie in Django and Drf
I'm building an application with django , Drf and currently using vanilla JS as Frontend for now. I searched almost all through web on different use case for authentication on the web and I found out different links but these links seem to always favour the session authentication and token authentication. Using Django helps us with the session authentication as default so I decided to study the auth process using a token auth. While doing this, I initially used the localstorage as a store for my tokens gotten from the backend response after user authenticates, But for some reasons which are valid , most devs/engineers advise against using the localstorage as it prones one to xss attacks.. So I decided to implement the httponly cookie method, but I haven't seen a practical use of this done on Django, I've seen theories on implementing all these but haven't seen someone done this.. Please how can I use the httponly cookie with my token stored as a cookie with DJANGO EDIT I know a httponly cookie does not allow JavaScript to access a cookie, so I decided to do this. Django sends the cookie httponly with the token as the cookie User … -
Login system with Django, Kivy and SHA256
I've created a simple REST API to list and create users with Django REST Framework and I'm trying to integrate it with an Kivy app. I've used the django.contrib.auth.models.User as my user class, and passwords are being created as show below: serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user As I'm using the set_password function, my REST API gives me SHA256 hashed passwords when I list my users: GET /list/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "username": "user1", "first_name": "Katy", "last_name": "Smith", "email": "katysmith@domain.com", "password": "pbkdf2_sha256$216000$rV8FoNw98RYu$0pdfnA4HO+15o4ov4GZVMXiq0tLNJopfLDV++iPvC5E=" }, { "username": "user2", "first_name": "John", "last_name": "Smith", "email": "johnsmith@domain.com", "password": "pbkdf2_sha256$216000$q4wfz8tiFnnF$gmOuN7HJurbEqHykZ221UX8STcG9pAQ8WQTKF+qDtbw=" }, With that backend, I'm creating an app frontend with Kivy. I have a login screen that asks users to input their username and password. My thinking about how should I create a login system (as I'm just a student in programming) is: Use urllib.request to get the user list; Loop and check if the username provided is in the list; Check if the password provided is the password … -
Limit the time users use the software
I have an app program by Python3 and I want to limited the time users use this app(4 hours a day). My idea: Count and write the time to the hidden file, check the time when open (but users can delete this file( intentionally or by an antivirus program,...)) Count the time users use and send it to my Django website. When users open app, it check out time allowed to use remaining in my web, if the time is up, notify the user and close the app. It is possible? Is there any other way? Please give me a suggestion. -
DAMN ! worker 2 (pid: 2954) died, killed by signal 9 :( trying respawn ... Respawned uWSGI worker 2 (new pid: 3008)
I am using Pytorch with Django on ubuntu ec2. It works well without Nginx and apache but it fails with the server. DAMN! worker 2 (PID: 2954) died, killed by signal 9 :( trying respawn ... -
Djnago with Paypal for server site integration
I am using django 3 and django-paypal module, It's my first time with payment integration so Is there any better way to just add paypal like client site integration in production?? i am trying many tutorial docs but they are not sufficient ! it would be highly appreciated if anyone suggest me any best way and also with the links to follow . Thank you -
"This field is required" after submitting form in a filled field using django and AJAX
I have been trying to add ajax to my django project these past days and I am finding problems with the form submission and data displaying. When I submit a POST form with just one field (with required =True) it does not recognize the form as a valid form (do not pass the .is_valid if) and the form error says "This field is required": forms.py enter code here from django import forms import datetime class FriendForm(forms.Form): name = forms.CharField( required=True, widget=forms.TextInput(attrs={'class': 'special', 'id':'id_name', 'name':'name'})) views.py from django.http import JsonResponse, HttpResponse from django.shortcuts import render from django.core import serializers from .forms import FriendForm, form_busqueda_address from .models import Friend import json import requests from decimal import Decimal import decimal def indexView (request): form = FriendForm () friends = Friend.objects.all () return render (request, "index.html", {"form": form, "friends": friends}) def searchFriend(request): form = FriendForm () if request.method =="POST": form = FriendForm (request.POST) if form.is_valid(): form = FriendForm (request.POST) name = form.cleaned_data['name'] query = Friend.objects.filter(nick_name=name) responseData = serializers.serialize('json', list(query)) return JsonResponse(responseData, safe=False) else: print(form.errors) query = { 'errors': form.errors, } return HttpResponse(json.dumps(query), content_type="application/json") main.js $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for … -
Do I need to check if form.is_valid(): here?
I am doing the CS50 Wiki project as an assignment (it involves a wiki homepage with the ability to search, edit and add entries) and it seems to be working ok. My question is: when I did my edit_entry and new _entry functions as below, I didn't use if form.is_valid(): check, and my question is, why would one need to? Since, when a form data is left blank, Django forms will prompt me (as I understand). Assuming I just stay on the current page until the save button is pressed and the form is not blank is there anything wrong with the following? (In general I understood that Django checks the user form data, so am not too sure in what context the check is needed. (Yes, I'm new to this) Thanks all. def edit_entry(request, title): content = util.get_entry(title) data ={'content': content, 'title':title} if request.method == "POST": util.save_entry(title, request.POST['content']) return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) else: form = EditForm(initial= data) return render(request, "encyclopedia/edit.html", { "content" : content, "title":title, "form":form }) def new_entry(request): form = EditForm() if request.method == "POST": util.save_entry(request.POST['title'], request.POST['content']) return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) else: return render(request,"encyclopedia/new_entry.html",{"form":form}) -
Saving image in media folder via django admin issue
I want to store image by a form. And I want to store it in the media/student_img folder. But it not saving in the database neither into the folder. models.py: class Student(models.Model): photo = models.ImageField(upload_to='student_img/', blank=False) settings.py: MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] -
Function to continuously run for auth user once started - Twitter Bot
I have the following function set up in a Django project to 'like' tweets that contain a particular keyword and therefore automated the account somewhat. The code running in the Django project currently is - def like(request): counter = 0 keyword = request.POST['search'] api = get_api(request) # Getting the user user = api.me() print(user.screen_name) # Adding keyword to search the tweets for search = keyword # Specifying the tweets limit numberOfTweets = 5 # Fetching the tweets and liking them for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): try: tweet.favorite() print('Tweet Liked!') counter = counter + 1 time.sleep(10) except tweepy.TweepError as e: print(e.reason) except StopIteration: break return render(request, "liked.html", {'counter': counter, 'keyword': search}) This likes 5 keywords and then stops. I would like the code to just sleep for a certain period of time and then restart even if the user has closed the web app. Essentially I need it to run like it would on a console if I had it running in a console with the following While loop - while True: like() time.sleep(5000) It essentially is to make a bot that will continuously interact with Twitter for the authorised user until authorisation is withdrawn. -
Django - cannot get the html page to display - NoReverseMatch Error
I have a django app already created and working. I am trying to add another html page. I have added the about page into the home app enter image description here This is home/views.py from django.shortcuts import render, redirect, reverse from hobby_product.models import hobby_product def home(request): """ Return home page """ #return redirect(reverse('home')) return render(request, 'home.html') def not_found(request): """ Return 404 page not found """ return render(request, '404.html') def server_error(request): """ Return 500 internal server error """ return render(request, '500.html') def about(request): return render( request, "about.html" ) Here is the url.py in home: from django.conf.urls import url, include from .views import not_found, server_error, home, about urlpatterns = [ url('/', home, name='home'), url('not_found/', not_found, name='not_found'), url('server_error/', server_error, name='server_error'), url(r'^about$', about, name='about'), ] This is the url.py for the base app: from django.conf.urls import url, include from django.contrib import admin from accounts.views import index, logout, login, registration, user_profile from django.views.generic import RedirectView from django.views.static import serve from .settings import MEDIA_ROOT from accounts import urls as accounts_urls from about.views import about from accounts.views import index from accounts.views import home from hobby_product import urls as urls_hobby_product from cart import urls as urls_cart from home import urls as urls_home from about import urls as urls_about … -
Facing memory error on my Django celery worker instance
I am using django celery with redis (broker). I have observed following error on one of my worker instance. [2020-12-27 02:26:15,920: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx- xxx.ec2.internal [2020-12-27 02:26:40,937: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:27:00,943: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:27:15,955: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:27:45,971: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:28:02,118: INFO/MainProcess] missed heartbeat from worker@ip-xxx-xx-xx-xxx.ec2.internal [2020-12-27 02:28:36,496: CRITICAL/MainProcess] Unrecoverable error: MemoryError() Traceback (most recent call last): File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/worker/worker.py", line 205, in start self.blueprint.start(self) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/bootsteps.py", line 369, in start return self.obj.start() File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 596, in start c.loop(*c.loop_args()) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/celery/worker/loops.py", line 83, in asynloop next(loop) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 364, in create_loop cb(*cbargs) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/transport/redis.py", line 1074, in on_readable self.cycle.on_readable(fileno) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/transport/redis.py", line 359, in on_readable chan.handlers[type]() File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/transport/redis.py", line 694, in _receive ret.append(self._receive_one(c)) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/kombu/transport/redis.py", line 700, in _receive_one response = c.parse_response() File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/redis/client.py", line 3036, in parse_response return self._execute(connection, connection.read_response) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/redis/client.py", line 3013, in _execute return command(*args) File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/redis/connection.py", line 637, in read_response response = self._parser.read_response() File "/home/ec2-user/.virtualenvs/atlasmind/lib/python3.7/site-packages/redis/connection.py", line 330, in read_response response = [self.read_response() for i in xrange(length)] File … -
How to expand Admin form queryset overriding
Two of my models have a bidirectional relation: class Listing(models.Model): main_photo = models.OneToOneField('ListingPhoto', related_name="listing_photos", on_delete=models.SET_NULL, null=True, blank=True) class ListingPhoto(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) Then I wanted in the admin form each Listing instance to be limited exclusively to the related photos. So I overrode the admin form field to narrow the queryset: forms.py: class ListingForm(forms.ModelForm): class Meta: model = Listing fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['main_photo'].queryset = ListingPhoto.objects.filter(listing=self.instance.pk) Which it works, but only for each instance's admin form. I mean that it doesn't affect the model's admin view that contains all the registered instances, where I have set that field to be editable, without visiting every instances' form. I wonder if there is a way to expand the above queryset overriding, to cover also that usage. Thank you in advance. -
settings for the author in a blog API project
I'm working on a blog project which different users can log in and create their own posts. The problem I have, is that when a user logs in his panel, he can select every other author name from the dropdown menu and post with the name of other users. I want every user to post only with his/her name, and not to be able to select other names Below are my codes: models.py: from django.db import models from django.contrib.auth.models import User class post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title views.py: from .models import post from .serializers import PostSerializer from rest_framework import generics, permissions from .permissions import IsAuthorOrReadOnly, IsAdmin class PostList(generics.ListCreateAPIView): permission_classes = (IsAdmin,) queryset = post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthorOrReadOnly,) queryset = post.objects.all() serializer_class = PostSerializer https://uupload.ir/files/kc9x_6.png -
Loginsystem in TOR browser with no JavaScript in Django
Is there a way to make a loginsystem in Django for an onion site hosted on The Onion Router: https://www.torproject.org/ It is pretty normal for sites to have a loginsystem for users to be able to log in, but it came to my interest how this is possible with no cookies and no JavaScript as most TOR browsers prevent JavaScript from running in Safer & Safest mode according to the TOR settings: about:preferences#privacy. I would like to do this in Django, but other frameworks are accepted, but I don't think that it depends on the framework rather than the methode of storing whether the user is logged in (token/cookie) or not logged in. As said this works when STANDARD safety is enabled and Safer & Safest are disabled. This is not meant for any illegal activities! -
Django multiple image upload taking only last one
Its counting true how many images on page but only saving last one image to data It is probably updating data at each loop, how can i just insert all of them as a new record for i in request.FILES.getlist('pic'): print('check') image = iform.save(commit=False) image.car = Article.objects.get(pk = article.pk) image.pic = i image.save() -
How to output Django form on the browser
I'm learning to create a post and comment session with Django and I'm following a tutorial but I don't know why I'm not getting the same result as the one in the tutorial. The post aspect is working but the form for comments is not being displayed on the browser. Even after going through Django documentation and other resources online, I still don't see where I'm getting it wrong. I have the following directories and files: start is my app directory while education is the main django directory start/models.py class Comment (models.Model): post = models.ForeignKey(Post,related_name = 'comments', on_delete = models.CASCADE) name = models.CharField() email = models.Email() body = models.TextField() createdAt = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['createdAt'] start/forms.py from django import forms from .models import Comment class Meta: model = Comment fields = ['name', 'email', 'body'] start/views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import post_comment def fullPost(request, slug): post = Post.object.all() return render (request, 'start/start.html', {'post': post}) if request.method == 'POST': form = post_comment(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect ('fullPost', slug=post.slug) else: form = post_comment() return render (request, 'start/fullPage.html', {'post': post, 'form': form}) start/templates/start/start.html ••• <h3>Comment</h3> <form method = … -
Django Rest + Djoser: signing in doesn't make user authenticated
I am using Django rest framework and Djoser to handle my users authentication. the problem is that after I Sign in using Djoser jwt-login-endpoint(/jwt/create/), I am still not authenticated. config/setting.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = {'AUTH_HEADER_TYPES': ('JWT',),} DJOSER = { 'LOGIN_FIELD': 'email' 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserCreateSerializer', 'user_delete': 'accounts.serializers.UserDeleteSerializer', }, } config/urls.py urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] -
Twitter OAuth [{'code': 215, 'message': 'Bad Authentication data.'}]
I am running a Django web app and logging in with Twitter so that the user can favourite certain hashtags or words. I am getting the following error when running the app - [{'code': 215, 'message': 'Bad Authentication data.'}] Can anyone see where my code is going wrong? Here is my views, it was cloned from a GitHub project so thought it would translate over to my app but having issues with the Authentication. from django.shortcuts import render from .models import * from django.http import * from django.shortcuts import render from django.urls import reverse from django.contrib.auth import logout from django.contrib import messages from auto_tweet_liker.utils import * # from profanityfilter import ProfanityFilter import tweepy import time import os CONSUMER_KEY = ***** CONSUMER_SECRET = ****** def index(request): # return render(request, "index.html") if check_key(request): return render(request, 'index.html') else: return render(request, 'login.html') def like(request): counter = 0 keyword = request.POST['search'] api = get_api(request) # Getting the user user = api.me() print(user.screen_name) # Adding keyword to search the tweets for search = keyword # Specifying the tweets limit numberOfTweets = 5 # Fetching the tweets and liking them for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): try: tweet.favorite() print('Tweet Liked!') counter = counter + 1 time.sleep(10) except tweepy.TweepError … -
Django Rest update many to many field of multiple objects at once
I'm working on chat app django rest backend. Btw I have a problem to update m2m field of multiple objects at once. Inside the Message model there is an m2m field deleted which represents a list of users who deleted this message. class Message(models.Model): # other fields deleted = models.ManyToManyField(User) So I can implement the delete functionality by adding user inside that field when user deletes a specific message. But the problem is when user deletes a conversation(all messages in it), how can I implement to update the delete field of multiple Message objects at once. Because each object has empty delete field, another user inside delete field, or same user inside delete field(means that user already deleted a message before). Sorry for my poor explanation and please tell me there is any unclear part in my question.