Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirect user from login to crud first page
I'm new in django and even in python I have a project 'mysite' with 3 apps. Configs of urls mysite urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), # user management path('account/', include('allauth.urls')), #local path("", include("pages.urls", namespace="pages")), path("imoveis/", include("imoveis.urls", namespace="imoveis")), ] App Users - no urls.py App Imoveis - urls.py: from django.urls import path from . import views app_name = "imoveis" urlpatterns = [ path('', views.form, name='form'), path('create/', views.create, name='create'), path('view/<int:pk>/', views.view, name='view'), path('edit/<int:pk>/', views.edit, name='edit'), path('update/<int:pk>/', views.update, name='update'), path('delete/<int:pk>/', views.delete, name='delete'), ] and App pages - urls.py: from django.urls import path from . import views app_name = "pages" urlpatterns = [ path("", views.HomePageView.as_view(), name="home"), ] I have a template folder (a folder not inside any app or project) with: Accounts Folder: login.html, logout.html and signup.html -Imoveis Folder: form.html, read.html and view.html and base.html and home.html direct in template folder I want to when user log in they goes to form.html. I don't know how to change from base.html I put in form.html : {% extends 'account_login.html' %} but nothing. Any help are welcome. Regards -
Django server doesn't serve requests
I've got a django server up and running. When I try to it any api in it, it gives error "Error: Parse Error: Expected HTTP/" on postman. I've tried to access a single api directly from browser by typing "localhost:9001/". I have a default health check api which should ideally run on this, but none of my apis are working on this. -
Django javascript online connection with socket?
Learning Django/socket, I challenged myself with a little online 1v1 memory card game. For the moment the code is able to create a landing page then creating/joining a room. The room present the memory card game with a chat. My following problem is that the memory card is not the same for the room, look like a random is generate 2 times even if player are in the same room If you have any clue, adivices I will appreciate. (not a pro or a student, just doing it for my pure enjoyement, sorry if the following code contains errors) Here is my code HTML : % extends 'base.html' %} {% load static %} {% block content %} <div class="container main"> <div class="sideme"> <div class=" w-100 d-flex justify-content-center"> <div> <strong class="my-3 text-white text-center"> <p class ="mt-3"id="userdiv"> </p> <span class="my-3">Total User : <span id="user_num"></span></span><br> <div class="d-flex justify-content-between"> <div><span id="userTurn"></span> Turn</div> <div id="lastStepDiv"> </div> </div> </strong> <div class="wrapper"> <ul class="cards"> <li class="card"> <div class="view front-view"> <img src="{% static 'images/que_icon.svg' %}" alt="icon"> </div> <div class="view back-view"> <img src="{% static 'images/img-1.png' %}" alt="card-img"> </div> </li> <li class="card"> <div class="view front-view"> <img src="{% static 'images/que_icon.svg' %}" alt="icon"> </div> <div class="view back-view"> <img src="{% static 'images/img-6.png' %}" … -
Django dynamic sitemap without using models
So, basically I have data coming from an API. There's no model and the data is not stored in my database. I just send request and get data. The problem is every single tutorial for dynamic sitemaps in Django requires usage of Models. Also came across this question but it doesn't have a proper solution. Is it possible to use Django's built-in sitemap module in this scenario or should I create my own script that generates sitemap programmatically? -
How to create url path dynamically from list of dicts
I have a list of dicts that contains a path, view, and view name suppose I have the following list with many of URLs, that are in the following format url_lsts = [ {"path" "preview/", "view": reverse("app:index"), name="preview"} ... ] urlpatterns = [ path(url["path"], url["view"], name=url["name"]) for url in url_lsts ] when using reverse i'm getting following url django.core.exceptions.ImproperlyConfigured: The included URLconf 'aisp.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. I've tried reverse_lazyand got the following URL raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
How to display a line chart with Charts.js and Django?
I would like to display a line chart in my Django template with chart.js but I'm unable to display something, except variables labels and data. The data structure seems to be correct according to the documentation, what could cause the issue ? > labels ['Home'] > data [{'x': '2022-01-07 16:00:00', 'y': 1.0}, {'x': '2022-01-08 16:00:00', 'y': 1.01}, {'x': '2022-01-08 17:00:00', 'y': 1.05}] base.html <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"> </script> template.html {% extends "base_generic.html" %} {% load static %} {% block content %} {% block scripts %} <script> // jquery function $(document).ready(function(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: {{labels}}, datasets: [{ label: 'Home data', data: {{data}} }] } }); }); </script> {% endblock scripts %} <canvas id="myChart" width="400" height="100"></canvas> {% endblock %} -
how to change form field from dropdown list to radio button in django if the options in dropdown are being inherited from another model?
i am working on an application where i can select item from drop-down list and buy them. i have a form field which is a drop-down list(items are connected to other model via foreign key.i want to make those options appear as radio buttons instead of drop down list my models.py class Plans(models.Model): plan_name = models.CharField(max_length=50) speed = models.IntegerField() price = models.FloatField() def __str__(self): return self.plan_name def get_deadline(): return dt.today() + timedelta(days=30) class Orders(models.Model): user = models.ForeignKey(CustomUser, primary_key=True, on_delete = models.CASCADE) pack = models.ForeignKey(Plans, on_delete = models.CASCADE) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(default=get_deadline()) is_active = models.BooleanField(default=True) def __str__(self): name = str(self.user.username) return name def get_absolute_url(self): return reverse('home-home') my forms.py(i tried using the init method but my drop down list vanishes when i use it) class BuyPlanForm(forms.ModelForm): error_css_class = 'error-field' required_css_class = 'required-field' class Meta(): model = Orders fields = ['pack'] #def __init__(self, *args, **kwargs): # super(BuyPlanForm, self).__init__(*args, **kwargs) # for field in self.fields.values(): # if isinstance(field.widget, forms.Select): # field.widget = forms.RadioSelect() my views.py class UserBuyPlan(LoginRequiredMixin, CreateView): template_name = 'plans/plan.html' form_class = BuyPlanForm def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) please help.(sorry i tried my best to explain the problem i am having but my english isn't that great) -
Django many-to-many relations
I'm trying to create a web app in which users can participate in some groups (every user can be part of multiple groups), and I want to be able to make both queries like group.users_set() and user.groups_set() I want to see all groups a user is participating to in the admin page of every user and vice versa. My last attempt was this: class CustomUser(AbstractUser): groups = models.ManyToManyField('Group', through='Participation') class Group(models.Model): group_name = models.CharField(max_length=200) group_password = models.CharField(max_length=200) customusers = models.ManyToManyField('CustomUser', through='Participation') class Participation: customuser = models.ForeignKey(CustomUser, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) but I get django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'userreg.admin.CustomUserAdmin'>: (admin.E013) The value of 'fieldsets[2][1]["fields"]' cannot include the ManyToManyField 'groups', because that field manually specifies a relationship model. Before, with just users = models.ManyToManyField(CustomUser) in the Group class and without the Participation class, I was able to get half of my goal, seeing the list of logged users in the admin page. What am I doing wrong? -
I can't render through the foreign key
I have a doubt. I want to show a name(nombre) of each client (cliente) with the total amount of money owed, so that each record is in a different cell. In pycharm I have this written: presupuestos.html <tbody> {% for pago in pagos %} <tr> <td> {% for presupuesto in presupuestos %} {{presupuesto.cliente.nombre}} {% endfor %} </td> <td> {{pago.cantidad_pagada}} </td> </tr> {% endfor%} </tbody> What happens is that when rendering this: {% for presupuesto in presupuestos %} {{presupuesto.cliente.nombre}} {% endfor %} The name appears, which is what I want to show, the bad thing is that all the repeated names appear in the same cell. But when using this: {{pago.estimate.cliente.nombre}} Nothing appears and If I put {{pago.estimate}} 'none' appears, but if there was nothing in the next loop the names would not appear I do not understand if my problem is due to my view.py or my models, possibly it is due to "estimates" in my payment model but I do not understand how to change it to be able to access that value pagos/models.py class Pagos(models.Model): numero_transaccion=models.IntegerField() estimate=models.ForeignKey(Presupuestos, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.numero_transaccion}' presupuestos/models.py class Presupuestos(models.Model): cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.cliente}' clientes/models.py class Clientes(models.Model): nombre … -
How can I include reverse related items in s Django serializer?
I'm trying to add all Payments that relate to a PayrollRun in the serializer to also return this. But how would I basically add reverse relations to a serializer? # views.py class PayrollRun(APIView): """ Retrieve payroll runs including line items for a company """ def get(self, request): # Get the related company according to the logged in user company = Company.objects.get(userprofile__user=request.user) payroll_runs = Payroll.objects.filter(company=company) serializer = PayrollSerializer(payroll_runs, many=True) return Response(serializer.data) # models.py class Payroll(models.Model): """ A table to store monthly payroll run information of companies """ # Relates to one company company = models.ForeignKey(Company, on_delete=models.CASCADE) month = models.DateField() amount = models.DecimalField(decimal_places=2, max_digits=10) line_items = models.PositiveIntegerField() def __str__(self): return f'Payroll run month {self.month} for company {self.company.name}' class Payment(models.Model): """ A table to store all payments derived from an offer """ # Relations offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.ForeignKey(Period, on_delete=models.CASCADE) payroll_run = models.ForeignKey(Payroll, on_delete=models.CASCADE, null=True, blank=True) # is populated once the payroll run was created amount = models.DecimalField(decimal_places=2, max_digits=10) def __str__(self): return f'{self.offer} with an amount of {self.amount} and payment month {self.month}' # serializers.py class PayrollSerializer(serializers.ModelSerializer): class Meta: model = Payroll depth = 1 fields = '__all__' right now returns the following without the related payment instances [ { "id": 12, … -
Put a book in several categories (Django)
I have a model named "book" and a model named "BookCategoty". how i can assign infinite category ForgienKeys? for books that fall into several categories. -
Django Rest Framework - Wrapping the JSON response with the name of the model
My goal is to customize the JSON response from Django DRF when listing items. The model: class Object(models.Model): code = models.CharField(max_length=16, primary_key=True, unique=True) item = models.CharField(max_digits=128) last_updated = models.DateTimeField(auto_now=True, editable=False) the serializer: class ObjectSerializer(serializers.ModelSerializer): class Meta: model = Object fields = ['code', 'item'] the view: class ObjectList(generics.ListAPIView): queryset = Object.objects.all() serializer_class = ObjectSerializer def list(self, request): queryset = self.get_queryset() serializer = ObjectSerializer(queryset, many=True) return Response(serializer.data) with this setup the JSON response is: [ { "code": "111", "item": "aaa" }, { "code": "222", "item": "bbb" } ] Is there a way to wrap the response with the name of the model? Expected result would be: "objects": [ { "code": "111", "item": "aaa" }, { "code": "222", "item": "bbb" } ] -
Save django Models in different script and run that script with HTML button
I have model.py as ''' class Fruit(models.Model): name = models.CharField(max_length=16) weight = models.IntegerField(max_length=16) color = models.CharField(max_length=16) class Veg(models.Model): name = models.CharField(max_length=16) weight = models.IntegerField(max_length=16) ''' I have myFunction.py as ''' def makeModels(file): with open(file, 'r') as f: line=f.readline() while line: if line.split(',')[0] == 'fruit': a = Fruit(name=line.split(',')[1], weight=line.split(',')[2], color=line.split(',')[3]) a.save() if line.split(',')[0] == 'veg': b = Veg(name = line.split(',')[1], weight = line.split(',')[2] b.save() line = f.readline() ''' and files as abc.txt "fruit,apple,3,red\n fruit,banana,1,green\n veg,spinach,4\n veg,collard,2\n fruit,banana,3,yelow\n veg,broccoli,3\n fruit,orange,1,orange" I want to create an HTML button to trigger this function/script and also create a celery scheduler to schedule a trigger to run at a time on a daily basis. This is on a django framework. Please help me on how to approach it. The running external function to save models through html button and scheduling it part. Thank you! -
django.db.utils.ProgrammingError:[SQL Server]The identifier that starts with xxx is too long. Maximum length is 128
I am trying to execute a store procedure using python. For that, I am passing json as input parameter of the stored proc. My json format is like: [ {"stored_procedur_root": {"sample11Id": 1050, "Userid": 1, "CreatedBy": 1388}}, {"stored_procedur_root": {"sample11Id": 1050, "Userid": 3, "CreatedBy": 1388}}, {"stored_procedur_root": {"sample11Id": 1050, "Userid": 6, "CreatedBy": 1388}} and so on.... ] If I execute the stored proc for only one row then the commit is successful but if I try multiple row input then I am getting error: django.db.utils.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The identifier that starts with '{"campaign_queue_users": {"CampaignId": 1050, "Userid": 1, "CreatedBy": 1388}}, {"campaign_queue_users": {"CampaignId": 1050, "U' is too long. Maximum length is 128. (103) (SQLExecDirectW)') What I believe is that I the query length exceeds 128 char limit after getting json input but I am unable to handle it. Is there a way that I can pass the json of list of dictionary line by line in the stored proc or I am doing wrong here? NOTE: I have tried single quote input also but getting the same error. Can someone please help me there, thanks in Advance. -
Filter related field Django orm shows multiple invalid results
Query TechnicianAssignment.objects.filter(Q(slot__slot_date=curr_datetime.date())&Q(assigned_technician__attendance_Technician__attendance_status__in=['Rejected', 'Absent', 'Someone else reported', 'Present'])) Models in short: **Table 1**: class TechnicianTeam(models.Model): id = models.AutoField(primary_key=True) supervisor = models.ForeignKey('self', null=True, blank=True, related_name="TechnicianSupervisor", on_delete=models.DO_NOTHING) customer_profile = models.ForeignKey('login.CustomerProfile', related_name="technician_TeamUser", on_delete=models.DO_NOTHING) class Meta: db_table = "technician_team" **Table2:** class TechnicianAssignment(models.Model): id = models.AutoField(primary_key=True) slot = models.ForeignKey('technician_management.TechnicianSlot', related_name="assignment_Slot", on_delete=models.DO_NOTHING) assigned_technician = models.ForeignKey('technician_management.TechnicianTeam', related_name="assignment_Technician", on_delete=models.DO_NOTHING) class Meta: db_table = "technician_assignment" **Table3** ATTENDANCE_CHOICES = [ ('Rejected','Rejected'), ('Someone else reported','Someone else reported'), ('Absent','Absent'), ('Present','Present') ] class TechnicianAttendance(models.Model): id = models.AutoField(primary_key=True) technician = models.ForeignKey('technician_management.TechnicianTeam', related_name="attendance_Technician", on_delete=models.DO_NOTHING) slot = models.ForeignKey('technician_management.TechnicianSlot', related_name="attendance_Slot", on_delete=models.DO_NOTHING) attendance_status = models.CharField(max_length=30, choices=ATTENDANCE_CHOICES, null=True) class Meta: db_table = "technician_attendance" Question what is wrong with my query: I need to filter out from TechnicianAssignment where in entries were "slot__slot_date" is current date and "__attendance_Technician__attendance_status__in" = ['Rejected', 'Absent', 'Someone else reported', 'Present'] there is only 1 entry in db with attendance status 'Present' but i am getting many output because of "__attendance_Technician__attendance_status__in" this filter. -
How to run Django admin site on Android
This is what am facing with with Django on my Android I'm using Pydroid on my phone. Python and Django are fully functional. But when I try to run Django admin site on Chrome it shows "Server error occurred. Contact administrator" and in the terminal it shows this error: storage/emulated/0/mysite $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 28, 2022 - 16:28:28 Django version 4.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C. [28/Apr/2022 16:28:45] "GET /admin/ HTTP/1.1" 302 0 [28/Apr/2022 16:28:55] "GET /admin/ HTTP/1.1" 302 0 Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/zoneinfo/_common.py", line 12, in load_tzdata return importlib.resources.open_binary(package_name, resource_name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 88, in open_binary package = _get_package(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 49, in _get_package module = _resolve(package) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/resources.py", line 40, in _resolve return import_module(name) File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line … -
Can't aggregate a DecimalField in Django
I have a queryset where I want to aggregate the fields amount which itself is a DecimalField. The target field is also a DecimalField. I get this error: django.core.exceptions.ValidationError: ["“{'amount__sum': Decimal('3821.02000000000')}” value must be a decimal number."] Why does it say it must be a decimal number even though it is a DecimalField? # models.py class Payment(models.Model): offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.ForeignKey(Period, on_delete=models.CASCADE) payroll_run = models.ForeignKey(Payroll, on_delete=models.CASCADE, null=True, blank=True) # is populated once the payroll run was created amount = models.DecimalField(decimal_places=2, max_digits=10) class Payroll(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) month = models.DateField() amount = models.DecimalField(decimal_places=2, max_digits=10) line_items = models.PositiveIntegerField() def test(): ... # Loop the companies for company in qs_companies: # Query all Payments of that company in that month qs_payments = Payment.objects.filter(offer__company=company).filter(month=period) # Create a payroll run instance payroll_run = Payroll.objects.create( company=company, month=next_payroll_run, amount=qs_payments.aggregate(Sum('amount')), line_items=qs_payments.count() ) payroll_run.save() ... -
How to have sequent numbers in django model
I have a model that represents a book and a model named chapter. models.py class Book(models.Model): title = models.CharField(max_length=255) book_summary = models.TextField() author = models.ForeignKey(Author, related_name='books', on_delete=models.DO_NOTHING) upload_date = models.DateField(auto_now_add=True) tags = models.ManyToManyField(Tag, related_name='books', blank=True) genre = models.ForeignKey(Genre, related_name='books', on_delete=models.PROTECT,) def __str__(self): return self.title class Chapter(models.Model): book = models.ForeignKey(Book, related_name='chapters', on_delete=models.CASCADE) chapter_num = # has to be consecutive text = models.TextField() I want to number each chapter so that I can order them. But I cannot implement that with AutoField because if I delete a chapter there will be 1, 3 ,4... and so on. How can I do this? -
Django DateField clashes with datetime.date instance: AttributeError: 'Period' object has no attribute 'strftime'
When I try to create a new model instance within a function I get the following error: TypeError: fromisoformat: argument must be str My first guess was the format of the date object but I pass a valid date object which also is the Django DateField format? # utils.py def create_payroll_run(): # Query all active companies qs_companies = Company.objects.filter(is_active=True) # Get the 1st of the month for the payroll run to be created next_payroll_run = date.today().replace(day=1) # Get the period instance period = Period.objects.get(period=next_payroll_run) # Loop the companies for company in qs_companies: # Query all Payments of that company in that month qs_payments = Payment.objects.filter(offer__company=company).filter(month=period) print(qs_payments) # Create a payroll run instance payroll_run = Payroll.objects.create( company=company, month=period, amount=qs_payments.aggregate(Sum('amount')), line_items=qs_payments.count() ) payroll_run.save() return payroll_run # Models.py class Payroll(models.Model): """ A table to store monthly payroll run information of companies """ # Relates to one company company = models.ForeignKey(Company, on_delete=models.CASCADE) month = models.DateField() amount = models.DecimalField(decimal_places=2, max_digits=10) line_items = models.PositiveIntegerField() class Period(models.Model): """ A table to store all periods, one period equals a specific month """ period = models.DateField() Full Traceback: import sys; print('Python %s on %s' % (sys.version, sys.platform)) import django; print('Django %s' % django.get_version()) sys.path.extend(['/Users/jonas/Desktop/salaryx_django', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm', '/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev']) if 'setup' in … -
How to read PSQL "explain" to improve Django query
I have a query in Django that ends up pulling about 3000 rows which are joined to another table. I've refactored as much of the query as possible to reduce joins, but I am trying to eek out additional performance from indexing. My initial (fumbling) attempts have improved things a little, but I'm butting up against the extent of my knowledge for database management. Thoughts on improving performance? Here's the explain: Sort Key: assets_deliverables.id -> Nested Loop (cost=0.43..34.15 rows=8 width=1212) -> Seq Scan on localization_language (cost=0.00..1.70 rows=1 width=89) Filter: (id = 1) -> Nested Loop (cost=0.43..32.37 rows=8 width=1123) -> Nested Loop (cost=0.29..31.10 rows=8 width=216) -> Seq Scan on assets_nodes (cost=0.00..9.31 rows=1 width=153) Filter: (upper((code_path)::text) ~~ '/WATCH%'::text) -> Index Scan using assets_deli_node_id_6e3b6b_idx on assets_deliverables (cost=0.29..21.78 rows=1 width=63) Index Cond: ((node_id = assets_nodes.id) AND (language_id = 1)) Filter: (((kind_id = 15) OR (kind_id = 19) OR (kind_id = 11) OR (kind_id = 24) OR (kind_id = 27) OR (kind_id = 34) OR (kind_id = 24) OR (kind_id = 17) OR (kind_id = 16) OR (kind_id = 34) OR (kind_id = 19) OR (kind_id = 11) OR (kind_id = 27) OR (kind_id = 15) OR (kind_id = 34) OR (kind_id = 13) OR … -
Django rest framework jwt {"detail": "You do not have permission to perform this action."}
I am trying to make a request using django-rest-framework and django-rest-framework-jwt but The response that I get detail": "You do not have permission to perform this action." views.py class Test(generics.RetrieveAPIView): permission_classes = [IsAuthenticated] authentication_classes = [] queryset = User.objects.all() def get(self, request): return response.Response({"test": "Test "}, status=status.HTTP_200_OK) urls.py from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token from .views import Test urlpatterns = [ path('', Test.as_view(), name='test'), path('token/', obtain_jwt_token, name='token_obtain_pair'), path('token/refresh/', refresh_jwt_token, name='token_refresh'), ] settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_GET_USER_SECRET_KEY': None, 'JWT_PUBLIC_KEY': None, 'JWT_PRIVATE_KEY': None, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': timedelta(days=5), 'JWT_AUDIENCE': None, 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_AUTH_COOKIE': None, } and the request that I made: >curl -X GET http://127.0.0.1:8000/users/ -H 'Authorization: Token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMCwidXNlcm5hbWUiOiJoYXNhbm1iaWxhbDE5OThAZ21haWwuY29tIiwiZXhwIjoxNjUxNTkxMDYxLCJlbWFpbCI6Imhhc2FubWJpbGFsMTk5OEBnbWFpbC5jb20iLCJvcmlnX2lhdCI6MTY1MTE1OTA2MX0.bvmtH6mnItBjwKkvaNU5eMXlEyk2ZAytMWzhEE_Ibhs' Note: I've used django-rest-framework-simplejwt and got the same problem... -
Failing to deploy a Django web app to AWS beanstalk
I am trying to deploy A django app to beanstalk and I get some errors related to python and requirements.txt and I can't figure out what to do, Any help is appreciated. here are the errors I get: (the logs are in pastebin bellow) ERROR [Instance: i-0e7826c4558b1d21a] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2022-04-28 15:13:52 UTC+0000 ERROR Your requirements.txt is invalid. Snapshot your logs for details. logs: https://pastebin.com/g1uZLqur -
Struggeling with Twilio login - sms auth in Django
So I built a login with sms verification which works fine. The problem is that It's not possible to enter 14 digits (includes "+" symbol) in my admin user-settings. The following error applies when I try to save the user-settings in my admin-console: (1406, "Data too long for column 'phone_number' at row 1") So I tried to upset the max_lenght of (my phone number) to 20 instead of 12, but it still does not send a sms automatically. ## models.py ### # imports class Costom_User(AbstractUser): phone_number = models.CharField(max_length=20) Appart from this error I also receive the following error when I try to go through my login verification : TwilioRestException at /verify/ Unable to create record: The 'To' number "my phone number" is not a valid phone number. I think Twilio only accepts E.164 numbers and so on I need to change the length of possible phonenumber inputs for a user, but I dont know how I shall do that. I am glad for any help, as I said the code works fine, when I input my phone number in the code instead of leaving it as parameter the sms is send, the problem which I need to solve is the … -
How to filter using a function in the left side of an expression?
It is possible to execute a filter with the Django ORM using the Replace function on the left side? It would be to achieve something like this query: select * from my_table where replace(field, '-', '') = 'value' If I try to use the function at the right side, inside the filter function, I'm receiving this error: keyword can't be an expression -
how to get adress from certain selected object?
So I have model with name and adress value. Is it possible to reveal adress in the table after i select certain value of "library". For example - i select some name from option tag and after that adress adds itself in thr table class VideoLibrary(models.Model): shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') function revealMore() { var blank_text = document.getElementById('blank_option'); // var text_area = document.getElementById('text_area') if (this.value !== blank_text) { var library = this.value; text_area.value = library; } } {% if shop_name %} <select name="shops" id="shop_select" class='box'> <option value="" disabled selected id='blank_option' onchange='revealMore()' name='select_option'></option> {% for library in shop_name %} <option id='library_element'>{{library.shop_name}}</option> {% endfor %} <table> <tr> <th>Adress</th> </tr> <tr> <td id='adress'></td> </tr> </table>