Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send push notification request from android app to django
I have created a sip calling app in android (java).. But it is only able to call if app is open.. When app is closed the registration get destroyed.. I want to invoke the registration using push notification when i call.. I have setup the FCM service for sending push notifications. I am sending device token and username to django where django saves the device taken in "subscribers" table .. But I don't know how to send request to send push notification from android app to django... Please help -
Django connect SQL Server using active directory user
I'm using Django and mssql-django backend to connect to SQL Server. No problems to connect to SQL Server when using sql login. But, when I try to connect using AD user, I get exception: django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server] Login failed for user 'DOMAIN\\myuser'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'DOMAIN\\myuser'. (18456); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") My database settings in settings.py are: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ.get('DB_NAME', 'djangodb'), 'USER': os.environ.get('USER', 'DOMAIN\myuser'), 'PASSWORD': os.environ.get('USER_PASS', 'mypass'), 'HOST': os.environ.get('HOST', 'server.blabla.net'), 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } What I am doing wrong? -
Override top bar in Django admin
I'm trying to override admin/base_site.html to display the top nav bar from the main site. I tried using {% block nav-global %} and adding my navbar there, but it just appends to the existing header. How would I delete the top header all together to replace with my own template? {% extends 'admin/base_site.html' %} {% block nav-global %} {% include 'base/navbar.html' %} {% endblock %} I've considered reconstructing the template as my own by not extending the original admin/base_site.html, however, I can't find the blocks I'd need in the docs anywhere. -
How can I set that when user is admin only then he can view a specific html page in Django
I've a html page called admin_dashboard.html. So, there is a button in the navbar called Admin Dashboard only admin can get this button. If admin click this button he will go to the admin_dashboard.html but a staff can also go to that page by using urls which is http://127.0.0.1:8000/admin_dashboard. So I want that a if staff manually types this url and tries to go to the admin_dashboard.html it will throw an error. here is my code for that button {%if user.is_superuser%} <li><a class="dropdown-item" href="admin_dashboard">Admin Dashboard</i></a></li> {%endif%} urls.py: path("admin_dashboard", views.admin_dashboard, name='admin_dashboard') views.py @login_required(login_url='/login') def admin_dashboard(request): return render(request,'admin_dashboard.html') -
Django array field filter
In my case customer filed are array filed customer = ArrayField(models.TextField(),default=[]) my model look like id customer 1 {1,2,3} 2 {4,2,5} 3 {1,8,9} i want to filter my model by {5,8} output will be 2th ,3th row -
Django, DRF: How to correctly divide the number of pages in a homemade pagination that does not issue count queries
I have created a pagination that does not issue a Count query as shown below, but This code uses sys.maxsize, so the number of pages is 461168601842738816, and if the data does not exist, raise NotFound("No data found for this page") is performed. but how do I make next empty on the page before that one? I need to determine whether to load the next page with or without next in the frontend infinite scroll. class CustomPaginatorClass(Paginator): @cached_property def count(self): return sys.maxsize class CustomPagination(PageNumberPagination): django_paginator_class = CustomPaginatorClass def paginate_queryset(self, queryset, request, view=None): page_size = self.get_page_size(request) if not page_size: return None paginator = self.django_paginator_class(queryset, page_size) page_number = int(self.get_page_number(request, paginator)) data = super().paginate_queryset(queryset, request, view=view) if not data and page_number > 1: raise NotFound("No data found for this page") return data def get_paginated_response(self, data): return Response( OrderedDict( [ ("next", self.get_next_link()), ("previous", self.get_previous_link()), ("results", data), ] ) ) -
Pycharm Debug mode with docker
Starting Pycharm debug mode occurs the following error. python: can't open file '/opt/.pycharm_helpers/pydev/pydevd.py': [Errno 2] No such file or directory It was working until this morning. Pycharm pycharm-2021.1.1 -
I can't get username form django I got only None like on the photo
I cna't get user, I got None intend od username, I don't know how to solve this problem... {% for wiadomosc in wiadomosci %} <li> <strong>{{ wiadomosc.author }}</strong> ({{ wiadomosc.created_date }}): <br /> {{ wiadomosc.tekst }} {% if wiadomosc.author.name == user.name %} &bull; <a href="{% url 'blog_app:edytuj' wiadomosc.id %}">Edytuj</a> &bull; <a href="{% url 'blog_app:usun' wiadomosc.id %}">Usuń</a> {% endif %} </li> {% endfor %} website: Wiadomości Lista wiadomości: None (Feb. 4, 2022, 2:11 p.m.): Czwarta wiadomość edytowana • Edytuj • Usuń None (Feb. 4, 2022, 2:54 p.m.): Piąta wiadomość edytowana • Edytuj • Usuń Strona główna models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Wiadomosc(models.Model): """Klasa reprezentująca wiadomość w systemie""" tekst = models.CharField('treść wiadomości', max_length=250) created_date = models.DateTimeField('data publikacji') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: verbose_name = u'wiadomość' # nazwa obiektu w języku polskim verbose_name_plural = u'wiadomości' # nazwa obiektów w l.m. ordering = ['created_date'] # domyślne porządkowanie danych def __str__(self): return self.tekst -
Could I send serialized data in Django to JSON dataframe chart.js?
below I send example of candlestick charts.js date structure - (JSON type): <script> const data1 = luxon.DateTime.fromRFC2822('15 Dec 2021 00:00 GMT'); const date2 = luxon.DateTime.fromRFC2822('16 Dec 2021 00:00 GMT'); const data = { datasets: [{ data: [ { x: data1.valueOf(), o: 1, h: 0.75, l: 0.75, c: 1.25 }, { x: date2.valueOf(), o: 1.20, h: 1.5, l: 0.75, c: 0.9 } ], }] }; // config const config = { type: 'candlestick', data, options: {} }; // render init block const myChart = new Chart( document.getElementById('myChart'), config ); </script> It seems similar to serializers? So I wonder if it is possible to send it in context to make this json like data And seems... const data = {{data}} doesn't work... :) -
Django SoftDelete Model And Model Manager Inheritance
i have a soft delete model BasicModel and a user model Paddy. the user model's objects isn't inheriting the BasicModel's object manager core app's models.py class BasicModelQuerySet(models.QuerySet): def delete(self): return self.update(is_deleted = True, deleted_at = timezone.now()) def erase(self): return super().delete() class BasicModelManager(models.Manager): def get_queryset(self): return BasicModelQuerySet(self.model, self._db).filter(is_deleted = False) # Base Application Model class BasicModel(models.Model): """ Base application model to add default fields to models without having to write repeated code. """ deleted_at = models.DateTimeField(blank = True, null = True,) is_deleted = models.BooleanField(default = False,) objects = BasicModelManager() class Meta: abstract = True # extras ... accounts app's models.py class PaddyManager(BaseUserManager): def create_user(self, first_name, last_name, email, password, **extra_fields): # user creation ... skipping code pass def create_superuser(self, first_name, last_name, email, password, **extra_fields): # super user creation ... skipping code pass # BasicModel from core.models.py class Paddy(BasicModel, AbstractUser): # model fields objects = PaddyManger() <-- HOW TO MAKE THIS USE BasicModel's Model Managers AND STILL USE CREATE_USER / CREATE_SUPERUSER METHODS OF PaddyManager() #extras my challenge is how do i get the user model to only return non-deleted objects when i call User.objects.all() and still be able to call the create_user or create_superuser methods of PaddyManager? -
How to get Django Whitenoise to 500 when Debug is True
I'm trying to get our Django app to throw 500s when an asset is not available - rather than somewhat silently throwing 404s. We want this so that our end-to-end tests catch an asset missing before it goes to prod and starts failing. I have WHITENOISE_MANIFEST_STRICT set to True, and I believe that Whitenoise is working - I'm using the --nostatic flag, and see the WHITENOISE_MAX_AGE in the Cache-Control Response Headers (although the assets themselves don't have the hash that we see in production or when Debug is set to false). However I'm still getting 404s for an asset that doesn't exist. Unfortunately we can't use DEBUG = False because the tests themselves depend on Debug being true, so any advice would be super appreciated! -
how to extract actual youtube videos urls through api like below links
i am try to fetch the actual URL of each video from you-tube channel. please help me any one. https://jsoncompare.org/LearningContainer/SampleFiles/Video/MP4/Sample-MP4-Video-File-Download.mp4 https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3 -
Django rest framework Adding Points Put Request
I wanna create an API PUT endpoint that adds/subtracts point to an answer (just like on forums) but i want to limit it so that if user has upvoted, he cant upvote twice. I tried doing something like this logically, but i keep getting an error with voters. I think its because of ManyToMany field, but i dont know why it happens. Do you have any idea why is that? class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) addition_done = models.BooleanField(default=False) subtraction_done = models.BooleanField(default=False) voters = models.ManyToManyField('users.CustomUser', default=None, blank=True, related_name='voters') Views class AddPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = AddPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) def perform_update(self, serializer): addition_done = serializer.data.get('addition_done', False) number_of_points = serializer.data.get('number_of_points',) voters = serializer.data.get('voters',) if not addition_done and self.request.user not in serializer.voters.all(): number_of_points += 1 addition_done = True voters.all = self.request.user serializer.save(addition_done=addition_done, number_of_points=number_of_points, voters=self.request.user) serializer class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points', 'addition_done', 'voters',) i keep getting the AttributeError: 'AddPointsSerializer' object has no attribute 'voters' -
django html: click form button in sequence
I have a form for user to fill in some data. at the bottom there are two buttons: "Get Price" and "Order Now". the user must click "Get Price" button in the first to get the price, then click "Order Now" button to redirect to a new page. However, we cannot control user behavior, some will directly click the "Order Now" button. So for "Order Now" button configuration, is there a way to enable sequential clicks ("Get Price" -> "Order Now"), i.e. when user click "Order Now" button, the program will click "Get Price" button first, then "Order Now". <form method="POST" hx-post="{% url 'OnlinePricing' %}" hx-target="#pickup_address" hx-target="#delivery_address" hx-target="#distance" hx-target="#charge" @submit.prevent> {% csrf_token %} <div> <label for="s1">pickup_address:</label> <input type="text" name="pickup_address" value="" required="required" /> <br /><br /> </div> <div> <label for='s1'>delivery_address:</label> <input type="text" name="delivery_address" value="" required="required" /> <br /><br /> </div> ... <div> <span id="pickup_address"> {{ pickup_address }} </span> </div> <div> <span id="delivery_address"> {{ delivery_address }} </span> </div> <div> <span id="distance"> {{ distance }} </span> </div> <div> <span id="charge" > {{ charge }} </span> </div> <button type="submit">Get Price</button> <button type="submit" style="margin-left:10px;" onclick="location.href = '/order/'">Order Now</button> </form> -
Why after deploying Django application on Elastic Beanstalk my website doesn't work?
After deploying my application to Elastic Beanstalk, the website doesn't work as expected. I don't know why. This is the database configuration: enter image description here This is the website: enter image description here -
Keep getting this error when trying to render my custom HTML form
Here is the error I got when I removed the else clause from my views.py file. File "C:\Users\david\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 309, in check_response raise ValueError( ValueError: The view register.views.register didn't return an HttpResponse object. It returned None instead. I'm guessing that I got this error as there is no else clause, which I need to have but if I have it in my views.py file I get another error. Here is my view file: from django.shortcuts import render,redirect from django.contrib.auth.models import User, auth def register(request): if request.method == 'POST': first_name = request.POST['first_name'], last_name = request.POST['last_name'], dob = request.POST['dob'], email = request.POST['email'] newuser= User.objects.create_user(first_name=first_name,last_name=last_name, email=email) newuser.save() print(request.POST) return redirect('/home') I originally had an else clause at the bottom of this but that caused a different error. Here is that clause: else: return render('/register/userinfo.html') And the error I get with it in place: File "C:\Users\david\OneDrive\Desktop\Django\Sub\register\views.py", line 4, in render return render(request,'/register/userinfo.html') TypeError: render() takes 1 positional argument but 2 were given Any idea as to what may cause this bottom error? -
Problems adapting multiple form wizard with a formset
I have a question, what happens is that I am using 3 formsets in a multiple way that appear on the same page. But I don't know how to save the data of each form. I've seen them recommend django-multipleformwizard and django-formtools-addons but at no time do I see them use them for a formset. I'm going to add my view to know how I can adapt it. views.py def create_Presupuestos(request): extra_forms = 1 ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20) PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20) presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) presupuestosfotosform=PresupuestosFotosForm(request.POST or None) if request.method == 'POST': formset = ParteFormSet(request.POST, request.FILES) manoObra_formset = ManoObraFormSet(request.POST, request.FILES,prefix='manoobra') pagos_formset = PagosFormSet(request.POST, request.FILES, prefix='pagos') #formset = ParteFormSet(request.POST, request.FILES,prefix='__form') if formset.is_valid() and manoObra_formset.is_valid() and pagos_formset.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') else: formset = ParteFormSet() manoObra_formset = ManoObraFormSet(prefix='manoobra') pagos_formset = PagosFormSet(prefix='pagos') presupuestosfotosform = PresupuestosFotosForm(request.POST or None) return render(request,'Presupuestos/new-customer.html',{ 'presupuestosclientesform':presupuestosclientesform, 'presupuestosvehiculosform':presupuestosvehiculosform, 'presupuestosparteform':presupuestosparteform, 'presupuestosmanoobraform':presupuestosmanoobraform, 'presupuestospagosform':presupuestospagosform, 'presupuestosfotosform':presupuestosfotosform, 'formset':formset, 'manoObra_formset':manoObra_formset, 'pagos_formset':pagos_formset }) -
Getting request.data as an empty dictionary
I have a viewset like the follwing class DummyViewSet: def create(self, request, *args, **kwargs): variable_a = 5 return another_api_end_point(request, variable_a) ---> request.data: {"a":"value1", "b": "value2"} @api_view(['POST']) another_api_end_point(request, variable_a) print(request.data) ---> request.data: {} print(variable_a) ---> variable_a: 5 return "Some Response" Why I can able to see variable_a's value as it is but request.data as empty? Debugging it from hours now. If anyone knows the reason for it, please revert. It would be a great help. -
Change the rows with the same cell value in the same color in HTML table - Django project
I created a table in my html file for my Django project, and the raw data is based on the following list (It's a very long list, so I only list a few lines): mylist=[{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65}, ... {'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}] My Html file: <table class="table table-striped" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>StartDate</th> <th>ID</th> <th>Name</th> <th>Days</th> </thead> <body> {% for element in mylist %} <tr> <td>{{ element.StartDate}}</td> <td>{{ element.ID }}</td> <td>{{ element.Receiver }}</td> <td>{{ element.Days }}</td> </tr> {% endfor %} </tbody> </table> I want to make all the rows with the same ID value the same color. Please advise what I should add into the <td>{{ element.ID }}</td>. Thank you! -
dajngo qrcode FileNotFoundError
I am trying to save qrcode image in django mode but when i save am getting the error saying Errno 2] No such file or directory: '/home/mecatheclau/django/ines_campus/main/static/media/degree/qrcode/2.png' Django code def save(self, *args, **kwargs): if not self.qrcode: import qrcode from django.core.files import File from django.conf import settings as appsettings from django.core.files.uploadedfile import InMemoryUploadedFile qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=2, border=0, ) qr.add_data("https://digitalsnatch.ines.ac.rw/degree/%s/preview/"%(self.pk)) qr.make(fit=True) img = qr.make_image() filename = "degree/qrcode/"+str(self.pk)+".png" imagepath = appsettings.MEDIA_ROOT+"/degree/qrcode/"+str(self.pk)+".png" img.save(imagepath) # self.qrcode.save(filename, imagepath, save=True) self.qrcode = filename super().save(*args, **kwargs) img.save(imagepath) returning can't proccess file what am doing wrong -
How to start wirh custom result backend in celery?
In advance im sorry if I'm not so specific with my question. I want to create a custom result backend but I don't know how to start and the documentation that I found is not very clear to me, does any of you know of any example or document that can guide me? I was thinking on create a class and assignt it in my celery.py like this RESULT_BACKEND='my_class' But I doubt this works, any advice will be really helpful. Thanks -
Django rest API make sure email is verified before giving API token
I'm making a Django REST framework for a JSON API, and I want to authenticate Users with a token (so, API request will be something like .../api/dosomething/{user} Token: ...). Django REST documentation shows how to expose an endpoint for token generation with username/password - however, I'd like to make sure that the email is verified before giving out the token. I don't want to send the token itself to the email, email verification should either be a link or a 6-digit code. Is there a default way of doing this in Django? I was thinking of doing the following - on registering at api/register, user provides username/email and password, account gets created (but no token so they can't use the API). To get the token, a user needs to hit api/generate_token endpoint with username and password. This will generate a random 6-digit code in the backend, store/update the user/code/created_at in the custom model, send an email with the code, and return a message "please verify your email with 6 digit code". There will be an endpoint api/verify_email_token which takes username and verification code. If user/code pair is in the DB and created in the last 30min, it'll create and return … -
how to delete a session in django through python shell?
As we know we can delete cache through python shell by typing python manage.py shell from django.core.cache import cache cache.clear() is there any way to delete django sessions through shell? -
How to change the validation error color and position in Django?
I am new to Django. I am trying to make a simple form to match the password. However, when I enter different passwords and press the Save button I get a black validation error above the form. I want to change the error color and position to appear in red color beside or below the control. Here newuser.html: {% block content %} <form method="POST"> {% csrf_token %} <table> {{frmNewUser.as_table}} {% for error in frmNewUser.password.errors %} {% comment %} I tried frmNewUser.non_field_errors too {% endcomment %} <p>{{error}}</p> {% endfor %} </table> <input type="submit" name="Save" value="Save" colspan=2> </form> {% endblock content %} Here forms.py: class NewUserFrom(forms.Form): username = forms.CharField(max_length=50, widget=forms.TextInput) password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput) name = forms.CharField(max_length=50, widget=forms.TextInput) email = forms.EmailField(max_length=50, widget=forms.EmailInput) def clean(self): cleaned_data = super().clean() pwd = cleaned_data.get('password') cof_pwd = cleaned_data.get('confirm_password') if pwd and cof_pwd: if pwd != cof_pwd: raise forms.ValidationError('Password is not match.') return super().clean() Here views.py: from django.shortcuts import render from django.http import HttpResponse, request from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc from .forms import NewUserFrom def newUser(request): form = NewUserFrom(request.POST) if not form.is_valid(): context = {'frmNewUser':from} return render(request,'login/newuser.html', context) return render(request, "login/welcome.html") -
Python django how i can prevent the duplicate entry of studnumber,email,username(unmae) in registration
Python django how i can prevent the duplicate entry of studnumber,email,username(unmae) in registration? i use this code before when it us one full name its work but when I divide it to (nmane),(mname),(nnmae), it always saying duplicate record. even their is no similar record on db MODELS.py from django import forms from django.db import models class newacc(models.Model): studnumber=models.IntegerField() fname=models.CharField(max_length=150) mname=models.CharField(max_length=150) lname=models.CharField(max_length=150) age=models.IntegerField() gender=models.CharField(max_length=1) uname=models.CharField(max_length=150) email=models.CharField(max_length=150) pwd=models.CharField(max_length=150) contact=models.IntegerField() class Meta: unique_together = ('studnumber','email','uname') class NewACCForm(forms.ModelForm): class Meta: model = newacc fields = "__all__" Views.py from django.shortcuts import redirect, render from register.models import newacc from django.contrib import messages from django.db.models import Q#disjunction sa email and uname: from register.models import NewACCForm def Unreg(request): if request.method=='POST': form = NewACCForm(request.POST) if form.is_valid(): form.save() messages.success(request,"The New User is save !") else: messages.error(request, "Duplicate Reccord.") return render(request,'Registration.html')