Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
startproject django creates invisible project/folder
im using pytohn 3.7.2 and django 2.1.7. Im not getting any error for python django-admin startproject projectname but the created project is not visible in the directory. im also able to runserver by manage.py runserver but cant see the folder. -
Nested object for Rest Framework Django
Currently, I have object coming in in django rest as shown below. What's best method to creating nested object to appear as desired output? I tried experimenting with jsonfield, but the format does not appear correctly. I also need to query the content of name and jobcode, so that is needed as well. Current output [ { "a": "4352", "b": "4352", "c": "sub", } ] Desired Output [ { "a": "4352", "b": "4352", "c": [ { "name" : "sub", "jobcode" : 1234 }, { "name" : "mac", "jobcode" : 1234 }, ] }, ] Models.py class Sample(models.Model): a = models.CharField(max_length=255, null=False) b = models.CharField(max_length=255, null=False) c = models.CharField(max_length=255, null=False) Serializer class SampleSerializer(serializers.ModelSerializer): class Meta: model = Sample fields = ("a", "b", "c") def update(self, instance, validated_data): instance.a = validated_data.get("a", instance.a) instance.b = validated_data.get("b", instance.b) instance.c = validated_data.get("c", instance.c) -
Filtering posts
I am trying to filter posts based on some privacy settings. The way my Post Manager is currently setup does not achieve that. Do I need to specify the friends Ids inside of the filter, for example like the only_me() function? Also In my views.py I am not sure if I need to make a different list variable for every query or keep using streamlist and append the queries to it. As it stands now, when I create a posts with a privacy setting all previous posts values change to it. Also I'm not sure how to properly filter when a GET method is requested. It currently shows all posts. Any help would be greatly appreciated. This is my post forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = [ "content", "image", "privacy" ] This is my models for posts. I'm using a Post Manager to make filtering easier. # I should probably specify the id, right? class PostManager(models.Manager): def all(self, *args, **kwargs): query_set = super(PostManager, self).order_by("-timestamp") return query_set def filter_by_public(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=0).order_by("-timestamp") return query_set def filter_by_private(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=1).order_by("-timestamp") return query_set def filter_by_friends(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=2).order_by("-timestamp") return query_set … -
Trying to deploy on pythonanywhere and not working
I've downloaded the pythonanywhere installation tool and am trying to deploy with the following line: pa_autoconfigure_django.py <https://github.com/myusername/myproject.git> Then, I get this a key error. My project runs on local. File "/projects/hosproject/venv/lib/python3.7/site-packages/pythonanywhere/project.py", line 16, in __init__ self.virtualenv = Virtualenv(self.domain, self.python_version) File "/projects/hosproject/venv/lib/python3.7/site-packages/pythonanywhere/virtualenvs.py", line 12, in __init__ self.path = Path(os.environ["WORKON_HOME"]) / domain File "/projects/hosproject/venv/bin/../lib/python3.7/os.py", line 678, in __getitem__ raise KeyError(key) from None KeyError: 'WORKON_HOME' Need some help to debug this and try to deploy again. If it helps, I'm new to Django and following this tutorial: https://tutorial.djangogirls.org/en/deploy/. -
Insert data into django model on GET request
Currently I am inserting data into django model using view. It works fine. However, I want to insert data for each GET request done on that view. Right now when I run the server it insert the data into model. So, when new data added into source JSON file (Remote API) and if my server is running even if I do the GET request it does not add new data into model. To add the new data I have to stop the server and start it again. I want it in a way that even if new data added into source JSON file (Remote API) and my server is running if I do the GET request I am able to add new data into model. Please refer below code View.py: from rest_framework import generics from customer.models import Customers from .serializers import CustomersSerializer, CustomersKeySerializer import json import urllib.request import pyodbc class CustomerAPIView(generics.ListAPIView): j = urllib.request.urlopen("https://web.njit.edu/~jsd38/json/customer.json") customer_data = json.load(j) cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=DAL1281;" "Database=Test;" "Trusted_Connection=yes;") cursor = cnxn.cursor() cursor.execute("SELECT CustomerId FROM dbo.Customers") CustomerIdRows = [x[0] for x in cursor.fetchall()] CustomerIds = Customers.objects.values_list('CustomerId', flat=True) for customer in customer_data: CustomerId = customer["@Id"] Name = customer["Name"] PhoneNumber = customer["PhoneNumber"] EmailAddress = … -
Django-nose/Coverage.py fails when running multiple tests in a directory
I have a strange issue with coverage.py and django. I have all of my TestCase files in a django app called tests. Running a specific TestCase works just fine with no errors (command used is below): coverage run manage.py test tests.myTestCaseFile However, when i run the entire set of TestCases in the tests folder this fails (command used is below): coverage run manage.py test tests In this case many ImportErrors are triggered as well as KeyError: 'en-us'. Essentially every single TestMethod errors out in one way or another. Any ideas what could be happening here? Spent quite a bit of time but am getting nowhere. -
Return a QuerySet of lists grouped by date
I have a Transaction model in my database which stores all of my banking transactions and displays them on a page. They are all listed but the list is very long. To shorten it, I want to group them by month/year so I can create a collapsible list on the page with all months collapsed except for the current month. A long search only returns the aggregate and annotate functions (which I don't fully understand). The closest I've gotten is this: >>> data = Transaction.objects.annotate(month=TruncMonth('date')).values('month').annotate(c=Count('id')).values('month', 'c') >>> data <QuerySet [{'month': datetime.date(2016, 12, 1), 'c': 74}, {'month': datetime.date(2017, 1, 1), 'c': 109}, {'month': datetime.date(2017, 2, 1), 'c': 70}, {'month': datetime.date(2017, 3, 1), 'c': 92}, {'month': datetime.date(2017, 4, 1), 'c': 79}, {'month': datetime.date(2017, 5, 1), 'c': 79}, {'month': datetime.date(2017, 6, 1), 'c': 83}, {'month': datetime.date(2017, 7, 1), 'c': 99}, {'month': datetime.date(2017, 8, 1), 'c': 98}, {'month': datetime.date(2017, 9, 1), 'c': 112}, {'month': datetime.date(2017, 10, 1), 'c': 87}, {'month': datetime.date(2017, 11, 1), 'c': 82}, {'month': datetime.date(2017, 12, 1), 'c': 86}, {'month': datetime.date(2018, 1, 1), 'c': 113}, {'month': datetime.date(2018, 2, 1), 'c': 98}, {'month': datetime.date(2018, 3, 1), 'c': 121}, {'month': datetime.date(2018, 4, 1), 'c': 111}, {'month': datetime.date(2018, 5, 1), 'c': 107}, {'month': datetime.date(2018, 6, … -
RecursionError at /form/movie/ maximum recursion depth exceeded while calling a Python object
I am not quite sure how manytomany fields work in django. so what i have here is a profile model where in the name field i want to add the username that i will get from the login credentials, and movies will be added from a form that was created using the movie model. I'd like to understand what's wrong in the views.py file here. Thanks enter image description here enter image description here my models.py file: from django.db import models from django.contrib.auth.models import User # Create your models here. class Article(models.Model): title = models.CharField(max_length = 200) body = models.TextField() pub_date = models.DateTimeField('date published') likes = models.IntegerField(default = 0) def __str__(self): return self.title class Comment(models.Model): name = models.CharField(max_length = 200) body = models.TextField() pub_date = models.DateTimeField('date published') article = models.ForeignKey(Article, on_delete=models.CASCADE) class Language(models.Model): name = models.CharField(max_length = 20) def __str__(self): return self.name class Framework(models.Model): name = models.CharField(max_length = 20) language = models.ForeignKey(Language, on_delete=models.CASCADE) def __str__(self): return self.name class Movie(models.Model): name = models.CharField(max_length = 20) def __str__(self): return self.name class Character(models.Model): name = models.CharField(max_length = 20) movies = models.ManyToManyField(Movie) def __str__(self): return self.name class profile(models.Model): name = models.ForeignKey(User,on_delete=models.CASCADE, related_name="name") # name = models.CharField(max_length = 20) movies = models.ManyToManyField(Movie) def __str__(self): return … -
Attach two users to model object
I have a model called Booked, that has a many to many user relationship. When my BookedForm is submitted, I want the instance to save two user ids (one for the teacher who posted the lesson, and one for the student who booked the lesson). I know I can save the current user with book.user = request.user, but I am wondering how to save the teacher user, who's user.id is attached to the lesson that is passed through lesson.id in the form. HTML <form action="{% url 'view:book_lesson' lesson.id %}" method="POST" autocomplete="off"> {% csrf_token %} <div class="hidden"> {% load tz %} {% timezone user.time_zone %} <p><span id="start">{{ lesson.lesson_datetime_start|time }}</span></p> <p><span id="end">{{ lesson.lesson_datetime_end|time }}</span></p> {% endtimezone %} </div> <div class="text-center"> <div class="form-group"> <div class="ins-left"> <p>{% render_field form.booked_instrument value=lesson.lesson_instrument %}</p> </div> <div class="date-right"> <p>{% render_field form.booked_date value=lesson.lesson_datetime_start|date %}</p> </div> </div> <br /> <br /> <div class="form-group"> <label>Length</label> {{ form.booked_length }} </div> <br /> <div class="form-group"> <label>Time</label> {{ form.booked_time }} </div> <div class="ins-left"> <p id="price"></p> </div> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button">Book Now</button> </div> </div> </form> models.py class Booked(models.Model): users = models.ManyToManyField(User) booked_instrument = models.CharField(max_length=255, blank=True) booked_length = models.CharField(max_length=255, choices=length_list, blank=True) booked_date = models.DateField(null=True, blank=True) booked_time = models.TimeField(null=True, blank=True) views.py def book_lesson(request, lesson_id): … -
No module named 'channels'
I am trying to install channels, following their tutorial(channels tutorial) but when I try to run the server I get the error: No module named 'channels'. I have tried reinstalling it, moving the app to the top of the list of "INSTALLED_APPS" but it still does not work. I have installed python 3.7 and django 2.1.3 -
Is there a way to paginate through individual template elements?
Problem: I currently have a template that has multiple nested divs which would contain different list items. Currently if I click the next button on one of the elements, the full page reloads and now all of the elements or on the next or previous page. Code: Main template code in a div {% include "users/activities.html" with activities=action1 table_title='Signups' action_verb='action1' %} {% include "users/activities.html" with activities=action2 table_title='Actions' %} {% include "users/activities.html" with activities=action3 table_title='Actions 2'%} Activity template code with pagination: {% if activities.has_other_pages %} <div class="paginationWrap"> <ul class="pagination"> {% if activities.has_previous %} <li><a href="?page={{ activities.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in activities.paginator.page_range %} {% if activities.number == i %} <li class="active"><span> {{ i }} </span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if activities.has_next %} <li><a href="?page={{ activities.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> </div> {% endif %} Goal: The ability to click in one div and not have all of divs return page change. -
Djangae Gauth integration
I'm following the "Gauth authentication" portion of Djangae's documentation but I'm running into some unexpected behavior. I've configured urls.py and settings.py as specified by the documentation (the current settings are mostly a result of using the Djangae Scaffold) but at no point are users prompted to authenticate using or link their Google account. I've tried un/setting DJANGAE_CREATE_UNKNOWN_USER but this has no impact. I've also tried running commands inspired by sitepackages/prod/djangae/contrib/gauth/tests.py in my local shell in order to verify that the back-end configuration is correctly configured and that users can actually be authenticated against AppEngineUserAPIBackend but that fails because my User model (djangae.contrib.gauth_datastore.models.GaeDatastoreUser) seems to be missing required attributes: AttributeError: 'GaeDatastoreUser' object has no attribute 'user_id'. So, am I misunderstanding how this is all supposed to work and must take some additional steps to get Google Sign-In working? Or have I (likely) misconfigured my application? (I'm happy to include genericized versions of my config, but as I said, they've come directly from Djangae Scaffold or the documentation.) Environment: Djangae (0.9.11) Django (1.11.19) -
Django - Performing a subquery on a subquery and then getting all associated fields
I have data in the following form: collection_name | type | manufacturer | description | image_url --------------------------------------------------------------------------- beach | bed | company a | nice bed | 1.jpg beach | king bed | company a | nice bed | 1.jpg beach | nightstand | company a | nice ns | 1.jpg grass | chest | company a | nice chest | 2.jpg apple | chest | company a | nice chest | 3.jpg fiver | chest | company b | good chest | 4.jpg and models like: class Product(models.Model): collection_name = models.TextField(null='true',blank='true') type = models.TextField(null='true',blank='true') manufacturer = models.TextField(null='true',blank='true') description = models.TextField(null='true',blank='true') image_url = models.TextField(null='true',blank='true') What am I trying to do in my app at the moment is: Link to a product by id (using the hidden pk id field), Then for that id get the collection name Get a list of products with that collection name Get a list of distinct image_urls from the set of products with a certain collection name * for each image_url in the new set, get all records that have the same image_url The reason I want to do this, is as you can see in the above sample data, different products sometimes reuse the … -
Django Rest Framework with Cachalot
I did a quick search on how to cache DRF queries. I found Django-Cachalot. Followed installation instructions on the documentation. Installed and setup redis. Now redis works. I've setup relevant settings.py settings for redis-django. Added cachalot to INSTALLED_APPS. Restarted Django. Now there are no more instructions on how to cache ORM results. I assumed cachalot automagically caches ORM results but that's not the case it seems. After trying to warm up the cache, I run redis-cli and run "KEYS *", I get an empty set. No keys. Redis log shows no errors. I'm probably doing something wrong on the view side. Here's one of my views: class ProjectListView(APIView): authentication_classes = (TokenAuthentication,) def get(self, request, format=None): """ Return a list of all projects. """ if request.user is None: raise Http404 projects = Project.objects.filter(user=request.user) serializer = ProjectSerializer(projects, many=True) return JsonResponse(serializer.data, safe=False) What can I do to get results from cache? -
Model relationships Django
A bit struggling over here. So currently I have a model Client and a model Bank. One of the fields in the Bank model is amount. I reasoned as follows: a client can have an account at multiple banks, and a bank can have multiple clients. Hence -> ManyToMany. The problem now is dat I can only specify 1 amount for all accounts a client have... How can I solve this? Create another model? OneToOne? many thanks for the input Best, -
Put dynamic value into form automatically
I have a form that books a users lesson. I use lesson.lesson_instrument and lesson.lesson_datetime_start to display the instrument and date of the lesson. I want my form to use the value of lesson.lesson_instrumentand lesson.lesson_datetime_start in form.booked_instrument and form.booked_date, so that information is saved in a new separate model instance. I was wondering how to get the value from that, into the form text input without typing it. HTML <div class="text-center"> <div class="form-group"> <div class="ins-left"> <p>{{ lesson.lesson_instrument }} {{ form.booked_instrument }}</p> </div> <div class="date-right"> <p>{{ lesson.lesson_datetime_start|date}} {{ form.booked_date }}</p> </div> </div> <br /> <br /> <div class="form-group"> <label>Length</label> {{ form.booked_length }} </div> <br /> <div class="form-group"> <label>Time</label> {{ form.booked_time }} </div> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button">Book Now</button> </div> </div> forms.py class BookedForm(forms.ModelForm): booked_instrument = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'})) booked_length = forms.ChoiceField(choices=length_list, widget=forms.Select(attrs={'class' : 'form-control', 'id' : 'length', 'required' : 'True'})) booked_date = forms.DateField(input_formats=['%Y-%m-%d'], widget=forms.DateInput(attrs={'class': 'form-control'})) booked_time = forms.ChoiceField(widget=forms.Select(attrs={'class' : 'form-control', 'id' : 'time', 'required' : 'True'})) class Meta: model = Booked fields = ('booked_instrument', 'booked_length', 'booked_date', 'booked_time') -
Privacy setting for posts
I am trying to create a privacy component for my application that creates posts. I currently created a posts manager that is supposed to filter posts and display them based on the privacy setting chosen. I'm not sure if I'm going about doing this right. Another issue I am faced with is, the ability to choose the type of privacy I want to use. Since I am using enum, I am not sure how to display them on the templates and use the choice in my views. I am currently selecting the privacy setting from the admin page. This is my posts/models.py My PostManager is not constructed properly to filter for these specification. Specifically the privacy setting for friends. class PostManager(models.Manager): def all(self, *args, **kwargs): query_set = super(PostManager, self).order_by("-timestamp") return query_set def filter_by_public(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=0).order_by("-timestamp") return query_set def filter_by_private(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=1).order_by("-timestamp") return query_set def filter_by_friends(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=2, followee__user1=request.user.id, is_active=True).order_by("-timestamp") return query_set def filter_by_foaf(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=3).order_by("-timestamp") return query_set def filter_by_only_server(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=4).order_by("-timestamp") return query_set def filter_by_only_me(self, *args, **kwargs): query_set = super(PostManager, self).filter(privacy=5, user=user).order_by("-timestamp") return query_set class Post(models.Model): PUBLIC = 0 PRIVATE … -
Web development in Wolfram Language
There is documentation for how to use the Wolfram Language to do things related to web development; see also here. And it seems there would be an advantage to developing software in such a high-level language. Yet I cannot find examples of prominent websites, web apps, or desktop software that was built using the Wolfram Language. So what gives? What hurdles, besides monetary cost, prevent people from doing more development with this language? To be very specific, I'd like to know what development of a website such as Reddit or StackExchange would look like if one tried to use the Wolfram Language vs. Ruby/Rails or Python/Django. -
How to prevent template language from displaying invalid data from an update form?
I have this logic for my user update form: def form_valid(self, form): if not form.has_changed() and form.is_valid(): user = form.save(commit=False) messages.error(self.request, _('Nothing changed.')) return redirect... else: if form.is_valid(): user = form.save(commit=False) user.save() messages.success(self.request, _('Success.')) return redirect... I have also tried with form.save() (no commit=False), but this throws an error. The problem is that this form exists on a page where you can see your username as you fill out the form i.e. {{ self.request.user.username }}, but if you choose a username that somebody else already has, the form throws a unique=True error as it should, but your username momentarily changes to the not unique username, even though the user model has not been saved. How do I prevent this behavior? -
Django No module named 'PIL' only in production
I get an error when trying to upload an image using the Django admin ModuleNotFoundError at /admin/home/image/16/change/ No module named 'PIL` The strange thing is, this only appears when I run the Django site with apache, when I run the server using sudo python3 manage.py runserver 0.0.0.0:80 it works just fine. Additionally, when I activate the virtual environment I have for Django, I can run import PIL just fine. I can also do this when running the Django shell with sudo python3 manage.py shell. Another note, I can't run the wsgi.py file in my Django project/ I'm not sure what will help, but here are some files I think may be important. apache conf file: <VirtualHost *:80> Servername www.ubspy.org Servername ubspy.org DocumentRoot /home/ubspy/django/ WSGIScriptAlias / /home/ubspy/django/ubspy/wsgi.py ErrorLog /home/ubspy/django/error.log Alias /static/ /home/ubspy/django/static/ Alias /media/ /home/ubspy/django/media/ Alias /php/ /var/www/html/ <Directory /home/ubspy/django/static/> Require all granted </Directory> <Directory /home/ubspy/django/media/> Require all granted </Directory> WSGIDaemonProcess ubspy.org python-home=/home/ubspy/django/env python-path=/home/ubspy/django/ WSGIProcessGroup ubspy.org <Directory /home/ubspy/django/ubspy/> <Files wsgi.py> Require all granted </Files> </Directory> <IfModule mod_expires.c> ExpiresActive on ExpiresDefault "access plus 1 month" </IfModule> </VirtualHost> settings.py: """ Django settings for ubspy project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full … -
Django - return all associated rows for distinct results set with postgres backend
I have data in the following form: product_id | collection_name | type | manufacturer | description | image_url ---------------------------------------------------------------------------------- 1 | beach | bed | company a | nice bed | 1.jpg 2 | beach | king bed | company a | nice bed | 1.jpg 3 | beach | nightstand | company a | nice ns | 1.jpg 4 | grass | chest | company a | nice chest | 2.jpg 5 | apple | chest | company a | nice chest | 3.jpg 6 | fiver | chest | company b | good chest | 4.jpg What I need to do, is select all images and only return each image once (distinct), but then return non-distinct row for each image. My goal is to ensure I display each image only once in my template, but show all records associated with each image. In the example above, 1.jpg is one image that would show both beds and the nightstand in one image. I would like to show such an image and list associated products with it. I have seen similar questions, although asking at the SQL/db level and not asking for a pure django solution. The query I have … -
Django: The page isn't redirecting properly
I want to do a check in the database whether an user has filled in the Payment_receipt model form while signing up, the next time the user logs in. If the user has not filled in the form at first, he will be redirected to the page named plan_select. I tried this view. But it's giving me the error: "The page isn't redirecting properly". def homeview(request): if request.user.is_authenticated: if Payment_receipt.objects.filter(user = request.user).exists(): return redirect('home') else: return redirect('plan_select') else: return render(request, 'services/home.html') What could have gone wrong? I want to do the same check with other models in this view under the condition if request.user.is_authenticated:. How do i redirect based on the conditions properly? -
Django: send data to modal with Ajax has strange behaviour
I´m sending data to a html modal with AJAX, but I´m getting a strange behaviour. I first started testing with a variable called name_1 and it works fine showing the title field in my django model. If I change that variable name everywhere to name_2 (or whatever) it doesn´t work anymore. What I´m doing wrong? The function call in the template <form name="form" action="#" id="form_tarea_{{tarea.id}}" method="POST"> {% csrf_token %} <input name="id" id="tarea_id_submit" type="text" value="{{tarea.id}}" hidden="true"/> <a style="padding-left: 1rem;" href="" id="{{tarea.id}}" class="show_tarea" data-toggle="modal" >{{ tarea.titulo }}</a> </form> The AJAX script <script> $(function(){ $('.show_tarea').on('click', function (e) { e.preventDefault(); let tarea_id = $(this).attr('id'); $.ajax({ url:'/catalog/tareas-detail/', type:'POST', data: $('#form_tarea_'+tarea_id).serialize(), success:function(response){ console.log(response); $('.show_tarea').trigger("reset"); openModal(response); }, error:function(){ console.log('something went wrong here'); }, }); }); }); function openModal(tarea_data){ $('#name_1').text(tarea_data.name_1); $('#modal_tareas').modal('show'); }; </script> The view def TareaDetailView(request): ID = request.POST.get('id') tarea = Tareas.objects.get(pk=ID) # So we send the company instance name_1= tarea.titulo return JsonResponse({'name_1': name_1}) The modal template <div class="modal fade" id="modal_tareas" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-body"> <div class="row"> <div id="name_1" style="font-size: 14px; color: black; margin-bottom: 5px;"></div> <div style="padding-top: 1.5rem;"> <button type="button" class="btn btn-outline-info waves-effect ml-auto" data-dismiss="modal">Cerrar</button> </div> </div> </div> </div> </div> </div> -
How to iterate over Query List of django model
I am trying to read JSON from URL and if record is not present in the django model trying to insert. While iterating over QuerySet even if record is present in the model it is trying to insert into model. Please refer below code: from rest_framework import generics from customer.models import Customers from .serializers import CustomersSerializer import json import urllib.request class CustomerAPIView(generics.ListAPIView): j = urllib.request.urlopen("https://web.njit.edu/~jsd38/json/customer.json") customer_data = json.load(j) queryset1 = Customers.objects.values_list('CustomerId', flat=True) for customer in customer_data: if customer["@Id"] not in queryset1.iterator(): CustomerId = customer["@Id"] Name = customer["Name"] PhoneNumber = customer["PhoneNumber"] EmailAddress = customer["EmailAddress"] StreetLine = customer["Address"]["StreetLine1"] City = customer["Address"]["City"] StateCode = customer["Address"]["StateCode"] PostalCode = customer["Address"]["PostalCode"] cus = Customers() cus.CustomerId = CustomerId cus.Name = Name cus.PhoneNumber = PhoneNumber cus.EmailAddress = EmailAddress cus.StreetLine = StreetLine cus.City = City cus.StateCode = StateCode cus.PostalCode = PostalCode cus.save() queryset = Customers.objects.all() serializer_class = CustomersSerializer -
Many to many field shows as empty list Django
I'm trying to get a list of users connected to the conversations, but the list seems to always be empty, I've looked into previous questions and the docs, and based on them something should show up (even an error would help). But it's just an empty list. My Viewset class MessagingViewSet(viewsets.ModelViewSet): def list(self, request): conversations = models.Conversation.objects.using(db_to_use).prefetch_related('users').filter(checkunread__user_id=request.user.id) conv_ids = list(conversations.values_list('id', flat=True).order_by('id')) comments = models.Comments.objects.filter(conversation_id__in=conv_ids) serialized_conversations = serializers.ConversationSerializer(conversations, many=True).data serialized_comments = serializers.CommentSerializer(comments, many=True).data #parsing the data into a JSON obect for conversation in serialized_conversations: conv_id = conversation['id'] for comment in serialized_comments: if comment['conversation_id'] == conv_id: conversation['comments'].append(comment) return Response(serialized_conversations) My Models (The user one is just a basic id, name) class Conversation(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='conversation_owner') users = models.ManyToManyField(UserProfile, through='CheckUnread') subject = models.CharField(max_length=255) start_date = models.DateField() end_date = models.DateField() class CheckUnread(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) read = models.BooleanField() and my serializer class ConversationSerializer(serializers.ModelSerializer): users = UserProfileSerializer(read_only=True, many=True) comments = CommentSerializer(many=True) class Meta: model = models.Conversation fields = ('id', 'owner_id', 'users', 'subject', 'start_date', 'end_date', 'comparison_start_date', 'comparison_end_date', 'comments') I get a working response for conversations but the users field just gives an empty list []