Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Graphql bottleneck performance with nested query (Django + React ) makes frontend app unusable. Please help :'(
For this project Im using Python+Django and GraphQL (graphene) in the backend, MySQL as database and React.js for the frontend. In the frontend, after user logs in, I have the following query to be executed: const GET_ORGANIZATION = gql` query getOrganization($orgId : Int!) { organization(id:$orgId){ id name user{ id username firstName lastName email dateJoined lastLogin isActive trainings { id name sessions { id name category createdAt totalSteps completedAt user { id } eventSet { id category description object errorSeverity performedAt } } } } courses{ id name description trainings{ id name user{ id username isSuperuser isStaff isActive email } sessions{ id name category createdAt completedAt user{ id username } eventSet { id category description object errorSeverity performedAt } } } } } }`; As you can see, it has several levels nested. The problem comes when I go into sessions and events . I am not super expert with graphQL but I always thought the selling idea of GraphQL was that you can use all these nested fields in one single query. Well, it's not. Here are few images why: It takes over 30 seconds for the response to come. Digging a bit more into the slow_log of my database, … -
How to fix CORS Error on Django and Django REST Framework
I sometimes get CORS Error from the server, when I turn on a VPN I get 200 and when I change the VPN or when I turn it off I get CORS Error again, How can I fix CORS Error on Django and DRF. I have tried some ways and some references like: How can I enable CORS on Django REST Framework https://dzone.com/articles/how-to-fix-django-cors-error#:~:text=A%20request%20for%20a%20resource,has%20blocked%20by%20CORS%20policy. https://github.com/adamchainz/django-cors-headers but it isn't solved. what shall I do? -
Select a particular data using xpath
This is the element from a webpage <div class='someclass'> <section> <h4>Skills</h4> <p>Python, java, django</p> </section> <section> <h4>Prerequisites</h4> <p>Coding</p> </section> </div> I am trying to extract the skills from this using xpath. How can I achieve it? my answer should be: Python, java, django -
Django - After login, I get an error message saying This page isnt working on Google Chrome
I get an error message on the web browser after trying to login to my application. The error message is - This page isn’t working d1bbcb8e2c574d65bcfc28f937c87503.vfs.cloud9.us-east-2.amazonaws.com redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS My views is below # Views from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render, redirect from django.contrib import messages from powercons_app.EmailBackEnd import EmailBackEnd def loginPage(request): return render(request, 'login.html') def doLogin(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: user = EmailBackEnd.authenticate(request, username=request.POST.get('email'), password=request.POST.get('password')) if user != None: login(request, user) user_type = user.user_type #return HttpResponse("Email: "+request.POST.get('email')+ " Password: "+request.POST.get('password')) if user_type == '1': return redirect('admin_home') # elif user_type == '2': # # return HttpResponse("Staff Login") # return redirect('staff_home') # elif user_type == '3': # # return HttpResponse("Client Login") # return redirect('client_home') else: messages.error(request, "Invalid Login!") return redirect('login') else: messages.error(request, "Invalid Login Credentials!") #return HttpResponseRedirect("/") return redirect('login') def get_user_details(request): if request.user != None: return HttpResponse("User: "+request.user.email+" User Type: "+request.user.user_type) else: return HttpResponse("Please Login First") def logout_user(request): logout(request) return HttpResponseRedirect('/') #Admin View from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.contrib import messages from django.core.files.storage import FileSystemStorage #To upload Profile Picture from django.urls import reverse … -
Django - How to ignore autmoatic model language filter
My application have three different languages I want to ignore the model translation automatic filter by the framework to get all data and not by activated translate. # LANGUAGES LANGUAGES = ( ('ru', _(u'Русский')), ('en', _(u'English')), ('cn', _(u'漢語')) ) def get_queryset(self): queryset = super(ModelView, self).get_queryset().order_by('-pub_date').only('city_ru') return queryset Before queryset get executed I've tried translate.activate('ru') to get 404 not found if user tried to switch to another language, but I want to keep the same data for all languages no matter if the user switched or not the text on website will be translated but data will still the same. -
Get sql query value in Django
how can I get only the value of the following query. I just want to get the value of name, and not a dict, since in laravel you can use the -> get () in django that I can use. with connection.cursor() as cursor: cursor.execute("SELECT name FROM person WHERE id=2") fila=cursor.fetchall() Thanks. -
Data migrations for OneToOneField in django with data in tables already
I have a case model that I added a OntToOneField to Example: zoho_api = models.OneToOneField( ZohoAPIState, default=create_new_zoho_api_state, related_name='referral_profile', on_delete=models.CASCADE ) During development there was no data in the tables and the migration worked fine. But trying to migrate with data in the tables gives me the following errors: Errors Says DETAIL: Key(zoho_api_id)=(some guid) is duplicated. How do I get around this issue? -
Items remain in the lists even after using del statement
I'm building an app using Python and Django and I'm facing a problem with some variables. Below are simpldified portions from my code to explain the problem (you can access the complete code in the repo): # resources.py class HREmployeeResource(ModelResource): def after_import_row(self, row, row_result, row_number=None, **kwargs): row_result.employee_code = row.get('Employee Code') if not kwargs.get('dry_run'): import_type = row_result.import_type employee_code = row_result.employee_code instance = kwargs.get('instance') # we need the ones belong to these 2 companies in the report if instance.company in ['Company 1', 'Company 2']: self.report.setdefault(import_type, []).append(employee_code) # views.py import gc from resources import HREmployeeResource def import_hr_file(request): if request.method == 'POST': hr_file = request.FILES['hr-file'] data = get_import_data(hr_file) hr_resource = HREmployeeResource() result = hr_resource.import_data(data, dry_run=True) if not result.has_errors(): result = hr_resource.import_data(data, dry_run=False) ImportStatus.objects.create( date=timezone.now(), status='S1', data=hr_resource.report ) del result, hr_resource, data gc.collect() return redirect('core:import-report') return render(request, 'core/upload-hr-file.html', {}) The ModelResource class is from a third-party library called django-import-export and the import_data method belongs to this class, you could find the code of the method here. When I run the view import_hr_file for the first time everything is working fine, but when I execute it the second time I find that the old items still exist in the lists of the report dict of the … -
how to request session value in template django
i want to fetch a session value directly in myy template i have fom by which i request session and after that i am viewing that session in another html my views.py where session got created class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.order_by('-update_at') return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('Size') cart = request.session.get('cart') if cart: cart[item] = size else: cart = {} cart[item] = size request.session['cart'] = cart print(request.session['cart']) return redirect('products:detail', item_id=item_id) my views.py in which i want ot render session class Cart(View): def get (self, request): cart = request.session.get('cart', None) if not cart: cart = {} # or however you define your empty cart request.session['cart'] = cart ids = (list(cart.keys())) ids = (list(request.session.get('cart').keys())) item = Item.get_items_by_id(ids) print(item) return render(request, 'cart.html', {'items': item }) my html code {% for item in items %} <tbody style="margin-bottom: 20px;"> <tr> <th scope="row">{{forloop.counter}}</th> <td> <img src="{{item.first.url}}" alt="" height="100px"></td> <td>{{item.name}}</td> **<td>{{request.session.cart}}</td>** <td>{{item.price|currency}}</td> <td> <a href="#">Remove</a> </td> </tr> </tbody> {% endfor %} </table> </div> </div> so my session list has two values in it one is id and other is its size so want … -
Django FileField does not save unless in debug mode
I'm trying to upload files in Django 3.2 and am having a weird problem where the files save to the MEDIA_ROOT folder when I have the debugger on and set a breakpoint. But if I just run the project, then the files don't save. I cannot workout what is going on, but I would guess some sort of timing/threading issue? Any help appreciated. I have put my code below. I'm using FormModels to generate the forms and a Formset to allow multiple images to be uploaded. Models class TimestampedModel(d_models.Model): created_date = d_models.DateTimeField(auto_now_add=True) updated_date = d_models.DateTimeField(auto_now=True) class Meta: abstract = True class Case(TimestampedModel): class CaseType(d_models.IntegerChoices): One = 0, d_translation.gettext_lazy('One') Two = 1, d_translation.gettext_lazy('Two') # __empty__ = d_translation.gettext_lazy('Other') reference = d_models.CharField(max_length=32, editable=False) case_type = d_models.IntegerField(choices=CaseType.choices) def get_file_path(instance, file): return '{0}/{1}_{2}'.format(datetime.datetime.today().strftime('%Y-%m-%d'), uuid.uuid4().hex, file) class SourceMedia(TimestampedModel): class SourceMediaType(d_models.IntegerChoices): Image = 0, d_translation.gettext_lazy('Image') Video = 1, d_translation.gettext_lazy('Video') case = d_models.ForeignKey(Case, on_delete=d_models.CASCADE) mime_type = d_models.CharField(max_length=50, null=True) media_file = d_models.FileField(upload_to=get_file_path) Forms: class CaseForm(d_forms.ModelForm): def __init__(self, *args, **kwargs): super(CaseForm, self).__init__(*args, **kwargs) class Meta: model = models.Case fields = ['case_type'] class SourceImageForm(d_forms.ModelForm): @classmethod def create_formset(cls, extra, max_num): formset = d_forms.modelformset_factory(models.SourceMedia, form=SourceImageForm, extra=extra, max_num=max_num) return formset class Meta: model = models.SourceMedia fields = ['media_file'] View def case_create(request): source_media_formset = forms.SourceImageForm.create_formset(extra=5, … -
Dependent Chained Dropdown Select List with Django - Not working
I am trying to build a dependant dropdown in a django form, but it is not working. I have followed videos and tutorials, but got no luck. I would like to select a brand of a car (make) and then a model of a car. The model depends on the car's brand, of course. I have followed this tutorial https://python.plainenglish.io/python-and-django-create-a-dependent-chained-dropdown-select-list-b2c796f5a11 Status: The "Make" dropdown works fine. The "Model" dropdown is never showing anything. It just does not work, but no error is shown... :S models.py from django.db import models from django import forms class Vehicle(models.Model): make = forms.CharField(max_length=30) model = forms.CharField(max_length=30) ...omitted forms.py from django import forms from .models import Vehicle import json def readJson(filename): with open(filename, 'r') as fp: return json.load(fp) def get_make(): """ GET MAKE SELECTION """ filepath = '/Users/alvarolozanoalonso/desktop/project_tfm/tfm/JSON/make_model_A.json' all_data = readJson(filepath) all_makes = [('-----', '---Select a Make---')] for x in all_data: if (x['make_name'], x['make_name']) in all_makes: continue else: y = (x['make_name'], x['make_name']) all_makes.append(y) # here I have also tried "all_makes.append(x['make_name']) return all_makes class VehicleForm(forms.ModelForm): make = forms.ChoiceField( choices = get_make(), required = False, label='Make:', widget=forms.Select(attrs={'class': 'form-control', 'id': 'id_make'}), ) ...omitted class Meta: model = Vehicle fields = ['make', 'is_new', 'body_type', 'fuel_type', 'exterior_color', 'transmission', 'wheel_system', 'engine_type', 'horsepower', … -
How do I allow partial updates via POST request in Django?
Working on a small Django app and I've been asked to set up partial updates via POST request. I'm aware that PATCH works for partial updates out of the box but I don't have access to the front end and that's not what I've been asked to do. I was told it's a quick one line change, so I'm assuming I have to update the serializer as explained in the DRF docs (https://www.django-rest-framework.org/api-guide/serializers/#partial-updates) but I'm not sure where to do that exactly. Serializers: from rest_framework import serializers from cat.models import Cat class CatSerializer(serializers.ModelSerializer): class Meta: model = Cat fields = ( 'id', 'name', 'breed', 'birth_date', 'added_at', 'description') Viewset: from rest_framework import viewsets from cat.serializers import CatSerializer from cat.models import Cat class CatViewSet(viewsets.ModelViewSet): queryset = Cat.objects.all().order_by('-birth_date') serializer_class = CatSerializer -
How to pass date string to datetime field in django?
I need the number (as integer) of users that signed up (User.date_joined) between '2016-01-01'(string) and '2016-04-01' (string) (both dates fully included) The below queries didn't give me accurate results, since the date_joined is datetime field User.objects.filter(date_joined__gte='2016-01-01',date_joined_lte='2016-04-01').count() User.objects.filter(date_joined__range('2016-01-01 00:00:00','2016-04-01 12:59:59')).count() I am new to django and python , want to know how to pass the string date values to datetime field and use of range function -
Django Database queries to 'default' are not allowed in SimpleTestCase
I tried running the following tests and they both fail. I don't understand the error because my view does not have a model included. view class ClassroomGradebookView(TemplateView): """for choosing first gradebook""" template_name = "gradebook/gradebookstart.html" urls urlpatterns = [ path('', views.index, name='index'), .... path('gradebookstart/', views.ClassroomGradebookView.as_view(), name='gradebookstart'), ] test class ClassroomGradebookTests(SimpleTestCase): def test_classroomgradebook_url_name(self): response = self.client.get(reverse('gradebook:gradebookstart')) self.assertEqual(response.status_code, 200) def test_classroomgradebook_status_code(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) error AssertionError: Database queries to 'default' are not allowed in SimpleTestCase subclasses. Either subclass TestCase or TransactionTestCase to ensure proper test isolation or add 'default' to gradebook.tests.ClassroomGradebookTests.databases to silence this failure. -
How to fix systemctl status error gunicorn when deploying the digital ocean
I'm deploying a django project on digital ocean. My project has the following structure: $/ flo-log/ logistics/ settings.py wsgi.py ... manage.py ... I created a user with sudo privilege.I encountered the error found an the attached file: enter image description here The error stated that there's no module called logistics however,I have a directory called logistics which contains the wsgi file. Please how do I fix this error? -
Django permission for member only
I use the default role access control from Django with decorator as : @is_allowed(accounts_allowed=AccountType.MYACCOUNT) It works well but there is a case where I have to add some restriction to let only project members acces my view. Here is how I've done : def isProjectMember(project, request): membersProjectsId = [project.member.id, project.member2.id, project.member3.id] if request.user.id in membersProjectsId: return False and in my view: if not isProjectMember(project, request): return HttpResponseForbidden() It woks fine but I would have liked to know if there would not be a more optimal way of proceeding? Thank you. -
Failure to send form information to Function in Django
please look at my codes I created a class to create comments, I also wrote Vivo and HTML codes, but whatever I do, the information is not registered. Does anyone know the reason ?? view funtion register comment in model admin def comment_view(request): comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): title_comment = comment_form.cleaned_data.get('title_comment') full_name = comment_form.cleaned_data.get('full_name') comment_text = comment_form.cleaned_data.get('comment_text') strengths = comment_form.cleaned_data.get('strengths') weak_points = comment_form.cleaned_data.get('weak_points') product_id = comment_form.cleaned_data.get('product_id') product: Product = Product.objects.get_by_id(product_id) CommentModel.objects.create(owner_id=request.user.id, product_id=product.id, title_comment=title_comment, full_name=full_name, comment_text=comment_text, strengths=strengths,weak_points=weak_points ) messages.success(request,'نظر شما با موفقیت ثبت شد') return redirect('/') context = {'comment_form': comment_form, 'title': 'ایجاد نظر جدید'} return render(request, 'comment.html', context) model comment class CommentForm(forms.Form): full_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'نام و نام خانوادگی خود را وارد کنید'})) title_comment = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'عنوان نظر خود را وارد کنید'})) comment_text = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'متن نظر خود را وارد کنید'})) strengths = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'نقاط قوت محصول را وارد کنید'})) weak_points = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'نقاط ضعف محصول را وارد کنید'})) product_id = forms.IntegerField(widget=forms.HiddenInput()) url comment path('new-comment', comment_view, name='new-comment'), forms comment class CommentForm(forms.Form): full_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'نام و نام خانوادگی خود را وارد کنید'})) title_comment = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'عنوان نظر خود … -
Django - How do I display data from a dictionary in views.py
I have a dictionary in my views.py that set up like this: def dctFormat(request): dct = {} dct1 = {} for data in MapData.objects.all().iterator(): dct[data.User_Number] = dct1 dct1["First_Name"] = data.First_Name dct1["Account_or_Gift"] = data.Account_or_Gift dct1["Child_Name"] = data.Child_Name return render(request, 'datamap.html', context=dct) In the model.py, the MapData model looks like this: class MapData(models.Model): # name of the table AccountType = models.TextChoices('AccountType', 'Account Gift') UserType = models.TextChoices('UserType', 'User Customer') User_Number = models.IntegerField() User_or_Customer = models.CharField(max_length=8, choices=UserType.choices) First_Name = models.CharField(max_length=30); Child_Relationship_With_Gift = models.CharField(max_length=20) Child_Name = models.CharField(max_length=20) Account_or_Gift = models.CharField(max_length=10, choices=AccountType.choices) Occasion_or_Purpose = models.TextField() City_State = models.CharField(max_length=30) How do I go about displaying the dictionary in my views.py on the front end in my HTML file? I've seen a few forums but none of them really helped. Essentially the dictionary should look like this: {'1': {'First_Name': 'Paula', 'Child_Name': 'Ari', 'Account_or_Gift': 'Gift'}, '2': {'First_Name': 'Jake', 'Child_Name': 'Luke', 'Account_or_Gift': 'Account'}...} So when I call on the dictionary, it'll display the data based on the corresponding number. -
how to create a comment system using drf
halo i'm working on a project that requires user to give a feedback whenever possible using django rest_framework but im getting an some difficulties doing that below is my code snippet & err msg ##mode file class Review(models.Model): school = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='review') name = models.CharField(max_length=250, blank=True, null=True) reviewer_email = models.EmailField() rating = models.CharField( max_length=250, blank=True, null=True) review = models.TextField() ##serializer file class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = ('name', 'review', 'id', 'reviewer_email', 'rating') ##apiView class ReviewAPIView(generics.CreateAPIView): serializer_class = ReviewSerializer permissions = [permissions.AllowAny] queryset = Review.objects.all() err msg return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/olaneat/Desktop/files/project/django/schMrk/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: schoolDetail_review.school_id [04/Aug/2021 15:37:12] "POST /school-detail/add-review HTTP/1.1" 500 208720 can anyone help pls -
Appointment slots with a few object created
I want to build an app that make easier Teacher and Student to have an appointment. Teacher have to submit their availabilities. For example, make them allow to tell student I'm available for appointment such date at such hour. Student can see all their availabilities and then can choice the appointment. Here is my models.py : class Appointment(models.Model): class Meta: unique_together = ('teacher', 'date', 'timeslot') TIMESLOT_LIST = ( (0, '09:00 – 10:00'), (1, '10:00 – 11:00'), (2, '11:00 – 12:00'), (3, '12:00 – 13:00'), (4, '13:00 – 14:00'), (5, '14:00 – 15:00'), (6, '15:00 – 16:00'), (7, '16:00 – 17:00'), (8, '17:00 – 18:00'), (9, '18:00 – 19:00'), (10, '19:00 – 20:00'), ) student = models.OneToOneField('Student', null=True, on_delete=models.CASCADE) teacher = models.OneToOneField('Staff', null=True, on_delete=models.CASCADE) date = models.DateField() timeslot = models.IntegerField(choices=TIMESLOT_LIST) def __str__(self): return '{} {} {}. Etudiant : {}'.format(self.date, self.time, self.doctor, self.patient_name) @property def time(self): return self.TIMESLOT_LIST[self.timeslot][1] is_completed = models.BooleanField(default=False) is_confirmed = models.BooleanField(default=False) So when the teacher will fill their availabilities, this will create many appointment objects and student have to choice one of them. I was asking myself there is an other possibility to not create as much appointment objects ? -
How to fix a Django view that is not returning an HttpResponse Object? (CS50 Project 1)
I am receiving the following error when submitting a form. ValueError at /edit_entry/hi/ The view encyclopedia.views.edit_entry didn't return an HttpResponse object. It returned None instead. Here is the views.py that is triggering the error. def edit_entry(request, title): if request.method == "POST": form = NewEditEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title, content) return HttpResponseRedirect("/wiki/" + title) else: form = NewEditEntryForm() return render(request, "encyclopedia/edit_entry.html",{ "form": NewEditEntryForm(), "title": title, "content": util.get_entry(title) }) What is the issue and how can I fix it? (I also need help prepopulating the form with already existing data. I have tried using initial, but that has not worked. What is the best way to prepopulate the form with existing data?) -
Django serializer update method key error in validated_data
I m using django rest framework to provide api to multiple application. single models being shared with these applications. And every applications are using some fields that no other apps are using. I have to write update method on serializer and take action as per the fields value received from these apps. when i write the update method and in case django doesn't finds any key it throws error. let see the code: Model: class TaskChecker(models.Model): taskName=models.CharField(max_length=50) notified = models.BooleanField (default=False) isDeleteRequest = models.BooleanField (default=False) isDeactivateMe = models.BooleanField (default=False) isActive = models.BooleanField (default=False) class TaskSerializer(serializers.ModelSerializer): class Meta: model=TaskChecker fields='__all__' def update(self, instance, validated_data): isDeleteRequest = validated_data['isDeleteRequest'] do some task isActive= validated_data['isActive'] do some task now the scenario is at a time either i will get validated_data['isDeleteRequest'] or validated_data['isActive']. in that case i get key error. how to resolve the issue? if i dont get the key at that time i should not get error. please help. thank you so much.... -
How to create element in another model with django
I have a small question. That is actually making me scratch my head. So in my Database, I have the following models: Activity Bill Clients I think you are all seeing the relationship I am trying to create : A Bill has one client and one or more activities. Here is the trick to make this whole thing user-friendly I am trying to create Bills (with the url: Bill/new) that can be edited manually. So the user is sent to an HTML page with the basic Bill template and he has a table that can add some rows with the activity the time spent and its cost. There are three things I am trying to achieve. Generate automatically the ID of the Bill (it should be pk of Bill) but it seems it's not generated until I have pressed on save. When I save a Bill I want to save also the activities I have entered manually. When I save the Bill I would like to save it as a Word or PDF document in the database. Are these possible? Thanks all for reading and helping I am banging my head to figure out how to do all of this … -
ResolutionFailure error while installing Twilio again with other dependencies in django
I need to install twilio in my django-project. The project already has a Pipfile and pipfile.lock containing the other dependencies needed. When I try to install twilio using the command "pipenv install twilio" its gives a resolutionfailure error. The issue is that twilio requires the PyJWT version to be 1.7.1 but other dependencies require the version of PyJWT to be greater than 2 and less than 3. How do I manage to maintain different versions of the PyJWT version and How do I install twilio with the same? -
how to show one text 3 times or more with httprespons in django
How can I return something or text 2 or more times ? In this case, i have one text should be printed . I want to keep the return because i need to execute a function that returns either None or an Httpresponse in urls we have : path('happy/<str:name>/<int:times>', happy), in views we have : def happy(request , name ,times): response = f"you are great , {name}:)\n " return HttpResponse(response , content_type='text/plain') i need show text in the amount of times how do this?