Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
user sending an input form to another user in the platform - django
in my app I want that if userA selected a userB he can send him an input form that contain fields. those users have a class profile. I don't know what should I do in my views. do someone have any idea or already worked on this before. I really need your help in this -
Postgres: sanitize string before searchin for it
I have a website which uses Postgres as a database. I now want users to be able to search the database for strings and am using pg_trgm for that. I can imagine that it is very dangerous to just search the database for the plain user input, as it could be malicious. So my question is: what security measures do I have to take in order to search for a string in Postgres, which could potentially contain malicious code? Are there for example certain characters which should be escaped? Thanks in advance, Kingrimursel -
Decoupling auth/auth from Django applications
I author a couple of Django applications that I deploy behind an auth/auth system. Currently, my apps' class-based views are hard-coded with my particular auth requirements, by using DRF's authentication_classes and permission_classes and Django's permission_required decorator (and friends). The problem I have is that I can't really figure out any way to configure these on a project level. For example, while testing, I don't want to have to deal with my auth system--creating test users, logging in, etc. I just want to test my app. But even though I have a separate Django environment for production and development, there's no elegant way for me to, in my dev environment's settings.py, say (for example) MYAPP_AUTH_MODEL=None and in my prod environment, say something like MYAPP_AUTH_MODEL=permission_required('myperm_create'). As another example, how could I give consumers of my app complete control over how they secure their deployment, including allowing them to choose not to secure it at all? How does one write a Django app that can be secured with auth/auth, without writing anything into the app that places restrictions on how it's secured in any given deployment? -
Migrating Django from 2.2 to 3.2
I am migrating my application in Django 2.2 to version 3.2 and when passing the tests it gives me the following error that seems native to the framework. The application works perfectly, but the tests stopped working. python manage.py test --keepdb Using existing test database for alias 'default'... Traceback (most recent call last): File "/home/proyecto/src/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/home/proyecto/env/lib/python3.6/site-packages/django/test/runner.py", line 725, in run_tests old_config = self.setup_databases(aliases=databases) File "/home/proyecto/env/lib/python3.6/site-packages/django/test/runner.py", line 645, in setup_databases debug_sql=self.debug_sql, parallel=self.parallel, **kwargs File "/home/proyecto/env/lib/python3.6/site-packages/django/test/utils.py", line 183, in setup_databases serialize=connection.settings_dict['TEST'].get('SERIALIZE', True), File "/home/proyecto/env/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 79, in create_test_db run_syncdb=True, File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/proyecto/env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 246, in handle fake_initial=fake_initial, File "/home/proyecto/env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/proyecto/env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, … -
How can I insert a checkbox in my django Sign Up form?
This is my forms.py file class SignUpForm(UserCreationForm): email = forms.EmailField(widget= forms.EmailInput(attrs={'class':'form-control'})) first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class':'form-control'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' I want to add a boolean checkbox on my signup form, but not quite getting there. Any help would be appreciated. -
django.core.exceptions.FieldError: Unsupported lookup 'exact' when run in apache2
I know, similar problems have been posted and discussed here and in other forums. Nonetheless, I was not able to get around the issue. The follwing code snipped from File "/data/django/jukeoroni/player/jukeoroni/juke_radio.py" works just fine in python manage.py runserver @property def last_played(self): try: return Channel.objects.get(last_played=True) except Channel.DoesNotExist: LOG.info('no last_played channel, returning None.') return None [09-12-2021 15:03:49] [INFO] [Dummy-10|2989487200] [player.jukeoroni.jukeoroni]: Button press detected on pin: 16 button: 0X00 (2), label: Play [09-12-2021 15:03:49] [INFO] [Dummy-10|2989487200] [player.jukeoroni.jukeoroni]: Media inserted: deathmetal (type <class 'player.models.Channel'>) However, the same code results in the titles error when run within apache2: [09-12-2021 15:00:32] [INFO] [Dummy-10|2843735072] [player.jukeoroni.jukeoroni]: Button press detected on pin: 16 button: 0X00 (2), label: Play Traceback (most recent call last): File "/data/django/jukeoroni/player/jukeoroni/jukeoroni.py", line 813, in _handle_button if self.radio.last_played is None: File "/data/django/jukeoroni/player/jukeoroni/juke_radio.py", line 126, in last_played return Channel.objects.get(last_played=True) File "/data/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 424, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 941, in filter return self._filter_or_exclude(False, args, kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/data/venv/lib/python3.7/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/data/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1393, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/data/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1415, in _add_q … -
order_by("-date") not working correctly with paginator
SO i have more than 500 records and want organize them by date, it was pretty simple and it worked but when i used paginator to add pagination it all got messed up, there is no sense in this ordering right now can anyone help me understand what's happening and what i need to do in order to get my order_by() working. Here is a my view: if request.method == "GET": if request.session["store_year"] == "" and request.session["store_month"] == "": request.session["store_year"] = "" request.session["store_month"] = "" timelineData = Timeline_english.objects.all().order_by("-date") timeline_list = [] timeline_date_list = set() for val in timelineData: obj = { "id": val.id, "image": val.image, "text": val.text, "url": val.url.replace(" ", "-").lower(), "date": val.date } timeline_list.append(obj) timeline_date_list.add(str(val.date)[:4]) page = request.GET.get('page', 1) print("page", page) paginator = Paginator(timeline_list, 9) try: timeline_list = paginator.page(page) except PageNotAnInteger: timeline_list = paginator.page(1) except EmptyPage: timeline_list = paginator.page(paginator.num_pages) print(timeline_list) try: page_count = math.ceil(timelineData.count()/9) page_limit = 3 page_count_arr = [] if page_count > page_limit: new_pagecount = int(page)+page_limit else: new_pagecount = page_count last_page_number = { "mode": "yes" if page_count == int(page) else "no", "index": page_count } if page_count > int(page): for i in range(int(page), new_pagecount+1): page_count_arr.append({ "mode": "yes" if i == int(page) else "no", "index": i }) data.update({"quotes_list_pages": page_count_arr}) else: … -
Django Leaflet Ajax
How to list and map located data: At one point In an interval In a rectangle In a circle of rayoun R thank you so much -
Translating django tables2 template column header
Hi i'm working with django-tables2 and I have a table where I need to translate the headers of each column. class ModelTable(tables.Table): name = tables.columns.Column() edit = tables.TemplateColumn('<a href='{% url "edit_my_model_instance" record.id %}'>Edit</a>', verbose_name=u'Edit', ) delete = tables.TemplateColumn('<a href='{% url "del_my_model_instance" record.id %}'>Delete</a>', verbose_name=u'Delete', ) class Meta: model = models.Model The above code without translations work fine, but when I add the gettext for translate like this : delete = tables.TemplateColumn('<a href='{% url "del_my_model_instance" record.id %}'>Delete</a>', verbose_name=_(u'Delete'), ) Where I added gettext as _ : verbose_name=_(u'Delete') I receive the following error TypeError: 'TemplateColumn' object is not callable The thing is if I use tables.Column it works fine with translation, so the problem is only when I user TemplateColumn. If you can guide me through this I'd appreciate it, thanks. -
Django Rest Framework Swagger API expand_all fields not working
I have a REST API described with Swagger. When I try to expand some fields, I get a valid JSON response (Response 200). However, when I try to expand all fields, I get no response (Response 500) I compared the logs when I expanded some fields vs when I expanded all fields. Below are some excerpts of logs from generics.py In generics.py,in function paginate_queryset, self.paginator= <rest_framework.pagination.PageNumberPagination object at 0x7fa32f2d01d0> In generics.py,in function paginate_queryset, self.paginator is NOT None In generics.py,in function paginator, self.pagination_class = <class 'rest_framework.pagination.PageNumberPagination'> . self._paginator= <rest_framework.pagination.PageNumberPagination object at 0x7fa32f2d01d0> In generics.py,in function paginator, self._paginator.django_paginator_class= <class 'django.core.paginator.Paginator'> . page_size = 10 . page_query_param = page . page_size_query_param= None . max_page_size= None . template = rest_framework/pagination/numbers.html, *************BELOW LINES ARE DISPLAYED ONLY WHEN I EXPAND SOME FIELDS & ARE NOT DISPLAYED WHEN I EXPAND ALL***************** In generics.py,in function paginate_queryset, self.request= <rest_framework.request.Request object at 0x7fa32f2d0b70> .return = [<Exon: Exon object (1)>, <Exon: Exon object (2)>, <Exon: Exon object (3)>, <Exon: Exon object (4)>, <Exon: Exon object (5)>, <Exon: Exon object (7)>, <Exon: Exon object (8)>, <Exon: Exon object (9)>, <Exon: Exon object (10)>, <Exon: Exon object (11)>], What could be the issue that prevents the paginate_queryset from being called, when I expand … -
getting null value when posting data to django using ajax
Am trynig to post data from an input to my django view to do some processing on this data ,which is a text, and am using AJAX but I get the input NULL in my view $(document).on('submit', '#post-form',function(e){ $.ajax({ type:'POST', url:'{% url "index" %}', data:{ inp:$('#qst').val() csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, dataType: 'json', success:function(json){ document.getElementById("post-form").reset(); $(".messages_area").append('<div class="messages__item messages__item--visitor">'+json.inp+'</div>') $(".messages_area").append('<div class="messages__item messages__item--operator">'+json.answer+'</div>') }, error : function(xhr,errmsg,err) { console.log(xhr.status + ":" + xhr.responseText); // provide a bit more info about the error to the console } }); }); And this is my view def chat(request): context={} inp="" response_data = {} if request.method == 'POST' and request.is_ajax: inp = request.POST.get('inp') answer=respond(inp) response_data['answer'] = answer response_data['inp'] = inp return JsonResponse(response_data) return render(request, 'templates/rhchatbot/index.html',context ) But when I print the inp value I get : {'inp':null} -
Why doesn't my 'home' page recognize 'object_list' in views?The specific template of CBV only does
I have a navbar template and I want to make it dynamic. When I want to do this in the template, nothing happens: {% for platform in object_list %} <li><a href="#">{{platform.title}}</a></li> {% endfor %} This code only works in the platform.html file but I want to show the navbar in all of my html files It is in platform.html(platform URL) and it should be like this And this one is in home url but it is an empty subnav this is my models from django.db import models # Create your models here. class Platform(models.Model): PLATFORM_CHOICES = ( ('PC', 'PC'), ('PS', 'playstation'), ('XBOX', 'Xbox'), ('NS', 'nintendo switch'), ) title = models.CharField(max_length=4, choices=PLATFORM_CHOICES, verbose_name= "platform") slug = models.SlugField(max_length=100, unique=True) class Meta: verbose_name = "platform" verbose_name_plural = "platforms" def __str__(self): return self.title class Game(models.Model): title = models.CharField(max_length=50) description = models.TextField() slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to="images") platform = models.ManyToManyField(Platform) class Meta: verbose_name = "game" verbose_name_plural = "games" def __str__(self): return self.title this is my views: from .models import Game, Platform from django.shortcuts import get_object_or_404, render from django.views.generic import ListView, DetailView, TemplateView # Create your views here. def home(request): return render(request, 'blog/home.html') class GameList(ListView): template_name = "blog/game.html" model = Game games = Game.objects.all() … -
Cookie is not setting from django app deployed on Heroku
I am building an app using React and Django. The backend is deployed on Heroku. When a user logs in, a JWT token is generated and a cookie is set on the client-side with the value of JWT token. When I run the django server on local machine, it works fine and the cookie is getting set. But when I use the server on Heroku, the cookie is not setting in the browser. What should be done to make the cookie work? Login View in views.py @api_view(['GET', 'POST']) def login(req): email = req.data.get('email') password = req.data.get('password') print(email, password) user = User.objects.filter(email=email).first() if user is None: #raise AuthenticationFailed('User not found') return Response({'message': 'Not Found'}) if not user.check_password(password): #raise AuthenticationFailed('Incorrect password') return Response({'message': 'Incorrect'}) payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') res = Response() res.set_cookie(key='jwt', value=token, httponly=True) res.data = { 'message': 'Logged In' } return res Settings.py 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.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' … -
Django KeyError: 'parent'
What i am trying to do is i try to check if the user has parent or not,then to authorize the serialization operation.But i get an error that says: value = self.validate(value) File "/root/server/accounts/serializers.py", line 715, in validate if (attrs['parent'] == None) and (attrs['id'] == self.context['request'].user.pk): KeyError: 'parent' Models.py class MyModel(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name =models.CharField(max_length=40,unique=True,default='name') parent = models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) Serializers.py class ModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('id','name','password','parent') def validate(self, attrs): attrs = super().validate(attrs) if (attrs['parent'] == None) and (attrs['id'] == self.context['request'].user.pk): return attrs elif (attrs['parent'].id != self.context['request'].user.pk) and (attrs['parent'] != None): raise ValidationError('Unauthorized Request') return attrs Does anybody know the issue of the problem? -
Results from dynamic search bar not showing up on my page?
So, I'm making a dynamic search bar and everything works as it's supposed to (getting the results from Django, converting it to JSON, JS receives the JSON, etc.), except the conversion of the results to HTML on the page. I'm not sure what I'm supposed to do to have the results actually show on the web page and not just on the console anymore? Code: <form class="d-flex" method="POST"> {% csrf_token %} <input class="form-control me-2" type="search" id='search' placeholder="Search for books via their titles" aria-label="Search" > <div id="results" style="display: none;"> </div> </form> document.addEventListener("DOMContentLoaded", () => { // TODO: Implement Search Mechanic const search = document.querySelector("#search"); if (search !== null) { search.onkeyup = () => { console.log(search.value); get_results(search.value); }; } }); function get_results(query) { //TODO Create API to get results if (query === null) { return [] } if (query !== "") { fetch(`/results/${query}`) .then(response => response.json()) .then(result => { console.log(result); const display_div = document.querySelector("#results"); display_div.style.display = "block"; result.forEach(query => { console.log(query); const par = document.createElement("par"); const a = document.createElement("a"); a.classList.add = "links"; a.textContent = query.name; a.href = "#"; par.appendChild(a); display_div.appendChild(par); }); }); } } @login_required def results(request, query): if request.method == "GET": if query is not None: results = Search(query).get_results() print(results) JsonResponse({"message": … -
How to resend verification email django restframework?
I can send a verification email upon registering the user so that the account can be activated. But how would one go about resending another verification email on an API? Here, I am making an activation link with a token in it and when the user opens the link it takes the token and verifies the user. But how would resending the verification email work? class RegisterUser(APIView): serialzer_class = RegisterSerialzer def post(self, request): user = request.data serializer = self.serialzer_class(data = user) serializer.is_valid(raise_exception = True) serializer.save() user_data = serializer.data # user = User.objects.get(username=serializer.data['username']) # print(user.id) # token = Token.objects.create(user=user) user = User.objects.get(email = user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+ user.username + 'user the link below to verify your email \n' + absurl data = {'email_body':email_body,'to_email':user.email, 'email_subject':'Verify your email'} Util.send_email(data) class VerifyEmail(APIView): def get(self, request): token = request.GET.get('token') try: payload = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=payload['user_id']) user.is_verified = True # user.is_authenticated = True user.is_active = True # if not user.is_verified: user.save() return Response({'email':'successfuly activated'}, status=status.HTTP_200_OK) # except jwt.ExpiredSignatureError as identifier: except jwt.ExpiredSignatureError: return Response({'error':'Activation Expired expired'}, status=status.HTTP_400_BAD_REQUEST) # except jwt.exceptions.DecodeError as identifier: except jwt.exceptions.DecodeError: return Response({'error':'invalid token'}, status=status.HTTP_400_BAD_REQUEST) -
I can't figure out what to write in HTML?
Help write html code to display video posts on the site I am new to Django I don't know what to write in HTML to display the post I added in django-admin Tried adding a form and this way to add the post didn't work I would be glad to get any help -
how to convert group by(values) to json - django
i'm trying to convert my grouped by (values in django) data into JsonResponse but it raise this error : AttributeError: 'dict' object has no attribute 'f_type' this is my function of loadding json data def load_cate(request): lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total') data = [] for i in lists.values(): item = { 'wc_type':i.f_type, 'room_type':i.room_type, 'beds':i.beds, 'balcon':i.balcon, 'total':i.total } data.append(item) return JsonResponse({'success':True,'data':data}) is there something i did wrong ? or its different for group by values ?! thanks in advance .. -
How to channel data thru Django's URL from third party URL without using redirecting?
What kind of existing options there is to make the client's GET "myserver://api/download/12345.jpg" to download from some_cloudfront_server://files/12345.jpg without redirecting the client to that CloudFront-path? Ie. I want the client see only myserver://api/download/12345.jpg all the time. It should be some kind channeling solution, as downloading a full file first to Django-server and then sending it to the client is not applicable (takes so much time that the client will see timeout before a response to its query comes). Any existing libraries for this? If I have to create one myself, I welcome even just tips where to start from as Django's communication layer is not too familiar to me. Problem here is that we are creating CloudFront signatures with wildcards to certain set of files, in format files/<object_id>*, thus allowing access only to certain object's all files. This works fine as long as file access traffic from clients is low. But if we start creating separate access signatures for hundred different files at same time, CloudFront starts throttling our requests. Solution I came up is to create and store to Django-server one generic allow-all signature for files/*, which is used only by Django-server and never given to any client, and then … -
How user can send a from to another user in my platform - django
I m working on a web app with django, it's actually like a platform that contains a lot of registered users. One user have to send like a form to another user through the app. And that user when he gonna open a page he can see a table that contains all forms sent by users. -
Display data from two different models in one html table using Django
I have two models namely StudentInfo & StudentAdmission. student_id is foreign key in StudentAdmission model. I want to display the values of both models together in one html table. How could I do that. models.py file: from django.db import models from datetime import datetime # Create your models here. class StudentInfo(models.Model): gender_choice = ( ("male", "Male"), ("Female", "Female"), ) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) gender = models.CharField(choices=gender_choice, max_length=10) dob = models.DateField(default=datetime.now, blank=True) address = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone = models.CharField(max_length=100) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') def __str__(self): return self.firstname class StudentAdmission(models.Model): class_choice = ( ("one", "one"), ("two", "two"), ("three", "three"), ) section_choice = ( ("A", "A"), ("B", "B"), ("C", "C"), ) transport_choice1 = ( ("abc", "abc"), ("bcd", "bcd"), ("def", "def"), ) transport_choice2 = ( ("ab", "ab"), ("bc", "bc"), ("de", "de"), ) admission_no = models.CharField(max_length=100) admission_date = models.DateField(default=datetime.now, blank=True) roll_no = models.CharField(max_length=100) email = models.EmailField(max_length=100) username = models.CharField(max_length=100) password = models.CharField(max_length=100) class_name = models.CharField(choices=class_choice, max_length=10) section_name = models.CharField(choices=section_choice, max_length=10) transportation = models.CharField(choices=transport_choice1, max_length=10) transport_vehicle = models.CharField(choices=transport_choice2, max_length=10) student_name = models.ForeignKey(StudentInfo, on_delete=models.CASCADE) def __str__(self): return self.username I want to display related class_name and section_name in following table -
Django's infinite streaming response logs 500 in apache logs
I have a Django+Apache server, and there is a view with infinite streaming response def my_view(request): try: return StreamingHttpResponse(map( lambda x: f"{dumps(x)}\n", data_stream(...) # yields dicts forever every couple of seconds )) except Exception as e: print_exc() return HttpResponse(dumps({ "success": False, "reason": ERROR_WITH_CLASSNAME.format(e.__class__.__name__) }), status=500, content_type="application/json") When client closes the connection to the server, there is no cleanup to be done. data_stream will yield one more message which won't get delivered. No harm done if that message is yielded and not received as there are no side-effects. Overhead from processing that extra message is negligible on our end. However, after that last message fails to deliver, apache logs 500 response code (100% of requests). It's not getting caught by except block, because print_exc doesn't get called (no entries in error log), so I'm guessing this is apache failing to deliver the response from django and switching to 500 itself. These 500 errors are triggering false positive alerts in our monitoring system and it's difficult to differentiate an error due to connection exit vs an error in the data_stream logic. Can I override this behavior to log a different status code in the case of a client disconnect? -
How to solve this django query problem without using the for loop?
I have a query containing a list of submissions by users. Models are below, but here's the gist: Each submission belongs to one problem that user tried to solve. However, user can make as many submission as they want for a single problem. There are several problems. submissions are ordered by time of creation (descending) I need to get a list of all the final submissions by users. final submission is the last submission of user for a specific problem. Naturally, if user solves several problems then they would have as many final submissions. How can I get this? Here is what I got so far but I dont know how to go on: all_users = list_users(contest_id) #query of all users in contest problems = list_problems(contest_id) #query of all problems in contest final_submissions = Submission.objects.none() for user in all_users: for problem in problems: query = list_problem_user_submissions(contest_id, user.id, problem.id)[:1] if query.exists(): final_submissions.union(query) This doesnt work, but I also cant think of anything without a for loop. Is there a way to remove that loop and do it straight in query? Here are the models: **User**: default django user model Contest: name = models.CharField(max_length=50) holder = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField() finish_time … -
How to get the user associated to another model DRF. ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing
I want to check that the card number is exists and then get the associated user to that card number. A user can have multiple card numbers. How do I filter to get the user from the card number entered? Models: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name="Email Field", max_length=60, unique=True) dateJoined = 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) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) # Parameters that we want to know about the user first_name = models.CharField(verbose_name="First Name", max_length=100) last_name = models.CharField(verbose_name="Lasst Name", max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } def has_perm(self, perm, obj=None): return self.is_superuser def has_module_pers(self, app_label): return True class cardModel(models.Model): user = models.ForeignKey(CustomUser, related_name='card_numbers',null = True, blank=True, on_delete=models.CASCADE) card_number = models.IntegerField( verbose_name="Card Number", blank=True, null=True, default=None, unique=True) def __int__(self): return self.card_number Serializer: class CheckCard(serializers.Serializer): card_number = serializers.IntegerField(write_only=True) class Meta: fields = ['card_number','user'] read_only_fields = ['user'] Views: class CheckCardAPI(APIView): permission_classes = [AllowAny] serializer_class = CheckCard def post(self,request,*args,**kwargs): serializer = self.serializer_class(data=request.data) card_number = request.data.get('card_number','') if cardModel.objects.filter(card_number=card_number).exists(): user = User.objects.filter(card_numbers=card_number) tokens, created = Token.objects.get_or_create(user=user) return Response({'token':tokens.key},status=status.HTTP_200_OK) else: … -
how to install python packages locally inside virtual environment
I am trying to install packages from my requirements.txt file but I am getting this error, it's interesting because I don't have any project dependency as such and I have already ran pip install -r requirements.txt error I am getting File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_sass' I want to install these dependencies such that they should be local only to the project I am working on, any idea how to achieve that ?