Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert the binary api Response into a pdf file in python
I have to call a api which gives me the response in binary, now I have to convert this to a readable pdf and send as attachment in mail. While doing so I am getting the pdf but it's getting corrupted. api_data = response.text attachments = [{"content": data, "type": "application/pdf", "filename": "REPORT.pdf"}] Api response in postman looks like this %PDF-1.7 2 0 obj [/PDF /Text /ImageB /ImageC /ImageI] endobj 11 0 obj <</Length 12 0 R /Filter /FlateDecode >> stream X �}���6��� �� `1��‑V�WJ �q�$��|�;� .��K��Ӌ~�Nw;3Y��_R"����‑�7�8ye~��*V�(����_�z,���˾��J�g= ���p,~,������D Any help will be appreciated very much. -
How can I style a django form with css?
I tried looking for the answer earlier but couldn't seem to figure out a few things. I'm creating my form in a form.py file so its a python file. Here is my forms.py file : class UploadForm(ModelForm): name = forms.TextInput(attrs={'class': 'myfieldclass'}) details = forms.TextInput() littype = forms.TextInput() image = forms.ImageField() class Meta: model = info fields = ["name", "details", "littype", "image"] Here is my views.py function for it if it helps find the solution : def uploadform(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) print(request.FILES) if form.is_valid(): form.save() redirect(home) return render(request, 'uploadform.html', {'form': UploadForm}) To style it I thought I could do something like this which I found in another question : class MyForm(forms.Form): myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass'})) Except I have no idea how to link a css page to that python file. This is what I tried writing but i think it doesnt work because its meant for html but its in a python file : <link type="text/css" rel="stylesheet" href="templates/form.css"> And so I'm just not sure how to style my form. Thanks for any answers! -
Django-Summernote not displaying as intended when in a modal/hidden div
I'm having alot of issues when trying to place django-summernote in a modal or a div (with display: none;) that is toggled with jquery. The bottom is an example of me trying to fit it in a modal. My example is below html: {% extends 'XYZ/index.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <button href="#certValModal" data-toggle="modal" type="submit" class="btn btn-success btn-circle btn-sm glow-button"> <i class="fas fa-check"></i> </button> <!--CERT VAL MODAL--> <div id="certValModal" class="modal" data-easein="bounceUpIn" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Send for CERT validation?</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button> </div> <div class="modal-body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form | safe }} </form> </div> <div class="modal-footer"> <button class="btn btn-success" data-dismiss="modal" aria-hidden="true">Send</button> </div> </div> </div> </div> {% endblock content %} Here is views: class TestView(LoginRequiredMixin, TemplateView): template_name = 'XYZ/TEST.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = forms.ValidationNew() return context forms: class ValidationNew(forms.ModelForm): content = SummernoteTextFormField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = 'add_validation' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = XYZValidation fields = ['content'] Please note: I have not set any custom settings in settings.py for django-summernote This is what summernote looks like … -
How do you post data in django with attribute depth=1 in the serializer?
I have a django model called “Enrolment” that depends on two other models through foreign key. “Course” model and “Enrolment” model. The “Course” model is like so: class Course(models.Model): name = models.CharField(max_length=100, blank=True) description = models.TextField(blank=True) prerequisite = models.TextField(blank=True) fee = models.FloatField(default=0.0) def __str__(self): return self.name And the Enrolment model is like so: class CourseEnrolment(models.Model): course_name = models.ForeignKey( Course, on_delete=DO_NOTHING) schedule = models.CharField(max_length=50, blank=True) student = models.ForeignKey( UserAccount, on_delete=DO_NOTHING) enrolment_date = models.DateTimeField(default=datetime.now()) def __str__(self): return self.course_name.name For me to gain access to the information about the enrolled course, I have to do like so in the CourseEnrolmentSerializer: class CourseEnrolmentSerializer(serializers.ModelSerializer): class Meta: model = CourseEnrolment depth = 1 fields = '__all__' With “depth = 1” being the secret to accessing information about the course. Now when I fetch enrolment, I get a response like below, which is exactly what I want like so. { "id": 5 "schedule": "June 23, 2022", "course_name": { "id": 4, "name": "fundamentals-of-programming", "description": "some description .", "prerequisite": "some prerequisite", "fee": 1000, }, "student": { "id": 1, "email": "martinsakinbo@yahoo.com", "first_name": "John", "last_name": "Doe", "phone": "1111111", } }, Now, the problem I have is that with “depth=1” in the serializer, I’m not able to create an enrolment when I … -
bootstarp grid system of django
MY problem I am implementing line breaks for more than 3 posts. and I set the grid with col-4 but Instead of being split middle the screen, they are gathered on the left. I want. 3 posts are located in the center so that a line break occurs every 3 how can i fix it? MY UNISEX.html {% extends "polls/base.html" %} {% block content %} {% load static %} <div class="container py-5"> <div> <p class="text-center fs-4 fw-bold">UNISEX</p> </div> </div> <!-- 사진크기 300px 400px --> <div class="container"> <div class="row"> {% for p in photo %} <div class="card col-4" style="width: 16rem; border: none"> <img src="{{ p.main_photo.url }}" class="card-img-top" alt="..."> <div class="card-body"> <p class=" card-text">{{ p.name }}</p> </div> </div> {% if forloop.counter|divisibleby:"3" %} </div> <div class="row"> {% endif %} {% endfor %} </div> </div> <div class="row"> </div> </div> <div class="container"> <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> <li class="page-item"> <a class="page-link" href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"> <a class="page-link" href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> </nav> </div> {% endblock %} Problem location <div class="container"> <div class="row"> {% for p in photo %} <div class="card col-4" style="width: 16rem; border: … -
Counting all items within django-treebeard Materialised Path nodes
I'm using django-treebeard to create a tree of Categories, each of which contains some Books: from django.db import models from treebeard.mp_tree import MP_Node class Book(models.Model): title = models.CharField(max_length=255, blank=False, null=False) categories = models.ManyToManyField("Category", related_name="books", blank=True) class Category(MP_Node): title = models.CharField(max_length=255, blank=False, null=False) book_count = models.IntegerField(default=0, blank=False, help_text="Number of Books in this Category") total_book_count = models.IntegerField(default=0, blank=False, help_text="Number of Books in this Category and its descendants") I want to display the number of Books in each Category, stored in Category.book_count, so I have a post_save signal like this: from django.dispatch import receiver @receiver(post_save, sender=Book) def book_post_save(sender, **kwargs): for category in kwargs["instance"].categories.all(): category.book_count = category.websites.count() category.save() (The reality is a bit more complicated, but this is the gist.) This works fine, and I can also do similar on an m2m_changed signal for if a Book's Categories have changed. BUT, I also want to calculate total_book_count - the total number of Books in a Category and in all of its descendant Categories. I can do this with a method like this on Category: def set_total_book_count(self): # All the Books in this Category's descendants: descendant_books = Book.objects.filter(categories__in=self.get_descendants()) # Combine with the Books in this Category but avoid counting duplicates: books = (descendant_books | self.books).distinct() … -
Connecting local data to Docker Django project
This is a question to understand what should be the best practice to follow in order to connect the dots on the argument. Currently I am developing a Dockerized Django website. In this website, one of the apps will be named 'dashboards', where I wish to publish data which is currently stored locally in .csv (updated every day through scheduled tasks). Now, I am trying to understand what should be the next steps to follow in order to connect these data to the Dockerized Django website. My first guess would be to schedule locally .sql scripts to 'append' the new data into the db that I can create locally. Then, connect the db to the Dockerized Django website through volumes belonging the postgreSQL service. Just a guess that I need to test. But, is there a way to skip everything locally and just do the work inside my Docker container? You can find the Github repository here. Many thanks! docker-compose.yml: version: '3.8' services: web: restart: always build: ./web expose: - "8000" links: - postgres:postgres - redis:redis volumes: - web-django:/usr/src/app - web-static:/usr/src/app/static env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn docker_django.wsgi:application -w 2 -b :8000 nginx: restart: always build: ./nginx/ ports: - … -
How to mock Django command which inserts data into django model
I am performing unittest on Django command which inserts the data received from API response into a database table. I am using unittest and mock to mock the the Command class and it's method, but I am not sure whether I am doing it correctly or not. Following is my code for Command and test: Command class Command(): def _insert_data(self, report_data, start_date): for data in report_data: self.cursor.execute(''' INSERT IGNORE INTO `report` ( `start_date`, `value_a`, `value_b`, `value_c`,`value_d`, ) VALUES (%s,%s,%s,%s,%s);''', ( str(start_date).split()[0], data['value_a'], data['value_b'], data['value_c'], data['value_d'] ) ) test_report_data.py from unittest import mock from base.test import BaseTestCase from client.models.intergration import Report from client.management.commands.update_report import Command as ReportCommand class CommandTestMixin(BaseTestCase): def setUp(self): super().setUp() self.mock_api_response = { "metrics": { "value_a": "123", "value_b": "123", "value_c": "1.48", "value_d": "1.0", } } self.mock_row = Report.objects.create( date = "2022-06-013" value_a = "123", value_b = "123" , value_c = "1.48", value_d = "1.0", ) def mock_response(self, json_data=None): mock_resp = mock.Mock() if json_data: mock_resp.json = mock.Mock( return_value = json_data ) return mock_resp class TestInsertReportData(CommandTestMixin): def setUp(self): super().setUp() def test_api_data_insert(self): command = ReportCommand() command._insert_data = mock.Mock() mock_resp = self.mock_response(json_data = self.mock_api_response) command._insert_data.return_value = self.mock_row command._insert_data(mock_resp, "2022-06-13") row = Report.objects.first() self.assertEqual(str(row.start_date), "2022-06-13") self.assertEqual(row.value_a, "123") self.assertEqual(row.value_b, "123") self.assertEqual(row.value_c, "1.48") self.assertEqual(row.value_d, "1.0") When … -
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=[] … -
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): … -
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 …