Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Different images of two users are showing in one story
I am building a Social Media app. AND i stuck on a Problem. What i am trying to do :- I have build a story feature ( users can make their story like instagram ) everything is working fine BUT When two different users post images in stories then images are showing in single story BUT i am trying to show if two users post two images in stories then show in different stories.- As you can see in first picture that first story is by user_1 and another is by user_2, They are showing in same story but i want them to show in different stories. stories.html <script> var currentSkin = getCurrentSkin(); var stories = new Zuck('stories', { backNative: true, previousTap: true, skin: currentSkin['name'], autoFullScreen: currentSkin['params']['autoFullScreen'], avatars: currentSkin['params']['avatars'], paginationArrows: currentSkin['params']['paginationArrows'], list: currentSkin['params']['list'], cubeEffect: currentSkin['params']['cubeEffect'], localStorage: true, stories: [ // {% for story in stories %} Zuck.buildTimelineItem( 'ramon', '{{ user.profile.file.url }}', '{{ story.user }}', 'https://ramon.codes', timestamp(), [ [ 'ramon-1', 'photo', 3, // '{% for img in story.images.all %}' '{{ img.img.url }}', '{{ img.img.url }}', // '{% endfor %}' '', false, false, timestamp(), ], ] ), // {% endfor %} ], }); </script> </body> </html> models.py class ImgModel(models.Model): img = models.ImageField(upload_to='status_images',null=True) … -
Filtered left outer join in Django that gives access to related Model, not its fields via values()
I am trying to build a list of products for further use in view template. This list is based on filtered Product model that are referred by ForeignKeys in ProductInfo and Image models. Final QuerySet should include all Products that are fall under given criteria and one or zero (depending on additional filters) objects from ProductInfo and Image. If I use annotate() and FilteredRelation() like this: ll = Product.objects.filter(Category=category) \ .annotate(pi=FilteredRelation('productinfo', condition=Q(productinfo__Language=language.id))) \ .annotate(im=FilteredRelation('image', condition=Q(image__IsPrimary=True))) then I need to use values() to access data from jointed Models, and some of custom template tags that I use (for example django-imagekit) will fail because they expect an instance, not just field. I don't expect that the products list will be more than 100 items, and I am thinking that it will be easier to retrieve 3 correctly filtered sets (Product, ProductInfo, Image) and try to join them in code. However I cannot pass it correctly to template engine via context. -
how to unit test custom product models with Foregienkey in unittest in django with pytest
I am trying to unit test a specific model which has a foregienkey with pytest , but after lot of effort I am still facing error and I am new to unit test . error : @pytest.mark.django_db def test_create_pg(client): user=PPuseers.objects.create(Uid='6fa459ea-ee8a-3ca4-894e-db77e160355e') make_pg=PG() > assert PG.objects.count==0 E assert <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x04E8D220>> == 0 E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x04E8D220>> = <django.db.models.manager.Manager object at 0x04E8D220>.count E + where <django.db.models.manager.Manager object at 0x04E8D220> = PG.objects PPpgOwner\test\test_views.py:41: AssertionError My MODELS.PY class PG(models.Model): pg_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) pg_Owner = models.ForeignKey(PPuseers, on_delete=models.CASCADE) pg_name = models.CharField(max_length=255,default='Null') location = models.CharField(max_length=50,default='Null') describtion = models.CharField(max_length=10000, default='Null') pg_main_price = models.IntegerField(default=0) pg_discount_price = models.IntegerField(default=0,blank=True,null=True) ...... ....... this model is liked with a PPusers model PPusers MODEL class PPuseers(AbstractBaseUser, PermissionsMixin): Uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email", max_length=554, unique=True) username = models.CharField(max_length=500, unique=False) date_joined = models.DateTimeField(verbose_name="Date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) ...... ...... ...... MY Pytest : from django import urls from django.contrib.auth import get_user_model from django.http import response from django.urls.base import reverse from PPCustomer.models import PPuseers from PPpgOwner.models import PG @pytest.mark.django_db def test_create_ppuser(client,ppuser_data): user=PPuseers.objects.create(Uid='6fa459ea-ee8a-3ca4-894e-db77e160355e') assert PPuseers.objects.count()==1 @pytest.mark.django_db def test_create_pg(client): user=PPuseers.objects.create(Uid='6fa459ea-ee8a-3ca4-894e-db77e160355e') make_pg=PG() assert PG.objects.count==0 pg_tester=PG.objects.create( pg_id='6fa459ea-ee8a-3ca4-894e-db77e160355e', pg_Owner … -
Does behave-django do migrations before running the tests?
I am trying to do a behavior testing on my API, but it seems like it does not run all my migrations. I can't seem to find something about this in their documentation. -
Saving Longitude and Latitude to a user profile in Django
I was looking for a way to use HTML5 (and possibly JS) to save visitor/user Longitudnal & Latitudnal data to a database. I do not wish to use packages out there as they seem a bit outdated and may break my code in future considerting their own reliance on other APIs. I know there is a way around using AJAX, but I clearly dont know and understand it well enough to implement it. My ask of the learned Lords is - 1. Get Loc data 2. Send it to Python in dict or json or string format from where it can be further processed and saved. Why you may ask - Good question. I would use it for displaying weather on the homepage and local twitter trends on a 'logged-in' page. Any assistance would be appreciated. Cheers! -
adding choices dynamically in django model based on 2-3 other models
I have a model which has an intake field.. class University(models.Model): name= models.CharField(max_length=50) .... .... def __str__(self): return str(self.name) class Course(models.Model): name= models.CharField(max_length=50) university= models.ForeignKey(University, on_delete= models.DO_NOTHING) .... .... def __str__(self): return str(self.name) class CourseDeadline(models.Model): intake= models.CharField(max_length=50) course= models.ForeignKey(Course, on_delete= models.DO_NOTHING) .... .... def __str__(self): return str(self.intake) class Coupon(models.Model): code= models.CharField(max_length=20) university= models.ForeignKey(University, on_delete= models.DO_NOTHING) intake= models.ForeignKey(CourseDeadline,on_delete= models.DO_NOTHING) .... .... def __str__(self): return str(self.code) I would like to show intakes dynamically as a choice field based on selected university.something like u= Universitiy.objects.get(id=university) c= Course.objects.filter(university=u).order_by('id').first() cd= CourseDeadline.objects.filter(course=c).all() intake= models.CharField(max_length=20, choices=cd) Is it possible through Models or Forms and this model is for django admin. -
Disable logging exceptions in Django (logging.raiseException = True)
Is there any equivalent to : import logging logging.raiseException = False in Django's log configuration ? -
Django : Not able to convert CSV file to HTML table using AJAX
i have a code which should display the contents of CSV file using AJAX , i did it in Django folder structure , so currently when i use Django for that purpose it shows error "Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/pandas.csv" But when i do the same without Django it works fine . So here is my code . $(document).ready(function() { $.ajax({ url: "pandas.csv", dataType: "text", success: function(data) { var employee_data = data.split(/\r?\n|\r/); var table_data = '<table class="table table-bordered table-striped">'; for (var count = 0; count < employee_data.length; count++) { var cell_data = employee_data[count].split(","); table_data += '<tr>'; for (var cell_count = 0; cell_count < cell_data.length; cell_count++) { if (count === 0) { table_data += '<th>' + cell_data[cell_count] + '</th>'; } else { table_data += '<td>' + cell_data[cell_count] + '</td>'; } } table_data += '</tr>'; } table_data += '</table>'; $('#employee_table').html(table_data); } }); }); {{ %load static%}} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="table-responsive"> <h1 align="center">CSV File to HTML Table Using AJAX jQuery</h1> <br /> <br /> <div id="employee_table"> </div> </div> </div> </body> </html> So this pandas.csv is kept inside Stat-->Static-->Pandas.csv and html template in Stat-->Website-->templates-->template.html So … -
How can use the exclude query in django
I just want to show that items which are in order table. I am using exclude query for that but when i use it it show nothing OrderProduct and Order are tables. view.py def get(self, request, *args, **kwargs): allOrder = OrderProduct.objects.all() categories = Category.objects.all() categoryId = self.request.GET.get('SelectCategory') product = Product.objects.filter(category_id=categoryId) orders = Order.objects.all() checkOrder = Order.objects.exclude( orderProduct__order__in=orders ) args = {'categories': categories, 'product': product, 'checkOrder': checkOrder} -
How to migrate a Django web app from local machine to another machine[with no internet; can't use PIP] as deployable app
I have a running Django application in my local system and I want to transfer and run the same to another machine in the same network. But, the destination machine cannot use PIP cmd to install dependencies as it does not have internet connectivity. Any ideas to transfer the project are appreciated. -
Uploading crop image and form using cropperjs in Django
I am using https://github.com/fengyuanchen/cropper/blob/master/README.md as the cropper function. However, I want to submit field objects (in this case the title) and the cropped image. But I got an error on the admin. And of course, I have done the makemigrations and migrate before running the server Error Picture admin.py from django.contrib import admin from .models import Image # Register your models here. class ImageAdmin(admin.ModelAdmin): pass admin.site.register(Image, ImageAdmin) models.py from django.db import models # Create your models here. class Image(models.Model): title = models.CharField(max_length=10) image = models.ImageField(upload_to='images') def __str__(self): return str(self.pk) forms.py from django import forms from .models import Image class ImageForm(forms.Form): image = forms.ImageField() title = forms.CharField( max_length=10, widget=forms.TextInput( attrs={ "class": "form-control", "placeholder": "Title", }, ), required=True ) views.py from django.shortcuts import render, redirect from .models import Image from .forms import ImageForm from django.http import JsonResponse from django.http import HttpResponseRedirect def main_view(request): form = ImageForm() if request.method == "POST": form = ImageForm(request.POST, request.FILES) if form.is_valid(): addimage = Image( title=form.cleaned_data['title'], image = form.cleaned_data['image'], ) addimage.save() else: form = ImageForm() context = {'form': form} return render(request, 'photo_list.html', context) photo_list.html {% extends "base.html" %} {% block javascript %} <script> console.log("Hello"); const imageBox = document.getElementById("image-box"); const confirmButton = document.getElementById("confirm-button") const input = document.getElementById("id_image"); const csrf … -
Username is not showing but user id is showing in html template in Django
Below is my Model : class Problem_Solved(models.Model): user_ref = models.ForeignKey(User, on_delete=models.CASCADE) contest_ref = models.ForeignKey(Contest, on_delete=models.CASCADE) problem_ref = models.ForeignKey(Problem, on_delete=models.CASCADE) points_get = models.IntegerField(default=0) time_submitted = models.DateTimeField('date published') class Meta: unique_together = (("user_ref", "problem_ref")) def __str__(self): return self.user_ref.username + " solved " + self.problem_ref.problem_name + " and got " + str(self.points_get) + " marks " Below is my view function : def pointtable(request, contest_id): context = {} contest_obj=Contest.objects.get(pk=contest_id) points_list = Problem_Solved.objects.filter(contest_ref = contest_obj).values('user_ref').annotate(user_sum = Sum('points_get')).order_by('-user_sum') print(points_list) context['points_list'] = points_list return render(request,'leaderboard.html', context) Now below is my html code : {% for pt in points_list %} <div class="container-sm w-75 tb-bg-color"> <div class="row mb-3 "> <div class="col-1 themed-grid-col col-border">{{forloop.counter}}</div> <div class="col-6 themed-grid-col col-border">{{pt.user_ref.username}}</div> <div class="col-2 themed-grid-col col-border">{{pt.user_sum}}</div> </div> </div> {% endfor %} Below is output : Username is not showing As clearly seen in image that username is not showing but if I write pt.user_ref in my html code then it will print user_id as shown below : User id is showing Now I want username but not user id what should i do as I am stuck with this from 2 days. Help me if u can. -
Invalid block tag in django
I've done pretty much everything in my knowledge to solve this, but I guess I've gone wrong somewhere as I'm still a beginner, so I'd like someone to kindly help me out with this and also I've added the error message at the bottom, including the code error TemplateSyntaxError at / Invalid block tag on line 9: 'static'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.6 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 9: 'static'. Did you forget to register or load this tag? Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py, line 531, in invalid_block_tag Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Python Path: ['C:\\Users\\Admin\\Desktop\\Django\\ecommerce', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Fri, 09 Apr 2021 00:16:08 +0000 setting STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] css/main.css body { background-color: blue; } store/main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ecommerce</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/main.css' %}" type="text/css"> </head> <body> <h1>Navbar</h1> <hr> <div class="container"> {% block content %} {% endblock content %} </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> </body> </html> store {% extends 'store/main.html' %} {% load static %} … -
addBooks() got an unexpected keyword argument 'name'
I want to take data from user and save it to database by using django. Have tried to solve it. But I am not able to solve this problem and didn't find any working solution on internet. I am getting this error:- My views.py file is:- from django.shortcuts import render, HttpResponse from home.models import addBooks def index(request): return render(request, "index.html") def checkBooks(request): return render(request, "checkBooks.html") def contactUs(request): return render(request, "contactUs.html") def addBooks(request): name = request.POST.get('name', False) email = request.POST.get('email', False) bookName = request.POST.get('bookName', False) authorName = request.POST.get('authorName', False) desc = request.POST.get('desc', False) book = addBooks(name=name, email=email,bookName = bookName, authorName = authorName, desc = desc) book.save() return render(request, "addBooks.html") And my models.py file is:- from django.db import models class addBooks(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) bookName = models.CharField(max_length=122) authorName = models.CharField(max_length = 122) desc = models.TextField() This is addBooks.html(Here I am getting the data from user by using from):- <form method="POST" action = "/addBooks"> {% csrf_token %} <div class = "container"> <h1 class = "text-center"> Add Books </h1> <div class="mb-3"> <label class="form-label">Your Name</label> <input type="text" name = "name" class="form-control"> <div class="form-text"></div> <div class="mb-3"> <label class="form-label">Email Address</label> <input type="email" name = "email" class="form-control"> <div id="emailHelp" class="form-text">We'll never share your email with … -
My django manage.py is not running server
I am connected to internet and everything is fine but as in the picture you can see manage.py is not running server -
How to pass a filter from a dropdown into django-import-export view
I understand on how to pass a filter through views that have the return render(request, 'htmlname.html, {}). I don't know how to do it for this case of exporting data through django-import-export export option. I'd like to pass a filter from a dropdown selection for the data to be downloaded. My view def ExportStudentsView(request): dataset = ExportStudentsResource().export(school = request.user.school,klass = ?????????) response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="All students.xls"' return response My resource class ExportStudentsResource(resources.ModelResource): def export(self, queryset = None, *args, **kwargs):#this method helps capture the current user school queryset = Students.objects.filter(school = kwargs['school'],klass = kwargs['klass']) return super(ExportStudentsResource, self).export(queryset, *args, **kwargs) klass__name = fields.Field(attribute = 'klass__name',column_name='class')#Changes column name from school__name to school stream__name = fields.Field(attribute = 'stream__name',column_name='stream') gender__name = fields.Field(attribute = 'gender__name',column_name='gender') class Meta: model = Students fields = ('adm','name','kcpe','klass__name','stream__name','gender__name','notes') export_id_fields = ('adm',) export_order = ('adm','name','kcpe','klass__name','stream__name','gender__name','notes') -
How to validate a column value in a csv file imported, and give validation error if not present in django
Here I'm trying to get the individual column value from the uploaded file and trying to retrieve a validation for a column not present in the csv checking if the file uploaded is a csv or not if not give a error saying unsupported file format, if a csv then check for the column inside and if any of the column is missing give a validation saying " * " column is not present. here is a part of csv file time,amplitude 0,0.73904 0.02441,1.2372 0.04883,1.0019 0.07324,0.50924 0.09766,-0.603 0.12207,-1.6674 0.14648,-1.5332 0.1709,-0.85486 0.19531,0.3971 0.21973,1.3604 0.24414,1.8384 my validation.py file def validate_file(value): ext = os.path.splitext(value.name)[1] valid_extentions = ['.csv'] if ext.lower() in valid_extentions: return value else: raise ValidationError(u'Unsupported file extention. please upload a .csv file. ') csv = pd.read_csv(value, header=0, nrows=0).columns.tolist() first = csv.index('time') second = csv.index('amplitude') if first != 0: raise ValidationError(u'Missing time value data') elif second != 1: raise ValidationError(u'Missing Amplitude value data') else: return value I've used this but not getting any validation even tho I give a csv without a time column value, please be free to ask for any requirements in the question, thank you in advance. -
Django REST API AttributeError - The serializer field might be named incorrectly and not match any attribute or key on the `list` instance
I am getting the following error message - AttributeError at /analysisapis/constituents Got AttributeError when attempting to get a value for field strings on serializer ConstituentNameLists. The serializer field might be named incorrectly and not match any attribute or key on the list instance. Original exception text was: 'list' object has no attribute 'strings'. My Model is as follows - Note - This is common Model used from Django Website as well. from django.db import models, connection from django.urls import reverse from . import queries as queries # Create your models here. class ISMASymbol(models.Manager): ''' Used to Manage the Symbol ''' def __init__(self): ''' Initialize the Class instance ''' self.symbol = 'NIFTY50' self.tablename = 'NIFTY50' self.exists = 2 self.message = 'NIFTY50 exists.' self.close = 0 self.change = 0 self.returns = 0 self.band = 0 self.upperband = 0 self.lowerband = 0 self.lotsize = {0:0, 1:0, 2:0} self.stepvalue = 0 self.weekly_expiry = True self.weekly_future = False self.isIndex = True self.cashstocks = [] self.derivativestocks = [] self.indexlist = [] self.companyname = 'NIFTY 50' self.has_fno = True SOME ADDITIONAL FUNCTIONS def get_symbol_list(self): ''' Creates a Symbol List for all Cash and Derivatives Used to Create Sitemap ''' symbol_query = queries.symbol_list derivative_query = queries.derivative_list index_query = … -
Migrations File Error When Migrate Django Project
I have a Django project created by Django 1.x few years ago and I want migrate to Django 3. When I test the updated project, it show errors in the migration files that the ForeignKey field missing the "on_delete" argument. Since the "on_delete" argument is optional in Django 1 but mandatory in Django 3. Is there any easy way to fix those errors? Should I need to manually remove all ".py" and ".pyc" files in migrations directory of the app? If I remove the files, will it affect the data in database and the migration processes in future? Thanks, Wilson -
Django template only first loop appears
I wanted to add some custom context to a ListView context like this: class WeatherListView(ListView): """ List view of Weather data """ template_name = "frontend/weather_list.html" model = Weather def get_context_data(self, **kwargs): weather_query = Weather.objects.all() temp_list = list(weather_query.values_list('temperature', flat=True)) humidity_list = list(weather_query.values_list('humidity', flat=True)) temp_list_compared = compare_item_to_previous(temp_list) humidity_list_compared = compare_item_to_previous(humidity_list) data = super().get_context_data(**kwargs) context = { "object_list": zip(data["object_list"], temp_list_compared, humidity_list_compared) } print("context ", context) return context My models.py class Weather(models.Model): temperature = models.FloatField( validators=[MaxValueValidator(28), MinValueValidator(19)] ) humidity = models.FloatField( validators=[MaxValueValidator(65), MinValueValidator(35)] ) time_recorded = models.DateTimeField(auto_now_add=True, blank=True) But when I try to loop through them in the template only the first loop works like this: {% for i in object_list %} {{ i.0.temperature }} {{ i.1 }} {% endfor %} {% for i in object_list %} {{ i.0.humidity }} {{ i.2 }} {% endfor %} expected result is 11.0 12.0 13.0 1 2 3 20.0 22.0 23.0 1 2 3 But what I get is this: 11.0 12.0 13.0 1 2 3 if I switched them put the second loop first it will work and the other one won't. -
How to retrieve string data from many to many form field in django
I'm programming using django, and I encountered the following issue. This might be a little complicated, but I would like to make the following while loop work in a form_valid function in my view. First of all, here is the loop: i = 0 while i <= days: days_added = i current_end = class_start_date + datetime.timedelta(days=days_added) str_current_end = str(current_end) current_end_day = calendar.day_name[datetime.datetime.strptime(str(current_end), '%Y-%m-%d').weekday()] if current_end_day == 'Saturday' or current_end_day == 'Sunday': days = days + 1 elif str_current_end == '2021-04-09' or str_current_end == '2021-04-13': days = days + 1 elif all_weekdays[0] != current_end_day or all_weekdays[1] != current_end_day or all_weekdays[2] != current_end_day or all_weekdays[3] != current_end_day or all_weekdays[4] != current_end_day: days = days + 1 i += 1 There are more to the code in the form_valid function to actually make this while loop work, but my problem is only with the last elif statement that contains all_weekdays. You see, I defined all weekdays as all_weekdays = form.instance.weekday.all() before I started the while loop. Here, weekday is a "many to many field" in the form submitted by the user. Basically, the user could select multiple options from Monday to Friday, which will be stored in the weekday. Also, current_end_day is just … -
how can i pass a list to objects.get in Django
I'm working on a small project using Django / Rest Framework I would like to know if there is any way to pass a list like that mycontact = Contact.objects.get(id=[14,26,44,88]) instead of mycontact = Contact.objects.get(id=14) -
Is there a way to build instant messaging inside an existing WSGI django web application?
So I spent all this time building and going through basic tutorials for geolocation and even payment processing. I'm finally at the step where I want the users to be able to contact each other. Is there a way for me to put ASGI within WSGI? -
Filter Django Queryset to return followers of logged in user only
I am trying work out how filter who follows the logged in user/who is followed by the logged in user using Django Rest Framework. However, all I seem to be returning is ALL users who have been followed by any user or are following any user, it is not specific to the logged in user (the front end view (numbers are the user PK), the API view). I make a GET Request with the pk of the logged in user via an AJAX call but can't seem to filter specifically against that. I'd be grateful for any help! Here is my model: class UserConnections(models.Model): follower = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) followed = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) Here are the relevant serializers: class UserConnectionListSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = ['follower','followed'] class UserConnectionSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = '__all__' depth = 2 Here is the views.py # gets list of who logged in user is following class FollowingViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserConnectionListSerializer queryset = UserConnections.objects.all() def get_serializer_class(self): if self.request.method == 'GET': return serializers.UserConnectionSerializer return self.serializer_class def get_followers(request): if request.method == "GET": user_id = self.request.GET.get('current_user_id', None) return UserConnections.objects.filter(follower__id=user_id) # gets list of followers who follow logged-in user class FollowerViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserConnectionListSerializer … -
OSError: [Errno 9] Bad file descriptor HELP I CANT SOLVE IT
I hope you can help me, I have been working with the raspberry socket, linked together with android studio. I have this code, it is to turn on an LED through the mobile, however, when I run the program it does not throw errors, but when I press the button on the mobile, it throws me the error BUT if I turn off the LED, if I compile again and run the program, I press the button, it throws me the error BUT the LED turns off. I do not know how to solve it, I have read several solutions but it does not work for me import socket, time, RPi.GPIO as GPIO GPIO.setwarnings (False) GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) #UDP_IP = "192.168.100.15" #ip del socket UDP_PORT = 2000 #Puerto del socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('',UDP_PORT)) sock.listen(5) while True: sock, addr = sock.accept() r = sock.recv(256) print("Conexión de %s" % str(addr), " Recibido %s" % r) if r.decode('utf-8') == 'A': GPIO.output(17,True) if r.decode('utf-8') == 'B': GPIO.output(17,False) sock.close() gpio.cleanup() it gives me this error Conexión de ('192.168.100.3', 37580) Recibido b'B' Traceback (most recent call last): File "/home/pi/Desktop/wifi.py", line 16, in <module> sock, addr = sock.accept() File "/usr/lib/python3.7/socket.py", line 212, in accept fd, …