Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: unsign values without original value
I am working on a Django app and using Django's Signer to sign my pk's in urls this is my code from django.core.signing import Signer signer = Signer() value = signer.sign(1) this gives me 1:4CrdZAT9VZfsW3ZdFf1Ud_zwP_3JRTP6xwwFzseK550' and then I am using this value in my templates like <a href="edit/1:4CrdZAT9VZfsW3ZdFf1Ud_zwP_3JRTP6xwwFzseK550/">Edit</a> However, I can strip the value to get the only signed value but when I need to unsign it back to use in my query, it needs the original value to unsigned. How can I unsign this value without using the original value? I don't want my URLs to look like this edit/1:4CrdZAT9VZfsW3ZdFf1Ud_zwP_3JRTP6xwwFzseK550/ (Remove original pk with ':'). Thanks for any help. -
django rest-frame work jwt athentications fails although I sent correct token
I can receive valid access and refresh token after I logged in to my login endpoint API. for some views, I have given is_authenticate permission where after providing a valid token, the user can get access to that view. the problem is although I provide a valid token, still it tells me { "detail": "Authentication credentials were not provided." } how can I solve the issue. here is my code. settings. py INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'rest_framework' , 'rest_framework_simplejwt.token_blacklist' , 'bd_api' , 'op_api' , 'drf_yasg' , 'django_filters' , 'corsheaders' , ] SITE_ID = 1 REST_FRAMEWORK = { 'NON_FIELD_ERRORS_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } # for jwt SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME' : datetime.timedelta(minutes=3) , 'REFRESH_TOKEN_LIFETIME' : datetime.timedelta(days=1) , } # swagger SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS' : { 'Bearer' : { 'type' : 'apiKey' , 'name' : 'Authorization' , 'in' : 'header' } } } views.py class op_ViewSet(viewsets.ModelViewSet) : permission_classes = (permissions.IsAuthenticated,) queryset = Op.objects.all().filter() serializer_class = op_Serializer authentication_classes = [TokenAuthentication , SessionAuthentication , BasicAuthentication] # pagination_class = PageNumberPagination # pagination_class = StandardResultsSetPagination filter_backends = [DjangoFilterBackend , SearchFilter , OrderingFilter] filter_class = op_filter ordering_fields = ['close_date' , ] ordering = … -
Use LIMIT with Django Models on aggregate function
For measurement purposes I would like to limit the QuerySet that comes back from DjangoModels. I want to check how much time it takes to get a QuerySet with a specific amount of objects. Here I try to summarize my problem. In SQL: SELECT author, AVG(books) FROM books LIMIT 10000 I know how do aggregate in Django but not to combine. My idea is now to combine my Query like this: Books.object.all()[:10000].aggregate(Avg('books')) This doesn't work, because the object that will be returned is the result of the aggregation I know. If I send the query Books.object.all()[:10000] it works. Also the aggregation like this: Books.object.aggregate(Avg('books')). But is there a way to send a query like this with djangoModels? Thank you in advance. -
Django Template Countdown
I want to countdown the remaining days before the deadline ends and display in Label/Ageing. I have a javascript but when I get the date from my database always null value. Anyone Can give me an idea on how to get the list of Date value order by ID to make Countdown.Thank you! This is my javascript code but output always "EXPIRED" and Ageing value is "Null" <script> var Ageing = new Date({{ object.Date_resolved_inital }}); var x = setInterval(function() { var now = new Date().getTime(); var distance = Ageing - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); document.getElementById("days").innerHTML = days + "d "; if (distance < 0) { clearInterval(x); document.getElementById("days").innerHTML = "EXPIRED"; } }, 1000); </script> Django Views class CS(ListView): def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) model = log template_name = 'CS/pending.html' Models.py Date_resolved_inital = models.DateTimeField(auto_now_add=False, blank=True, null=True) Table The Countdown value appears in Ageing column by ID Database This are the value to compute the Countdown, date value comes from API -
How to calculate the number of non-zero fields in a row and using that make a query in Django
My model from django.db import models class Books(models.Model): field_1 = models.IntegerField(default=0) field_2 = models.IntegerField(default=0) .......................... field_6 = models.IntegerField(default=0) Now I want to make a query to count the number of Books where exactly 3 fields are non-zero. -
How to debug built in django code with breakpoint
Is there a way to set breakpounts in Django default codes like the ones at django/cobtrib/auth/views.py I tried Import pdb And then breakpoint () But it simply ignores it. Print() does work. Any help is appreciated. -
Django User with that username already exists
My aim - Trying to create an authentication system in Django, and allows user to signup again with same username if their account is not activated. If an user try to register with a certain username and that username already exists then update that user with this current user. My Approach - I have created a form using "UserCreationForm" and defining my own methods to validate the form, and allows the user even if username already exists but user.is_active = False. Code forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import User class SignupForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') name = forms.CharField() institution = forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') user = None try: try: user = User.objects.get(username=username) print("is user active username", user.is_active) except ObjectDoesNotExist as e: pass except Exception as e: raise e if not user: pass elif not user.is_active: pass else: raise forms.ValidationError("This Username Already Exists") except Exception as e: raise e return username class Meta: model = User fields = ('username', 'email', 'institution', 'password1', 'password2') views.py from .forms import SignupForm def regUser(form): ''' It will save Django user and student. It recieves form.cleaned_data as argument ''' print("reg user line 1") user = User.objects.create_user(username=form['username'], email=form['email'], password=form['password1'], … -
django reset sequence for all autofields in a project
In my django project, I have a lot of models. The thing is, I want to make sure the primary key field of all these models starts with 10000 and increments from there. I am using postgresql at the backend. I know that I can run custom sql migrations for every sequence of my models. But when there are a lot of models, this process becomes not so much applicable. Any alternatives to this? thanks! -
Django how to list customers in the sidebar
I created a system with Django. A user has several customers. The sidebar is in the base.html file. I created a view for the sidebar but It is working only in homepage. When I open a different page, it dissapears. How can I fix it? views.py def base(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(companyName=userP[0].comp_name) return render(request, 'base.html', {'customer_list': customer_list}) base.html <ul> <li class="header-menu"> <span>Customers</span> </li> <li class="sidebar-dropdown"> {% for customer in customer_list %} <a href="#"> <i class="fa fa-building"></i> <span>{{customer.name}}</span> </a> <div class="sidebar-submenu"> <ul> <li> <a href="/customers/{{ customer.id }}/update"> Update</a> </li> <li> <a href="#">Analyses</a> </li> </ul> </div> {% endfor %} </li> </ul> -
Unable to create Django Project
I am trying to create a project in Django using CLI command django-admin startproject MySQLCRUD. But I am getting an error ie: 'django-admin' is not recognized as an internal or external command, operable program or batch file. I tried various solution but couldn't get the error resolved. I already have Python and Django installed in my machine. Attached are the screenshots any solution please ? -
Add extra parameter to serializer.data
I get three fields from rest api i.e name , phone number and email id in serializer but i want to store the datetime as well when i receive the api . in database i have created 4 columns i.e name , phone number, email id , created data . How can i add current date timeparameter to my serializer.data before saving it to posgtresql database table "table_userdetails". please help me with the answers because i am new to it Below is the code for views.py @api_view(['GET', 'POST']) def UserInfo(request): if request.method == 'GET': snippets = UserDetails.objects.all() serializer=UserDetailsSerializer(snippets, many=True) return Response(serializer.data) elif request.method =='POST': context=datetime.datetime.now() serializer = UserDetailsSerializer(data=request.data) print("serializer",serializer) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Below is the code for Models.py class UserDetails(models.Model): name=models.CharField(max_length=255) mobile_no=models.CharField(max_length=255) email_id=models.CharField(max_length=255) user_id=models.IntegerField(primary_key=True) created_date=models.CharField(max_length=255) class Meta: db_table=table_userdetails def __str__(self): return self.response Below is my code for serializer.py class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model=UserDetails fields='__all__' i added context part in post method but how to add in serializer.data .please help me with the solution and what am i doing wrong here .any kind of help is appreciated . Thank you -
<class 'segno.QRCode'> object has no attribute to_artistic (Error on Django not local device)
I am getting this error: <class 'segno.QRCode'> object has no attribute to_artistic My code (url_used is fine): qr = segno.make("sup", error='h') logo_open = urlopen(url_used) buffer = io.BytesIO() qr.to_artistic( background=logo_open, target=buffer, scale=10, border=3, kind='png', finder_dark="black", dark="white") I get this error on Django but don't get it on my local computer. Thanks! -
How to integrate Audio, Video Conferencing using Python & Django
Hello Everyone, I am creating one E-learning Software like BYJU'S where I want to have the functionality for Chat, Audio & Video Conferencing and whiteboard more similar to Zoom. Please take a look for my requirements below: Once Students/Teachers logged-in then they will be able to see their dashboard. Teachers can conduct the classes and there will be Audio, Video chat and Whiteboard similar to Zoom App. For conducting the classes Teacher will create the Room and send the Room Id to the students. Once Students put that Room Id then will jump to the Room where all the functionality will be there like Audio, Video, Chat(for Q&A) and Whiteboard. I'm trying with Open meetings but unable to get a clear idea for integrating these features. Please let me know what are the third party APIs or vendors are available with Django to have this functionality in my Software. -
Django rest framework hide columns logic
I have two tables (user_type and raw_data) while showing raw_data in list method user_type needs facility to hide raw_data columns(i.e. cid, eup, etc) explicitly how to do that? -
how to implement Django and electron.js as a Standalone local app
Does anyone tried out Django + electron.js as standalone local app running on localhost . all the material I can find are some what outdated or just hypothesis. There are some example with Flask . Appreciates your time -
Can we upload and access the uploaded image with just using the ImageField?
We are having trouble while accessing an uploaded image. The idea was to have the ImageField on its own without the CharField, but then we aren't able to find a way to access the uploaded image without the CharField input. # models.py class upload(models.Model): name = models.CharField(max_length=50) main_Img = models.ImageField(upload_to='images/') Here we want to remove the name field. # forms.py class UploadForm(forms.ModelForm): class Meta: model = upload fields = ['name','main_Img'] But then, as we want to access the uploaded image in the views.py folder for further processing on the uploaded image, we are relying on the name field.(uploads = upload.objects.get(name=a)) # Create your views here. def upload_view(request): if request.method == 'POST': form = UploadForm(request.POST,request.FILES) a=request.POST.get("name") if form.is_valid(): form.save() uploads = upload.objects.get(name=a) imgpath=uploads.main_Img.path request.session['imgpath'] = imgpath request.session['imgpt']= a #sr(imgpath) tf=is_grey_scale(imgpath) if tf==False: return redirect(rgb_view) else: return redirect(bw_view) else: form = UploadForm() return render(request, 'upload_image_form.html', {'form' : form}) Is there a way to exclude the name field and yet be able to access the image? If so, how can we do it? My team and I are new to Python and Django in general, so we are pretty confused at this point. Thanks in advance :) -
django.db.utils.ProgrammingError: relation "..." does not exist
I want my User objects in Django to be linked to a Client object (which I create). To do so I extend the User model with a one-to-one link with a Profile class (which I create) class Profile that links User & Client. I followed the instructions from https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html So far so good. However when I create a User object I dont have access by default to I want my User objects My models.py: from django.contrib.auth.models import User [...] class Client(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) [...] class Profile(models.Model): need_setup = Client.objects.get(name='NEED TO ADD CLIENT IN ADMIN > PROFILES') user = models.OneToOneField(User, on_delete=models.CASCADE) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() The problem comes when I make my migrations / runserver (my app is called 'dashboard'): django.db.utils.ProgrammingError: relation "dashboard_client" does not exist LINE 1: ...nque_id", "dashboard_client"."date_creation" FROM "dashboard... because of the need_setup = Client.objects.get(name='NEED TO ADD CLIENT IN ADMIN > PROFILES') (no problems if I comment it out). I can work around the problem by manually creating a client in the db called 'NEED TO ADD CLIENT IN ADMIN > PROFILES' and then run my migrations … -
here the after the user is logged in then he can rate the movie and he can rate it only once
here i want to join the two tables and i want that once the user is logged in then he/she can rate a movie and only one user can rate the movie and if the same user tries to rate it again then it should show an error message i have used knox for 3rd party authentication and i want to join the movie and rating table models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator, MaxValueValidator class Movie(models.Model): title = models.CharField(max_length=128) director = models.CharField(max_length=128) added_by = models.ForeignKey(User, related_name="movies", on_delete=models.CASCADE, null=True) added_at = models.DateTimeField(auto_now_add=True) # rating=models.IntegerField() class Meta: db_table = "Movie" class Rating(models.Model): movies=models.CharField(max_length=128) rating = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(5)]) class Meta: db_table = "Rating" Views.py from rest_framework.response import Response from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAuthenticated from knox.models import AuthToken from TestApp.models import Movie, Rating from TestApp.serializer import UserSerializer, RegisterSerializer, LoginSerializer, MovieSerializer, RatingSerializer from django.shortcuts import render # , RegisterSerializer, LoginSerializer, MovieSerializer class UserAPIView(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user class RegisterAPIView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer … -
For Loop in Object_list where BooleanField value is true
Suppose I have an Announcement model that contains is_important = models.BooleanField() How do I select rows with is_important = True only in for loop? As I want to do a bootstrap carousel for all important announcements. Or is there another way of doing it aside from for loop in object_list? -
Apple's MusicKit JS library example runs fine when rendered by Node.js, fails with Django
For three hours, I've been scratching my head over this. Apple's MusicKit uses JWT tokens to authenticate. When I npm start this Node.js example project, I can generate the JWT token, and then authorize Apple Music and collect the user token in response. This works when executing from localhost:8080. Here is a successful pop-up window. When I launch my Django server locally which also generates valid JWT tokens, running the same exact HTML code with a fresh JWT token, I receive this from Apple: "Problem Connecting: There may be a network issue." The only error on Apple.com's authorization page, is this: vendor-2c0b12a9762d9af673e21ccd8faf615e.js:2325 Error while processing route: woa Failed to construct 'URL': Invalid URL TypeError: Failed to construct 'URL': Invalid URL I have confirmed that both applications are generating valid JWT tokens. I can use the tokens generated in my Django application with Postman directly with Apple API, as well as my token from the Node.js app. I have tried: Using JWT token from Django in the Node.js app -- works Using JWT token from Node.js app in Django -- fails still Allowing all hosts to Django Allowing all CORS traffic to Django Hosting page on an HTTPS valid cert. domain … -
Django removes "@" and other special character from file name
I want to upload a file with filename as email of the uploader. I know this is not a OS file system issue, nor a unsupported python operation because I did save images with this format in python. Now I want to save the images in model(Specifically ImageField). I'm using OverwriteStorage to overwrite images if there is some existing image with same name. Saving the image model = Model.objects.create(email=email) # Blob to image tempfile_io = io.BytesIO() img.save(tempfile_io, 'JPEG') image_file = InMemoryUploadedFile(tempfile_io, None, email + ".jpeg",'image/jpeg',tempfile_io.getbuffer().nbytes, None) print("email is", email) model.pic.save(email + ".jpg",image_file) Model class Model(models.Model): email = models.EmailField() pic = models.ImageField(upload_to="pics", storage=OverwriteStorage()) OverwriteStorage class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, *args, **kwargs): print("name is", name) if self.exists(name): self.delete(name) return name But for some reason, I don't get the exact name in OverwriteStorage-get_available_name. email is xyz@example.com name is xyzexamle.com.jpg Notice how the @ sign is brutally removed. Is there any file name string check i need to disable. How can I make Django use the exact file name given(whenever possible)? -
Pip Install Local v.s Remote Repository Confusion
I am confused as to what exactly pip install (package) does. In my django project, I wanted to install a package and thought that I only needed to include it in the settings.py INSTALLED_APPS. However I also needed to run the command pip install (package) as well. Why is this the case? I thought that pip install only installed packages locally? The package seems to also work through my remote repository from another user as well which is why I am confused -
Fetch specific column in Django using JsonResponse
I have a problem on how can I filter specific column using Jsonresponse in html. I just want to filter specific column Paid_by. It is possible to filter in Jsonresponse just like this response.data.paid_by in my script? I tried response.datas.paid_by but it returns undefined Views.py def sample(): with connection.cursor() as cursor: cursor.execute("SELECT * FROM app_person WHERE paid_by != %s GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid", [blank]) row = dictfetchall(cursor) result = {'data':row} return JsonResponse(result) JsonResponse Success html success: function(response){ console.log(response.data) #fetch all data console.log(response.data.paid_by) #Undefined $("#rports").modal('show'); $("#rports").val(null).trigger("change"); } -
Nginx Gunicorn won't redirect to custom error page
I have Nginx -> Gunicorn -> Django web server, where my nginx config looks like this server { listen 8080; server_name mediadbin.n-media.co.jp; client_max_body_size 500M; access_log /home/mediaroot/mediadbin/logs/nginx-access.log; error_log /home/mediaroot/mediadbin/logs/nginx-error.log; server_tokens off; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Real-IP $remote_addr; } location /static { alias /home/mediaroot/mediadbin/mediadbin/static; } location /media { alias /home/mediaroot/mediadbin/mediadbin/media; } error_page 404 500 502 503 504 /500.html; location = /500.html { root /var/www/html/; internal; } } I have 500.html in my /var/www/html/ with chmod 777 for this file. When I trying to access something like www.mediadbin.n-media.co.jp:8080/asfgbdtDbggsfzsd <- it shows default Not Found Page not my 500.html. When I try to access www.mediadbin.n-media.co.jp:8080/500.html it shows this page. What I'm doing wrong? -
Are there security/performance issues if I connect a dockerized web app to an Amazon RDS DB?
I'm developing an app in Django. During the development process, I've used an Amazon PostgreSQL DB (using a free Dev/Test template). The database configuration for the app is straightforward: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db_name', 'USER': 'postgres', 'PASSWORD': 'db_password', 'HOST': 'AWS_endpoint', 'PORT': '5432' } } I've decided to create a docker image and use Amazon ECS to deploy the app. When I run the app as a docker container, it works just fine with the current database configurations; however, I've not seen any tutorials that discuss this solution to deploying a docker container and a database (i.e. creating an image of the app and using a hosted db solution). As an aside, most of the tutorials show the image being constructed with both the database and Django site on the same image, but that seems like a bad idea. My question: In a production environment, is it acceptable for me to connect my docker container (Django) to my database (Amazon PostgreSQL) in the manner I've described above, only using a new production db instance? At this point, I'm convinced that the answer to my question is obviously stupid (i.e., "of course, why would you ask such a …