Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postman giving "Invalid pk \"1\" - object does not exist."
I'm making a post request to a django server using Postman. But i'm getting the following error [ { "question": [ "Invalid pk \"1\" - object does not exist." ] } ] The object exists with pk = 1. I don't know why postman adds the " in the request and maybe that what causes this. Can you please tell me how to take off the "\ from it. Here is my request : {"user":1,"form":2,"completed_at":"2018-09-04T00:00:00+0100","device_id":5,"responses":[{"resourcetype":"ShortTextResponse","question":1}]} -
AttributeError: module 'users_data.models' has no attribute 'random_string'
When I try to change function name it shows me the error in the command line: AttributeError: module 'users_data.models' has no attribute 'random_string'enter image description here -
Passing foreign key through url with Django
I'm building an app using django in the backend and vuejs in the frontend. I'm stuck with the following: After showing the categories, if the user clicks on one category, I want to display all the extras and menus related to the choosen category. I have declared category_id as a foreign key within the Product model as shown here: from django.db import models from django.contrib.auth.models import * class Category(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) category_des = models.CharField(max_length=250) class Type(models.Model): type_des = models.CharField(max_length=250) class Product(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) category_id = models.ForeignKey(Category, on_delete=models.CASCADE) type_id = models.ForeignKey(Type, on_delete=models.CASCADE) product_name = models.CharField(max_length=250) product_price = models.FloatField() The views: from rest_framework import generics from .import models from .import serializers class CategoryList(generics.ListCreateAPIView): queryset = models.Category.objects.all() serializer_class = serializers.CategorySerializer class CategoryDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Category.objects.all() serializer_class = serializers.CategorySerializer class MenuList(generics.ListCreateAPIView): queryset = models.Product.objects.filter(type_id=1) serializer_class = serializers.ProductSerializer class MenuDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Product.objects.filter(type_id=1) serializer_class = serializers.ProductSerializer class ExtraList(generics.ListCreateAPIView): queryset = models.Product.objects.filter(type_id=2) serializer_class = serializers.ProductSerializer class ExtraDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Product.objects.filter(type_id=2) serializer_class = serializers.ProductSerializer urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from fastfood_app import views urlpatterns = [ path('Menu/', views.MenuList.as_view()), path('Menu/<int:pk>/', views.MenuDetail.as_view()), path('Extra/', views.ExtraList.as_view()), path('Extra/<int:pk>/', views.ExtraDetail.as_view()), path('Category/', views.CategoryList.as_view()), path('Category/<int:pk>/', views.CategoryDetail.as_view()), ] Here is the vue page in the frontend: <template> <div … -
Data not passed when using HttpResponseRedirect in DJANGO
i am using Django redirect , currently it is redirecting to the page , but am not able to pass the data from views --> template . i tried different methods checking youtube and stackoverflow questions but nothing worked , below is my code def Dashboard(request): status = output['status'] if(status == 'success'): msg = output['id'] else: msg = output['error'] return HttpResponseRedirect(reverse('AllOrders', kwargs={'status':status,'msg':msg})) and here is how i fetch it in template: div class="col-span-12 mt-8"> {% if kwargs.status == "success" %} <div class="alert alert-outline-success alert-dismissible show flex items-center mb-2" role="alert"> {{kwargs.status}}</div> {% endif %} and this shows me INTERNAL SERVER ERROR , but if i remove passing arguments , everything works fine , Can anyone help me in this -
pull audio file from django backend in vuejs
I am trying to build an app that would transfer recorder audios from the vuejs front end to my django back end and get them back. However I have troubles with both ways: front -> backend : my audios recordings are 'blobs' format. Should I 'send' in vue to django the entire blob and django would store it or would I juste create an url and vue would store the file on the server ? backend -> front : I try to display an audio by putting in the url of where I stored them, however I keep having 404 errors... Here is my django audio models.py: class Audio(models.Model): id = models.SlugField(max_length = 6, primary_key = True, unique = True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) room = models.ForeignKey(settings.AUTH_ROOM_MODEL, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, help_text="timestamp of the audio") audiofile = models.FileField(upload_to='recordings/%Y/%m/%d') def __str__(self): return str(self.audiofile) def __str__(self): return f"{self.id} ({self.user})" Here is my vue, where I want to display audios: onResult() { var div = document.getElementById("audiosContainer"); var link = document.createElement("link"); link.rel = "stylesheet"; link.href = this.audios[0].audiofile; // here http://localhost:8000/files/recordings/2021/05/04/file_example_MP3 div.innerHTML += '<audio controls name="media"><source src="' + link.href + '" type="audio/wav"></audio>'; }, my django python view: class AudioView(APIView): def get(self, request): all_audios = Audio.objects.all().order_by("id") … -
How to use function of order_set if I am using filter instead of get?
When I use get instead of filter in views.py, I get error saying customer object isn't iterable, which I understand. But using filter instead of get doesn't allow me to user 'order_set' function (also in views.py), showing up with an error message: 'QuerySet' object has no attribute 'order_set'. How can I workaround this? views.py def customer(request, pk): customer = Customer.objects.filter(id=pk) order = customer.order_set.all() context = {'customer': customer, 'order':order} return render(request, 'accounts/customer.html', context) customer.html <table> <tr> <th>Email</th> <th>Phone</th> </tr> {% for i in customer %} <tr> <th> {{i.email}}</th> <th> {{i.phone}}</th> </tr> {% endfor %} </table> <table class="table table-sm"> <tr> <th>Product</th> <th>Category</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {%for order in order%} <tr> <td>{{order.product}}</td> <td>{{order.product.category}}</td> <!-- the above is chaining --> <td>{{order.date_created}}</td> <td>{{order.status}}</td> <td><a href="">Update</a></td> <td><a href="">Remove</a></td> </tr> {% endfor %} </table> urls.py urlpatterns = [ path('', views.home), path('products/', views.products), path('customer/<str:pk>', views.customer) ] -
Django pass context to a nested ModelSerializer
I have a Foo serializer inside a Bar serializer. I want to pass the context request to Foo serializer so I can make a valid url of Foo object. class FooSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() def to_internal_value(self, data): # Save depending on name foo = Foo.objects.get(name=data) return {'foo': foo} def to_representation(self, instance): request = self.context.get('request') # Get request from BarSerializer name = instance.foo.name link = request.build_absolute_uri( '/apps/foo/{}'.format(instance.foo.id)) return {'name': name, 'link': link} class BarSerializer(serializers.ModelSerializer): foo = FooSerializer(source='*') How do I pass the context request from one serializer to another? -
Mark all duplications in annotations
I have a model: class Order(models.Model): data = models.TextField() sessionid = models.CharField(max_length=40) I need to get queryset where every unique sessionid will be masked as name or something. For example if I have 3 objects { "data": "...", "session_id": "foo" }, { "data": "...", "session_id": "foo" }, { "data": "...", "session_id": "bar" } query should annotate each unique session_id to return: { "data": "...", "name": "A" }, { "data": "...", "name": "A" }, { "data": "...", "name": "B" } How could I make this query? Thanks! -
how to join 3 tbales with django?
i need to join 3 tables using django , here is my problem a super user can create a Project and assign users to it a Project contains a Tasks each user have specific tasks under a projects thanks a lot ! class Project(models.Model): name = models.CharField(max_length=100, null=True) category = models.CharField(max_length=50, choices=CATEGORY, null=True) users = models.ManyToManyField(User,db_table='users_to_mission') superuser = models.ForeignKey(User,on_delete=models.CASCADE, related_name='created_by') def __str__(self): return f'{self.name}' class TaskList (models.Model): title =models.CharField(max_length=1000, null=True) def __str__(self): return f'{self.titre}' class Tasks (models.Model): titre = models.ManyToManyField(TaskList) project = models.ForeignKey(Project , on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='user') def __str__(self): return f'{self.titre}' -
Test Concurrent Clients in Django's TestCase
I want to test the performance of Django when a number of clients making requests concurrently. I had no luck using Python's multiprocessing package in a TransactionTestCase case but got it to work using threading, like this: class UserRegisterTestCase(TransactionTestCase): NUM_PROCS = 5 @staticmethod def register(): email = '{}@test.com'.format(threading.get_ident()) c = Client() c.post(reverse('my_login'), {'action': 'register', 'email': email, 'password_1': '12345', 'password_2': '12345'}) connection.close() def test_register(self): threads = [] for i in range(self.NUM_PROCS): threads.append(threading.Thread(target=self.register)) for t in threads: t.start() for t in threads: t.join() self.assertEqual(MyClients.objects.count(), self.NUM_PROCS) The test passed, but I wonder with Python's GIL, is it true that 5 concurrent clients are trying to register at the same time, or is it just some syntactic sugar in that under the hood, Django sees and handles one client request at a time? If latter is the case, what's the right way to test for concurrent clients? Thanks. -
django: FOREIGN KEY constraint failed
In my django project when I'm trying to add a faculty it throws a "FOREIGN KEY constraint failed" error. Here I'm trying to save the faculty under the institute and all the roles have a user login which is linked with a one to one field models.py : class CustomUser(AbstractBaseUser): is_admin = models.BooleanField(default=False) is_institute = models.BooleanField(default=False) is_faculty = models.BooleanField(default=False) is_student = models.BooleanField(default=False) user_email = models.EmailField(verbose_name='Email',primary_key=True,unique=True) date_created = models.DateTimeField(verbose_name='date created', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) user_image = models.ImageField(upload_to='profile_images',null=True,blank=True) USERNAME_FIELD = 'user_email' class Institute(models.Model): user = models.OneToOneField('CustomUser',primary_key=True,on_delete=models.CASCADE) institute_name = models.CharField(max_length=75,verbose_name="Institute Name",null=True,blank=True) institute_address = models.TextField(max_length=100,verbose_name="Address",null=True,blank=True) institute_number = models.PositiveBigIntegerField(verbose_name="Mobile Number",null=True,blank=True) institute_id = models.IntegerField(unique=True,verbose_name="Institute Id",null=True,blank=True) class Faculty(models.Model): user = models.OneToOneField('CustomUser',primary_key=True,on_delete=models.CASCADE) faculty_id = models.CharField(max_length=75,verbose_name="Faculty Id",null=True,blank=True) first_name = models.CharField(max_length=75,verbose_name="First Name",null=True,blank=True) last_name = models.CharField(max_length=75,verbose_name="Last Name",null=True,blank=True) faculty_number = models.PositiveIntegerField(verbose_name="Mobile Number",null=True,blank=True) institute = models.ForeignKey('Institute',on_delete=models.CASCADE) class Meta: unique_together = [['faculty_id','institute']] views.py add faculty function: def addFaculty(request): if request.method == "POST": user = CustomUser.objects.create_user(user_email=request.POST.get('user_email'),role="faculty",password=request.POST.get('password')) user.save() Faculty.objects.create(user=user,faculty_id=request.POST.get('faculty_id'),faculty_number=request.POST.get('faculty_number'),first_name=request.POST.get('first_name'),last_name=request.POST.get('last_name'),institute=Institute(user=request.user)).save() return redirect('dashboard') else: extraFields = [ { 'label':"First Name", 'name':'first_name', 'type':'text' }, { 'label':"Last Name", 'name':'last_name', 'type':'text' }, { 'label':"Faculty Id", 'name':'faculty_id', 'type':'number' }, { 'label':"Faculty Number", 'name':'faculty_number', 'type':'number' } ] return render(request,'learnerApp/addUser.html',context={'extraFields':extraFields}) -
Django Dynamic MySQL Table Creation
How to create Dynamic MySQL Database Table in Django? Suppose I create a table 'surveys'. Enter a survey 'Student Survey' which has id '1' in 'surveys' table. I want to create 'response_1' table for saving the responses. Enter a survey 'Employee Survey' which has id '2' in 'surveys' table. 'response_2' table for saving the responses. Enter a survey 'Job Survey' which has id '3' in 'surveys' table. 'response_3' table for saving the responses. And so on.. Please help.. Thank you. -
Python unittest and coverage missing not working
I have the following function: def edge_delete_check(id: str) -> bool: queryset = NsRequestRegistry.objects.filter( **{ 'nsr_insd__constituent-isd__contains': [ {'id': id} ] } ) if not queryset: return True else: return False And when I run my tests, coverage tells me that i'm missing on return False. So I've been trying to run a test that tests the False condition on my function above. class HelperTests(unittest.TestCase): """Tests helper functions""" def test_edge_delete_check_false(self): result = edge_delete_check('e932bb55-44cb-4ec4-a0cb-1749fe51e5fd') self.assertTrue(result, False) The given id should return a False for result = edge_delete_check('e932bb55-44cb-4ec4-a0cb-1749fe51e5fd'), which it does, which means the given id can not be deleted as queryset in the function above returned a non-empty result. But doing a self.assertFalse(result, False) throws an AssertionError: True is not false : False. If I change my assert to: self.assertTrue(result, False) the test passes but the coverage report still says that my return False on my function is missing. So the two questions I have are: How should I write my test to test the return false statement on my function above? How can I get coverage to report that it has tested the return false statement and is no longer missing? Thanks for any help. -
How to handle patch method in AJAX?
How to handle the patch method from AJAX. My backend is written in Django rest API.Im using model viewsets.Backend view as below: class ProductAPI(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = ProductTbl.objects.all() @action(detail=False, methods=['PATCH']) def get_object(self,*args,**kwargs): return get_object_or_404(**kwargs) def update_product(self,request,pk): try: product_obj = self.get_obj(pk=pk) serializer = self.serializer_class(product_obj,data = request.data, partial = True) if serializer.is_valid(): serializer.save() return Response({},status = 200) return Response(serializer.errors,status = 400) except Exception as e: return Response({},status = 500) urls.py path('product/edit/<int:pk>/', ProductAPI.as_view({'patch': 'update_product'}), name='update_products'), my ajax code as follows: var form = new FormData($("#update_form")[0]) $.ajax({ type:"PATCH", url : "/product/edit/1", data:form, success:function(data){ }, error:function(data){ } }) Still, I'm getting error 405.Method not allowed... -
Django channels create a separate task that sends message to group at intervals
Essentially I am trying to create a real time applications for teams with Django channels. What happens is that there is a physics simulator that runs on the server and then sends the game state to be displayed on the client machines. What I need is a function that runs every 1/20 seconds on the server and then sends an output to each socket in a group. What I am currently thinking of doing is using threading to spin up a task (only needs to run for 60s total) which runs the physics simulation and then waits for the remaining time until the next execution. But I can guess that there is a real way to do this with Django channels which I can't find in the documentation. -
Django: Open a form from admin action
I'm trying to change some things inside this logic, so for now I'm only able to send a push notification to one user at the time and I'm trying to make that I would be able to select multiple users. So I have created an admin action which let's me to select some users and now I'm struggling about creating a form which would fulfill the users that I selected. This is what I have now (Sending push notification to one user at the time). Select users that I want to send the push notification. This is my code: class CustomUserAdmin(UserAdmin): fieldsets = ( (None, {'fields': ('password',)}), (_('Personal info'), {'fields': ('email', 'phone', 'companies', 'active_company', 'avatar', 'completed_registration', 'language')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined', 'work_hours_until', 'work_hours_from')}), (_('Terms and conditions agreement'), {'fields': ('agreement_date', 'agreement_text')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('phone',), }), ) list_display = ['id', 'phone', 'email', 'is_active', 'is_staff', 'is_superuser', 'date_joined', 'last_login'] ordering = ('-id',) search_fields = ('email', 'phone') exclude = [] actions = ('send_push_notification', ) def send_push_notification(self, request, queryset): # Create some kind of form and logic..?? queryset.update(is_staff=False) # This is just to test -
Doesn't save form in django python foreignkey
There is a form with input text, which is not saved and throws a ValidationError, because there is no such value in the foreignkey model. The problem is that the check goes against pk, but the name. How to do it? (via select it is impossible, since this is entered and ajax gives him options). models class Orders(models.Model): service = models.ForeignKey('Service', null=True, blank=True, on_delete=models.PROTECT) class Service(models.Model): name = models.CharField(max_length=150, db_index=True, unique=True) def __str__(self): return self.name forms class SimpleOrderAddForm(forms.ModelForm): class Meta: model = Orders fields = ['service'] def clean_service(self): name = self.cleaned_data['service'] try: get_service = Service.objects.get(name=name) return get_service.pk except get_service.DoesNotExist: return name picture html form: UPD: a question in a different vein: how to change validation from pk to name field in input forms? UPD2: when entering the correct value into input, it outputs: Choose the correct option. Your option is not among the valid values. the error is that when entering, you must specify the pk field for the Service model and then the model is saved. And how to make the comparison by the name field take into account when writing the form? UPD3: already asked this question in a different vein here: here and here -
How to change the dbsqlite file ownership in gcp?
I have hosted my Django app to gcp. I am able to access the url aswell. But I am not able to login to the django admin panel. It gives me the following message. As per what I read it seems to be a permission issue. How can I fix this problem? NOTE: I dont want to use any cloud database. I want to stay with dbsqlite. Any help is appreciated. -
Django sending email with pdf
How to send an email with pdf or attachment and html using django i received no error but no email send from django.core.mail import EmailMessage send_mail=EmailMessage(email_template, [settings.EMAIL_HOST_USER, Email] , [Email]) send_mail.attach_file('static/pdf/ENROLLMENT-PROCEDURE-2021-.pdf') send_mail.send() print(send_mail) -
How to get count of model objects in django
Would anyone try to explain to me why I can't get a count of what is the query. I'd like to get count for all the books borrowed by every student def view_student(request): issues = Student.objects.all() for issue in issues: borroweds = Issue.objects.filter(borrower_id__student_id = issue.student_id).count() print(borroweds) return render(request, 'view_student.html', {'borroweds':borroweds}) And the tml code is this. {% for student in students %} <tr> <td>{{ forloop.counter }}</td> <td>{{ student.student_id }}</td> <td>{{ student.name }}</td> <td>{{ student.batch }}</td> <td>{{ student.semester }}</td> <td><a href="{% url 'all_borrowed' student.student_id %}"> {{ borroweds }}</a> </td> </tr> {% endfor %} This gives me a list of all students with books borrowed print(borroweds) while in the template {{ borroweds }} gives me 0's Am I calling it the wrong way of the code in the views???? -
centre the contents of a login page
I'm having trouble centring the contents of my login page Can you help me with the styling? I basically want the long input fields to be in the centre and be short like a typical login page. I had another question regarding bootstrap, I found a code snipped for some component for which I used version 3.4 but I am not able to use the other features of the higher versions for my other components..is there a way around that? the code is: {% extends "auctions/layout.html" %} {% block body %} <h2>Login</h2> {% if message %} <div>{{ message }}</div> {% endif %} <form action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="form-group"> <input autofocus class="form-control" type="text" name="username" placeholder="Username"> </div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <input class="btn btn-primary" type="submit" value="Login"> </form> Don't have an account? <a href="{% url 'register' %}">Register here.</a> {% endblock %} -
Updation of fileds in Django
I am looking to update the profile of my user in Django. However, after clicking the submit button on my webpage, the changes are not reflected into the database and backend. Below, are my models.py, views.py, urls.py, forms.py and html page files containing details of the same. How can I fix this issue. models.py: class User_profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile") Address = models.CharField(max_length=150) Skills = models.CharField(max_length=150) Work_Experiences = models.CharField(max_length = 150) Marital_Status = models.CharField(max_length = 150) Interests = models.CharField(max_length = 150) Edcucation = models.CharField(max_length = 150) category = models.ForeignKey("Category.Category",on_delete=models.CASCADE,default="demo") sub_category = models.ForeignKey("Category.SubCategory",on_delete=models.CASCADE,default="demo") phone_number = models.CharField(max_length=11) Aadhar_Card = models.FileField(upload_to="user_aadhar_card/",default="") def __str__(self): return str(self.user) views.py: def myaccount(request): instance1 = User_profile.objects.get(user=request.user) if request.method == "POST": user_form = UserForm(request.POST,instance=request.user) profile_form = UserProfileForm(request.POST,instance=instance1) if user_form.is_valid(): user_form.save() messages.success(request,('Your profile was successfully updated!')) elif profile_form.is_valid(): profile_form.save() messages.success(request,('Your profile was successfully updated!')) else: messages.error(request,('Unable to complete request')) return redirect('dashboard') user_form = UserForm(instance=request.user) profile_form = UserProfileForm(instance=instance1) return render(request=request, template_name="userprofile.html", context={"user":request.user, "user_form":user_form, "profile_form":profile_form }) forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ["username", "email", "password","first_name","last_name"] class UserProfileForm(forms.ModelForm): class Meta: model = User_profile fields = '__all__' exclude = ['user'] def _init_(self, *args, **kwargs): super()._init_(*args, **kwargs) self.fields['first_name'].widget.attrs.update({'id':'fname','class': 'form-control'}) self.fields['last_name'].widget.attrs.update({'id':'lname','class': 'form-control'}) self.fields['email'].widget.attrs.update({'id':'email','class': 'form-control'}) self.fields['username'].widget.attrs.update({'id':'uname','class': 'form-control'}) self.fields['password'].widget.attrs.update({'id':'password','class': 'form-control'}) self.fields['Address'].widget.attrs.update({'id':'address','class': 'form-control'}) self.fields['Skills'].widget.attrs.update({'id':'skills','class': 'form-control'}) self.fields['Work_Experiences'].widget.attrs.update({'id':'we','class': … -
how to get data with product id in django
i am working on oms django i stuck at getting data of product with product id in order form how to get data of product in neworderForm with product id i added some models called new_product and new_orders i want data of new_product in new_orders field in django anyoe can help* models.py code i added some models called new_product and new_orders i want data of new_product in new_orders field in django anyoe can help class new_order(models.Model): Product_Name = models.CharField(max_length=250, null=True) Product_Id = models.CharField(max_length=10, null=True) Free_Size = models.IntegerField(default=0, null=True) S = models.IntegerField(default=0, null=True) M = models.IntegerField(default=0, null=True) X = models.IntegerField(default=0, null=True) XL = models.IntegerField(default=0, null=True) L = models.IntegerField(default=0, null=True) # customer details Name = models.CharField(max_length=250, null=True) Address = models.TextField(null=True) Pincode = models.IntegerField(null=True) Mobile = models.IntegerField(null=True) Alt_Mobile = models.IntegerField(null=True) Date_Of_Order = models.DateField(auto_now=True) Order_Type = ( ("Prepaid", "Prepaid"), ("C.O.D", "C.O.D"), ) Order_Type = models.CharField(max_length=30, null=True, choices=Order_Type) Order_Id = models.CharField( max_length=5, blank=True, null=True, default=random_string ) Total_Amount = models.PositiveIntegerField(null=True, blank=True) Track = models.CharField(max_length=50, null=True) Courier_Partner = models.CharField(max_length=50, null=True) Status = ( ("Pending", "Pending"), ("Dispatched", "Dispatched"), ("Cancelled", "Cancelled"), ) Status = models.CharField(max_length=50, null=True, choices=Status, default="Pending") def __str__(self): views.py code from django.shortcuts import render, redirect, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from … -
How to solve Session matching query does not exist in Django sessions
I added a one user instance functionality to my web app, where a user is logged-out whenever they login in another browser. It worked well, until I updated the logged in user information. whenever I try loggin in- my app throws a DoesNotExist error; stating that Session matching query does not exist. and does not login or even create a new user. How do I get over this error, I will attach codes if need be. -
I want to post a list of JSON values to a model's field in Django
I want to post a movie into the collection's movie field( list of movies). I define the model as class Movie(models.Model): # collection = models.ForeignKey(Collection, on_delete = models.CASCADE) #, related_name='reviews' title = models.CharField(max_length=200) description = models.CharField(max_length=200) genres = models.CharField(max_length=200) uuid = models.CharField(max_length=200) def __str__(self): return self.title class Collection(models.Model): title = models.CharField(max_length=200) uuid = models.CharField(max_length=200, primary_key = True) description = models.CharField(max_length=200) movie = models.ForeignKey(Movie, on_delete = models.CASCADE) def __str__(self): return self.title this is how i am using the viewset class CollectionViewSet(viewsets.ModelViewSet): queryset = models.Collection.objects.all() serializer_class = serializers.CollectionSerializer but i am not able to enter values for the movie field enter image description here