Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unit testing
I am testing my django code, but feel like i am missing something. Here is the view @login_required() def report_incident(request): template_name = "incident/report_incident.html" # request.post logic if request.method == "POST": form = IncidentForm(request.POST) if form.is_valid(): # use while loop to generate random unique id unique = False while not unique: id = generate_random_id(15) if Incident.objects.filter(incident_id=id).first() is None: unique = True # Assign unique id to form instance form.instance.incident_id = id # get incident type incident_type = form.instance.incident_type # If incident type is safeguading issue if str(incident_type.type).lower() == "safeguarding concerns": # if form instance of child is none, it means they used the text input # to write a new child name if not form.instance.child: # get the child name from the post request child_name = request.POST.get('childText') child_name = str(child_name) # create child object with new name unique = False while not unique: id = generate_random_id(15) if Child.objects.filter(child_id=id).first() is None: unique = True child = Child.objects.create(child_id = id, name=child_name) # add new child object to form instance of child form.instance.child = child #save form form.save() messages.success(request, "Incident reported succesfully") return redirect("report-incident") else: form = IncidentForm() context = {"form": form} return render(request, template_name, context) and here is the unit test class TestViews(TestCase): … -
how to print dictionary in django
I'm working on a translator program. I want the result to appear at the bottom of the original page when I presses the 'submit' button. There is no error, but there is no change when I press the 'submit' button. I want to show the contents of the dictionary by using table. This is my codes. 'trans_suc.html', 'views.py' and 'urls.py'. Please let me know how to modify it. trans_sub.html {% extends 'dialect/base.html' %} {% load static %} <!-- template 확장하기 body interface --> {% block content %} <!-- Masthead--> <div class = box> <div class = "container"> <form action="/trans/" method ="post"> {% csrf_token %} <input id = "trans" type ="text" name ="content" placeholder="0/500"> <input class = "btn" id="trans_btn" type ="submit" value ="번역"> </form> <!--<div><p>{{ content }}</p>--> {% for i in context %} <div> <table> <tr> <td>{{ i.siteName }}</td> <td>{{ i.contents }}</td> </tr> </div> {% endfor %} </div> </div> {% endblock content %} views.py class Postview(View): def get(self, request): massage = "hello" return render(request, 'dialect/main_page.html', {'msg': massage} ) @csrf_exempt def success(request): content = request.POST.get('content') context = { 'content': content } dict = pd.read_csv("C:\\Users\\user\\jeju-dialect-translation\\jeju\\dialect\\dict2.csv", sep=",", encoding='cp949') hannanum = Hannanum() okt = Okt() nouns = hannanum.nouns(content) stem = okt.morphs(content, stem = True) tempt=[] … -
Is there a way to filter out specific error messages using Django Logging? eg UncompressableFileError
Is there a way to filter out specific error messages using Django Logging? eg UncompressableFileError Would like to stop these errors being sent to Sentry.io -
Django Channels self.scope['user'] shows blank output
I'm trying to get self.scope['users'] on consumers but the output is always blank, however when I try to get self.scope['users'].id it gives a proper output i.e id of the user. I'm authenticating and logging in user and redirecting to a page if the user is authenticated. views.py if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/create_room/') else: return redirect('register') if request.user.is_authenticated: return redirect('chat') return render(request, 'users/login.html') consumers.py async def receive_json(self, text_data): message = text_data['message'] print(self.scope['user']) # <-- this gives a blank output print(self.scope['user'].id) # <-- this gives proper user id await self.channel_layer.group_send( self.room_name, { 'type': 'send.message', 'room': self.room_name, 'message': message, 'user': self.scope['user'].id }); routing.py websocket_patterns = [ re_path(r'chat/(?P<room_name>\w+)/$', MessageConsumer.as_asgi()) ] -
Comment intégrer Jitsi meet sur son projet Django ? je ne comprend pas la documentation si on veut m'aider. Merci
... const domain = 'meet.jit.si'; const options = { roomName: 'PickAnAppropriateMeetingNameHere', width: 700, height: 700, parentNode: document.querySelector('#meet') }; const api = new JitsiMeetExternalAPI(domain, options); -
Extract name of all foreign keys used in a model in django-pandas dataframe
I have data stored in a Django Model/Table which I am fetching in pandas dataframe via django-pandas (Version: 0.6.6) The model has 3 columns as foreign key viz: state_name, district_name and block_name The model.py is as: #################################################################################### BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) UNIT_CATEGORIES = (('AMFU', 'AMFU'), ('DAMU', 'DAMU')) class GroupDetail(models.Model): """Village level Whatsapp Information options""" unit_type = models.CharField(max_length=16, choices=UNIT_CATEGORIES, default="DAMU") state_name = models.ForeignKey(State, to_field='state_name', on_delete=models.SET_NULL, null=True) unit_name = models.CharField(max_length=100, default="KVK") district_name = models.ForeignKey(District, to_field='district_name', on_delete=models.SET_NULL, null=True) block_name = models.ForeignKey(Block, to_field='block_name', on_delete=models.SET_NULL, null=True) village_name = models.CharField(max_length=150) village_covered_through_whatsapp_group = models.BooleanField(verbose_name=_('Village Covered through Whatsapp Group "yes/no"'), choices=BOOL_CHOICES) number_of_whatsapp_group_created = models.PositiveIntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) number_of_farmers_covered_in_the_village = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000)]) objects = DataFrameManager() class Meta: db_table = 'Group_Info_Table' constraints = [models.UniqueConstraint(fields=["state_name","district_name", "block_name", "village_name"], name="all_keys_unique_together")] def __str__(self): return self.unit_type return self.state_name return self.unit_name return self.district_name return self.block_name return self.village_name return self.village_covered_through_whatsapp_group return self.number_of_whatsapp_group_created return self.number_of_farmers_covered_in_the_village views.py is as: If I am fetching data like this, it returns id's of all columns having foreign keys def amfu_state_wise(request): state_name_is = None district_name_is = None block_name_is = None if request.method == "POST": state_name_is=request.POST.get('state') district_name_is=request.POST.get('district') block_name_is=request.POST.get('block') fetch_whole_database = GroupDetail.objects.all() all_fields = GroupDetail._meta.get_fields() print("all_fields",all_fields) fetch_data_df = fetch_whole_database.to_dataframe(['unit_type', 'state_name__id', 'unit_name', 'district_name__id', 'block_name__id', 'village_name', 'village_covered_through_whatsapp_group', 'number_of_whatsapp_group_created', 'number_of_farmers_covered_in_the_village'], index='id') print("fetch_data_df", fetch_data_df.state_name__id.head(5)) The output in console is … -
Accessing a network path using a Django API
I have a network path say "\\\\drive\\Folders\\". I have to check for certain files. I have been using os.listdir to get all the subsequent directors. It works just fine when I run it normally using python compiler. But, a Django API of mine throws "The system cannot find the path specified:" error. I am not sure what I am missing. -
Use prefetched data on django form to set field queryset
I am not sure how to set form fields using prefetched data. I am fetching a questionnaire section and then pre fetching the questions in the section. The idea if that the questions for the section will be available in the section condition choices form. Query questionnaire_sections = Section.objects.prefetch_related( Prefetch( 'question_set', queryset=Question.objects.all(), to_attr="questions" ) ), ) This works: for section in questionnaire_sections questions = Question.objects.filter(section=section) condition_form = QuestionnaireConditionForm() condition_form.fields["item"].queryset = questions section.condition_form = condition_form But it i try to use prefetched data like below to save queries, I get error below. for section in questionnaire_sections questions = section.questions condition_form = QuestionnaireConditionForm() condition_form.fields["item"].queryset = questions section.condition_form = condition_form Error: AttributeError: 'list' object has no attribute 'all' The error is quite obvious, but I am wondering if I can actually populate form choices using prefetched data at all? -
Django 4 Cascade Admin Panel modification
After upgrade from Django 2 to Django 4 i have noticed that Admin panel went, lets say, cascade. In Django 2 every model clicked was opened in new window but now it's 'cascading' lower and lower and its super ultra inreadable. Is there possibility to somehow bring back 'old' Admin Panel view into Django 4? -
Render template with params from another app (microservice)
I'm making web app with the microservice architecture and when it comes to login I want to redirect the successful logged in user to his dashboard (which is on another microservice). I have a problem with passing parameters such as: name, surname, email, token microservice 1: class SignInView(viewsets.ViewSet): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() print(bool(user.is_coordinator)) if user is None: messages.error(request, 'User not found. Please try again') return HttpResponseRedirect('/sign-in') if not user.check_password(password): messages.error(request, 'Invalid password. Please try again') return HttpResponseRedirect('/sign-in') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = ({ 'jwt': token }) if user.is_coordinator: return redirect('http://127.0.0.1:8001/dashboard-coordinator') else: return HttpResponseRedirect('http://127.0.0.1:8001/dashboard-employee', {'name': user.name, 'surname': user.surname, 'email': user.email, 'response.data': response.data}) ... microservice 2: class HomeView(viewsets.ViewSet): def get(self, request): return render(request, 'dashboard-employee.html', {'name': name, 'surname': surname, 'email': email, 'response.data': response.data}) It does not work what I include in microservice 2. How can I get and process params from microservice 1 ? Is there any better solution/approach ? -
Dynamic FileResponse on Django URL
I have one view at my project that returns a FileResponse using data from a post request form from another view. I was wondering if I could, at my urls.py where I point the FileResponse, make the path dynamic using data from the post request. My current url is returning a static file name, which is "pdf_file" path('pdf_file', generateFile, name='pdf_file') Lets say my form request the name, then I would like to return 'pdf_file_{name}', as an example Is that possible? -
Is there a way to achieve what that code wants to do with scrolling down instead of clicking on Next?
Based on an answer to my previous question here , I learned about pagination in Django and I can go to next pages after clicking on Next . Views: def All( request ): p=product.objects.all() pa=Paginator(p,20) page=request.GET.get('page') pro=pa.get_page(page) return render(request,'home.html',{'pro':pro}) Template: <div class="grid"> {%for p in pro%} <div class='card'> <img src="{{p.image}}"></img> <p id="id">{{p.description}}</p> <a href="{{p.buy}}" target='_blank' rel='noopener noreferrer'> <button ><span class="price"> ${{p.price}}</span> buy</button> </a> </div> {%endfor%} {% if pro.has_next %} <a href="?page={{pro.next_page_number}}">Next</a> {% endif %} </div> This code wants to show me the next pages: {% if pro.has_next %} <a href="?page={{pro.next_page_number}}">Next</a> {% endif %} Is there a way to achieve what that code wants to do with scrolling down instead of clicking on Next? -
Django - Integrity error when tried deleting a project [I AM A BEGINNER]
I only have one model and that's the only one I need. How to design the model in a way that I don't get the foreign key constraint error? Here's my model: class Project(models.Model): STATUS = ( ('Inititated', 'Inititated'), ('Paused', 'Paused'), ('In progress', 'In progress'), ('Aborted', 'Aborted'), ('Completed', 'Completed') ) PHASE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10') ) p_id = models.IntegerField(null=True) p_name = models.CharField(max_length=100, null=True) c_name = models.CharField(max_length=100, null=True) c_mail = models.CharField(max_length=100, null=True) init_date = models.DateField(null=True) ect = models.DateField(null=True) status = models.CharField(max_length=200,null=True, choices=STATUS) collabs = models.IntegerField(null=True) phase = models.IntegerField(null=True, choices=PHASE) def __str__(self): return self.p_name @property def phase_percentage(self): return self.phase * 10 -
Django/Djoser Login Through React
I'm quite new to web development in general. So my django/react skills are quite poor. I'm not entirely sure what code I would need to post here to be able to effectively explain my issue. Essentially I'm trying to create a saas product which displays different data for each user. I can't seem to be able to get django to recognise that a user has logged in. At the moment I'm able to log in a user through my react app by sending a post request through djoser. This logs in and keeps the user logged in but it doesn't seem like django recognises this log in. I've tried adding in the react build into a django application but I'm getting the same result when doing this. I feel like I need to add something into the django app that contains my react build but I have no idea what or where to look. I'm not sure which pieces of code to add here as there are so many and I'm not entirely sure where the issue lies. So if someone requests to see anything I will upload whatever will be useful. Thanks -
How to filter objects in specific time range in Django
How you guys filter objects within specific time range including minutes. So, I have ticketing system, in which users are reporting work time for specific ticket. I need to filter this data for report, currently I'm using Q(time_to__hour__range=(9, 17)) which will select all objects from 9:00 till 17:59, but management need this report to be till 18:05 Here is filter which I'm using currently: f = Q(time_from__range=[form.cleaned_data.get('date_range_from'), form.cleaned_data.get('date_range_to') + timedelta(days=1)])\ & Q(client__in=form.cleaned_data.get('client_set') if form.cleaned_data.get('client_set') else Clients.objects.all())\ & Q(tech__in=form.cleaned_data.get('tech_set') if form.cleaned_data.get('tech_set') else Tech.objects.all()) if form.cleaned_data.get('selection') == '1': f &= Q(time_to__hour__range=(9, 17)) elif form.cleaned_data.get('selection') == '2': f &= ~Q(time_to__hour__range=(9, 17)) p.s. Django version 3.1.1 -
How can I implement publisher subscriber model using rabbitMQ and celery in Django?
As I know there are 2 main models in message queue, Publish/Subscribe and Producer/Consumer. Producer/Consumer is easy to implement and hte main concept would be that some app will be pushing into my message queue and one out of multiple celery workers will pick the message and process the same. This can be done by creating workers with the help of celery. However what I don't understand is how exactly would a publisher subscriber work with RabbitMQ and celery in Django. As I understand message produced by publisher is consumed by all subscribers that have subscribed to specific queue . Publishers produce messages while subscriber consumes message. So my question is how exactly can I use celery workers to subscribe to queues, how would this work exactly with Django. Any theory, blog, docs or videos that explains the same with Django, celery and any message queue would help -
Django Rest Framework reset password
I am following a tutorial on YouTube and wonder why we need the PasswordTokenCheckAPI in views.py because we then verify the uidb64 and token again in the SetNewPasswordAPIView anyway (in the serialiser.is_valid(), we also check if the token and uidb64 are valid). Can we just give the url to the reset password page directly in the email and verify things later when the user submits the password reset request? class RequestPasswordResetEmail(generics.GenericAPIView): serializer_class = ResetPasswordEmailRequestSerializer def post(self, request): serializer = self.serializer_class(data=request.data) email = request.data.get('email', '') if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) uidb64 = urlsafe_base64_encode(smart_bytes(user.id)) token = PasswordResetTokenGenerator().make_token(user) current_site = get_current_site( request=request).domain relativeLink = reverse( 'password-reset-confirm', kwargs={'uidb64': uidb64, 'token': token}) redirect_url = request.data.get('redirect_url', '') absurl = 'http://'+current_site + relativeLink email_body = 'Hello, \n Use link below to reset your password \n' + \ absurl+"?redirect_url="+redirect_url data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Reset your passsword'} Util.send_email(data) return Response({'success': 'We have sent you a link to reset your password'}, status=status.HTTP_200_OK) class PasswordTokenCheckAPI(generics.GenericAPIView): serializer_class = SetNewPasswordSerializer def get(self, request, uidb64, token): redirect_url = request.GET.get('redirect_url') try: id = smart_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(id=id) if not PasswordResetTokenGenerator().check_token(user, token): if len(redirect_url) > 3: return CustomRedirect(redirect_url+'?token_valid=False') else: return CustomRedirect(os.environ.get('FRONTEND_URL', '')+'?token_valid=False') if redirect_url and len(redirect_url) > 3: return CustomRedirect(redirect_url+'?token_valid=True&message=Credentials Valid&uidb64='+uidb64+'&token='+token) else: return … -
Getting an error when serializing a list of values [AttributeError: 'list' object has no attribute 'user_project']
I have two models Project and Shift with a Many-to-one relationship. And I want to collect statistics for all Shift objects. How this should happen: The User sends a GET request with a parameter that specifies which Project to calculate statistics for all its Shift, the function is called which calculates statistics and puts it all into the list and returns it, the list should be serialized and sent to the User. But I get an error when I send it. [AttributeError: 'list' object has no attribute 'user_project'] If I needed to serialize a model or QuerySet I probably wouldn't have any problems, but here I have a regular list. I wrote a separate serializer specifically for values from this list, but nothing works. Most likely I wrote it wrong. If there is a better way to do it, please advise me. models.py class Project(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) task = models.CharField(max_length=128) technical_requirement = models.TextField() customer = models.CharField(max_length=64, blank=True) customer_email = models.EmailField(blank=True) start_of_the_project = models.DateField() salary_per_hour = models.FloatField() project_cost = models.FloatField(blank=True, default=0) project_duration = models.DurationField(blank=True, default=datetime.timedelta(0)) class Shift(models.Model): user_project = models.ForeignKey('Project', on_delete=models.CASCADE) shift_start_time = models.DateTimeField() shift_end_time = models.DateTimeField() shift_duration_time = models.DurationField(blank=True, null=True) salary_per_shift = models.FloatField(blank=True, null=True) serializers.py class ShiftStatisticSerializer(serializers.Serializer): user_project … -
Deploying Django project with custom apps to heroku: remote: ERROR: /path/to/myapp/django-myapp is not a valid editable requirement
I am using Django 3.2 I have written a number of standalone apps, which I am using in my project. In my requirements file, I have included them at the bottom of the requirements.txt file like this: requirements.txt asgiref==3.5.0 Babel==2.9.1 certifi==2021.10.8 charset-normalizer==2.0.12 coverage==6.4.1 dj-database-url==0.5.0 Django==3.2 django-appconf==1.0.5 django-crispy-forms==1.14.0 django-js-asset==2.0.0 gunicorn==20.1.0 idna==3.3 psycopg2-binary==2.9.3 python-decouple==3.6 pytz==2022.1 requests==2.27.1 six==1.16.0 sqlparse==0.4.2 urllib3==1.26.9 webencodings==0.5.1 whitenoise==6.0.0 -e /path/to/django-apps/moderation/django-moderation -e /path/to/django-apps/social/django-social -e /path/to/django-apps/user/django-userprofile -e /path/to/django-apps/event/django-events -e /path/to/django-apps/contactus/django-contactus On my local machine, I type: pip install -r requirements.txt and everything is installed correctly. However, when I try to deploy to heroku by typing: git push heroku main I get the following error message: remote: -----> Installing requirements with pip remote: ERROR: /path/to/django-apps/moderation/django-moderation is not a valid editable requirement. It should either be a path to a local project or a VCS URL (beginning with bzr+http, bzr+https, bzr+ssh, bzr+sftp, bzr+ftp, bzr+lp, bzr+file, git+http, git+https, git+ssh, git+git, git+file, hg+file, hg+http, hg+https, hg+ssh, hg+static-http, svn+ssh, svn+http, svn+https, svn+svn, svn+file). remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... How do I fix this, so I can push local changes to heroku? -
Django Loading up Class based model data on a template
I am new to django before this only made 1 project and that was just a follow along video so obviously the fix is probably very easy, but I am trying to make a restaurant reservation page, and later on there will be user authentication to only show the reservation that particular user made, but right now I want to display all of the reservations in my modal and trying to learn how to actually display the data. here's the modal: https://gyazo.com/066e3e060492990008d608a012f588f3 here's the view: https://gyazo.com/6947ed97d84b38f1e73680e28f3a0a9a Here's the template: https://gyazo.com/966c4810b3c7f4dd8dad2e5b71c2179c I am spent about 3 hours watching other videos on people loading there modal data in there website and when they do it I understand everything but for some reason I can't apply that to my own project, my guess is my for loop is wrong since I have a hard time with writing them and seem to always mess up, so any help so I can at least start looking in the right direction would be appreciated -
Why Django admin Shows Invalid string value for specific table?
I use Mysql database where i set database and database column are utf8mb4 and collate utf8mb4_general_ci. When i want to change any data value then given this error Incorrect string value: '\xE0\xA6\xB8\xE0\xA7\x8D...' for column This error only happen those table whose Foreign key uses in other table. But single table which is not related to other tables then no error occured. I search the solution in google almost everyone says to change column charset, i change this but given same error those table which table is associated with other table..! Please help me!!! -
Best framework to learn in 2022? [closed]
I am web developer beginner working on WordPress right now, I just want to learn one framework amoung this? Django, React, or Laravel Plz suggest… -
Django : smtplib.SMTPAuthenticationError: 535, b'5.7.8 Username and Password not accepted
I was trying to send mail using the gmail smtp in DJango. I know about this option Less secured apps. But this option has been disabled by google now. Also I don't have any 2 factor authentication on my account. Here is my setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' # put your gmail address here EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True But I am getting error [2022-06-15 10:28:10,688: ERROR/ForkPoolWorker-1] Task app.tasks.send_email_task[9068931b-a457-415e-b910-d7c631596fce] raised unexpected: SMTPAuthenticationError(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o16-20020a056a00215000b0051b97828505sm9333570pfk.166 - gsmtp') Traceback (most recent call last): File "/etc/myprojectenv/lib/python3.8/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/etc/myprojectenv/lib/python3.8/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/etc/myproject/app/tasks.py", line 12, in send_email_task return send_mail( File "/etc/myprojectenv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 87, in send_mail return mail.send() File "/etc/myprojectenv/lib/python3.8/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/etc/myprojectenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/etc/myprojectenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 91, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.8/smtplib.py", line 743, in login raise last_exception File "/usr/lib/python3.8/smtplib.py", line 732, in login (code, resp) = self.auth( File "/usr/lib/python3.8/smtplib.py", line 655, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials … -
Can't establish a WebRTC connection between browser and server with Django and aiortc: WinError 10051
I have created a simple WebRTC conference where multiple peers on the same network can open a web page and see each other/talk to each other. Each peer keeps track of its own pool of RTCPeerConnections, while Django handles authorization and django-channels handle signaling through WebSockets. I also need to stream audio data to the server for analysis. I decided to add the server as another WebRTC peer. In order to do that, I used aiortc module and created a class RTCPeer that handles RTCPeerConnections and a class RTCRoom that spawns RTCPeers and keeps track of them. Both are connected to signaling: they can send messages through channel layer; any messages received by WebSockets consumer are forwarded to RTCRoom.receive. When I try to connect a client to the server, I run into error 10051 multiple times. It looks like none of the pairs of gathered ICECandidates can provide connection. What could be wrong here? INFO:aioice.ice:Connection(0) Check CandidatePair(('172.18.108.97', 58214) -> ('109.120.16.131', 63420)) State.FROZEN -> State.IN_PROGRESS DEBUG:aioice.ice:Connection(0) protocol(1) > ('109.120.16.131', 63420) Message(message_method=Method.BINDING, message_class=Class.REQUEST, transaction_id=b'\xcc)\xfb\x9c\xba\xc4!\xc0\x85P\x8fs') DEBUG:aioice.ice:Connection(0) protocol(1) error_received([WinError 10051] Сделана попытка выполнить операцию на сокете при отключенной сети) ... INFO:aioice.ice:Connection(0) Check CandidatePair(('172.18.108.97', 58214) -> ('192.168.1.149', 63420)) State.IN_PROGRESS -> State.FAILED Full log: https://drive.google.com/file/d/1v70SwZS2332sAoAfEbVHAJDRVJ0FVovg/view?usp=sharing RTCRoom … -
How i can make this filter
I wanna create filter for cars by marks, and idk why, i get empty template with list of objects I have this model with Foreignkey mark model for getiing mark for specify car class Product(models.Model): ENGINE_CHOICES = ( ('Бензин', 'Бензин'), ('Дизель', 'Дизель'), ) code = models.AutoField(primary_key=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) mark = models.ForeignKey(Mark, on_delete=models.CASCADE, related_name='mark') model = models.CharField(max_length=45) color = models.CharField(max_length=45) availability = models.BooleanField() price = models.PositiveIntegerField() image = models.CharField(max_length=64, null=True) slug = models.SlugField(blank=True) year = models.PositiveSmallIntegerField("Дата выхода", default=2019, null=True) draft = models.BooleanField('Черновик', default=False) cat = models.ForeignKey(Category, verbose_name='Категории', on_delete=models.PROTECT, null=True) description = models.TextField(max_length=500, null=True) engine = models.CharField(choices=ENGINE_CHOICES, max_length=20, blank=True, null=True) And this model class Mark(models.Model): code = models.AutoField(primary_key=True) title = models.CharField(max_length=45) def __str__(self): return self.title i have this component in html for getiing mark in vews <div id="myDropdown7" class="dropdown-content"> {% for mark in marks %} <form action="{% url 'filtration_marks' %}" method="GET"> <label class='dropdown-content-menu'> <input id='checkbox1' type="checkbox" class='checkbox' name="id" value="{{ mark.id }}"> <label for='checkbox1'></label> <button type="submit" style="border: 0; background-color: white; font-size: 16px;">{{ mark.title }}</button> </label> </form> {% endfor %} And this method in views that handle request def filtration_marks(request): products = Product.objects.filter(mark__in=request.GET.getlist('mark')) categories = Category.objects.all() marks = Mark.objects.all() context = { 'products': products, 'categories': categories, 'marks': marks, } return render(request, 'filtration.html', …