Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using firebase to sign up and authenticate users for a React & Django Rest Framework app
I have a Django Rest Framework backend with a React client. I want to use Firebase authentication in the following way: Ability to register and authenticate users via Django Rest Framework. Email registration should be supported. (I'm mainly interested in using Firebase to avoid building custom logic for email verification, password resets, etc) Ability to Django Rest Framework -
AWS S3 bucket serves image locally but on production image is not loading
I am having a problem with AWS S3 bucket. I searched and couldn't find a solution, I have a Django project hosted on Heroku and serve static images using s3 bucket. Some days back I deleted my old IAM credentials created new now the images works locally but on production it doesn't serve this images. By checking on the image URL I noticed the app locally could access the IAM credentials from env variables but on production it is still using the old deleted credentials. Here are my AWS settings setting environmental variables for S3 AWS_ACCESS_KEY_ID = os.environ.get('MY_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('MY_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('MY_AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = 'us-east-2' AWS_DEFAULT_UCL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Thanks for your help in advance. -
pass two of pk into url
If the 'school year' value is changed, 404 does not appear. I want data to be displayed only when both 'school_year' and 'pk' have the right values in url. for example If you have data that (School_Year = 2020, pk = 33) when you enter url https://190.0.1/190/190/33 and https://190.0.1/190/whatthell/33 Both are the same results. However, I would like to display the result only when both values are correct. i really dont know if i explained correctly, thanks. view.py class StudentDetail(DetailView,FormView): model = Student template_name = 'student/member.html' context_object_name = 'student' form_class = AddConsultation def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['pk'] = Student.objects.filter(pk=self.kwargs.get('pk')) return context url.py path('student/<school_year>/<pk>/', views.StudentDetail.as_view(), name='student_detail'), html link <a href='{% url 'student_detail' student.school_year student.pk %}'> models.py class Student(models.Model): school_year = models.CharField( max_length=10, choices=SCHOOL_YEAR_CHOICES, default='2021N', verbose_name='school year' ) ... etc -
Having trouble in routing ( giving urls or path) in Django Rest Framework
This is my main project urls . Now I have an app which is routed by path('', include('mysite.urls')),. Now I have a folder named crmAPi for creating apis. This api folder is not an app though, just a folder. I route the urls by using path('api', include("mysite.crmapi.urls")),. urlpatterns = [ path('', include('mysite.urls')), path('admin/', admin.site.urls), path('api', include("mysite.crmapi.urls")), ] Now, this is my crmApi urls. The problem is I can access to first path, i can see airilnes list. No, matter what i do, i cannot acces flightdetails. What is the problem with the route?? help pleaseee?? even i create a different listview, again I cannot the route, only the arilines one, I can access. urlpatterns = [ path('', views.AirlinesListAPIView.as_view(), name='api'), path('api/flightdetails', views.FlightDetailsListAPIView.as_view(), name='flightdetails'), ] This is my view. class AirlinesListAPIView(ListAPIView): # permission_classes = [AllowAny] serializer_class = AirlinesListSerailizer queryset = Airlines.objects.all() permission_classes = (IsAdminUser,) class FlightDetailsListAPIView(ListAPIView): # permission_classes = [AllowAny] serializer_class = FlightDetailsListSerailizer queryset = FlightDetails.objects.all() permission_classes = (IsAdminUser,) -
django model not in urls.py
I am new to python and django and I want to know the best way to set things up. I have a model called OauthProviders which I set up to encrypt some fields before save in the ModelViewSet (override perform_create method). I dont want to create routes (urls) for this model. Now, if I want to access this model in the code (I can with OauthProvider.objects.all() of course), but I have a few questions: how do I enter data to this model NOT in code? If I use the admin portal for it, it doesn't execute my custom perform_create method, so it gets added to the database in plain text What is the best way to decrypt a message if I retrieve data? -
django update query is not working but works in shell
I have a function in django , it's work well but queryset model not update def SLATarget(instanceID): SLAstatus = 2 print(SLAstatus) print(instanceID) ProcessInstance.objects.filter(no=instanceID).update(SLAstate=SLAstatus) run with SLATarget("1221") result of print is 2 1221 -
How can I import an external python file in django without raising errors in views.py
I am currently working on my website, which is a translator which you input a phrase and it gets translated into my own language. However, it is raising errors because it is not detecting the import. Here's the code of the translator function: def translator(phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper: translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper: translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper: translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper: translation = translation + "C" else: translation = translation + "c" return translation However, I am stuck in showing this funcion in my web, here's the code in views.py, here’s where the problem is shown from .translate import translator def translator_view(request): return render(request,'main/translator.html') def translated_view(request): #here is the main problem text = request.GET.get('text') print('text:', text) translate = translator dt = translator.detect(text) tr = translated.text context = { 'translated': tr } return render(request, context, 'main/translated.html') I knows the solution, please answer this post because I'm genuinely stuck -
Annotate with aggregate of related queryset
I'm having trouble getting my head around a django ORM query. I have the following models: class Container(models.Model): name = models.CharField(...) class ContainerItem(models.Model): amount = models.PositiveSmallIntegerField(...) date = models.DateTimeField(...) container = models.ForeignKey(Container) class Group(models.Model): container = models.ForeignKey(Container) start_datetime = models.DateTimeField(...) end_datetime = models.DateTimeField(...) For a Group queryset, I need to annotate the groups with the sum of the amount fields of the ContainerItems that fall within the group start_datetime and end_datetime. This is what I've got so far, but I keep getting 'This queryset contains a reference to an outer query and may only be used in a subquery.' items = ContainerItem.objects.filter( container=OuterRef('container'), date__gte=OuterRef('start_datetime'), date__lt=OuterRef('end_datetime') ) total_amount_qs = items.aggregate( total_amount=Sum('amount'), ).values('total_amount') Group.objects.all().annotate(amount_sum=Subquery(total_amount_qs) -
NoReverseMatch at / Reverse for 'user_login' not found. 'user_login' is not a valid view function or pattern name
New to Django 2. I have checked all the earlier post related to this error but could not find my mistake. Below are the details : Project - learning_users ; App - basic_app. There are 4 templates - base.html, index.html, login.html, registration. html. views.py from basic_app.forms import UserForm, UserProfileInfoForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required # Views def index(request): return render(request, 'basic_app/index.html') @login_required def special(request): return HttpResponse("You are logged in, Nice !") @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid and profile_form.is_valid: user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'basic_app/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else : return HttpResponse('User Not Active') else: print("Someone tried to login and failed") print("Username : {}, password : {}".format(username, password)) return HttpResponse("Invalid Login Details") else: return render(request, 'basic_app/login.html', … -
AssertionError at /api/movies/ 'MovieViewSet' should either include a `queryset` attribute, or override the `get_queryset()` method
Iam trying to access http://localhost:8000/api/movies/. But, it showing like this ..AssertionError at /api/movies/ 'MovieViewSet' should either include a queryset attribute, or override the get_queryset() method. I attached my code below 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 = 32) description = models.TextField(max_length =300) def __str__(self): return self.title class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) class Meta: unique_together =(("user","movie"),) index_together =(("user","movie"),) serializers.py from rest_framework import serializers from .models import Movie,Rating class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('id','title','description') class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id','stars','user','movie') urls.py from django.contrib import admin from django.urls import path from rest_framework import routers from django.conf.urls import include from .views import MovieViewSet,RatingViewSet router = routers.DefaultRouter() router.register('movies',MovieViewSet,basename='movies') router.register('ratings',RatingViewSet,basename='ratings') urlpatterns = [ path('', include(router.urls)), ] views.py from django.shortcuts import render from rest_framework import viewsets from .models import Movie,Rating from .serializers import MovieSerializer,RatingSerializer class MovieViewSet(viewsets.ModelViewSet): query_set = Movie.objects.all() serializer_class = MovieSerializer class RatingViewSet(viewsets.ModelViewSet): query_set = Rating.objects.all() serializer_class = RatingSerializer -
AWS: This XML file does not appear to have any style information associated with it. The document tree is shown below. (Django)
I'm using S3 services to store my projects media files but they are not showing. This is the problem the django's debugger displays when I open an image to a new tab. I'm on EU Paris Region and basically this is the message shown. This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> <AWSAccessKeyId>#################</AWSAccessKeyId> <StringToSign>AWS4-HMAC-SHA256 20200927T094200Z 20200927/eu-west-3/s3/aws4_request ###</StringToSign> <SignatureProvided>#####</SignatureProvided> <CanonicalRequest>###</CanonicalRequest> <RequestId>84D23A1D58F00C2D</RequestId> </Error> I've searched everywhere but none seem to have a solutions for django based applications My settings.py: AWS_S3_REGION_NAME = 'eu-west-3' AWS_ACCESS_KEY_ID = '################' AWS_SECRET_ACCESS_KEY = '##########################' AWS_STORAGE_BUCKET_NAME = '########' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' (p.s I have hashtaged the sensitive informations) -
Observing django-background-tasks metrics with Prometheus
I am trying to collect application-specific Prometheus metrics in Django for functions that are called by django-background-tasks. In my application models.py file, I am first adding a custom metric with: my_task_metric = Summary("my_task_metric ", "My task metric") Then, I am adding this to my function to capture the timestamp at which this function was last run successfully: @background() def my_function(): # my function code here # collecting the metric my_task_metric.observe((datetime.now().replace(tzinfo=timezone.utc) - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds()) When I bring up Django, the metric is created and accessible in /metrics. However, after this function is run, the value for sum is 0 as if the metric is not observed. Am I missing something? Or is there a better way to monitor django-background-tasks with Prometheus? -
How to stop response until page get full load with pdfkit.from_url in python
I am converting url to pdf file by using pdfkit.from_url. Here when ever I hit that url then with in fraction to seconds it is converting to pdf(here it is not waiting to load all data in page url). my problem is how to stop pdfkit.from_url until page data get load full. Please give me slolution. This is my code pdf_file = pdfkit.from_url(url, path + 'assigned_id' + '_' + str(assign_code) + '.pdf', options=options) -
Is it really necessary to use virtualenv for a new Django or Flask project?
I started to learn Flask and Django, and it is preferred to create a virtualenv before installing the dependencies system-wide or globally. But isn't installing globally would help using the dependencies for other projects as well. Also, creating virtualenv and installing Django/Flask for every project would take up system memory. -
Did Debug=(os.getenv("DEBUG_VALUE")=='True') but still showing debug info on all devices
I have hide my debug value and security key in env variable. but after accessing a unknown page on my website. it shows debug information. what am I doing wrong? # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.getenv("DEBUG_VALUE") == 'True') DEBUG_VALUE = 'True' in env var. and I have done heroku config:set Secret_Key="***" and Debug_value='True' -
TemplateSyntaxError at /notes/list/ add requires 2 arguments, 1 provided
I am trying add pagination in my notes list but i am having an 2 argument error. I don't know to fix it. Can you guys tell me how can I solve it? notes/views.py class NotesListView(LoginRequiredMixin,ListView): login_url = '/accounts/login/' model = Notes context_object_name = 'notes_data' paginate_by = 3 def get_queryset(self): return Notes.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') notes/notes_list.html {% if is_paginated %} {% if page_obj.has_previous %} <a class ='btn btn-warning'href='?page=1'>first</a> <a class ='btn btn-warning'href="?page={{page_obj.previous_page_number}}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if num == page_obj.number %} <a class ='btn btn-warning'href="?page={{num}}">{{num}}</a> {% elif num > page_obj.number|add.'-1' and num < page_obj.number|add.'1' %} <a class ='btn btn-success'href="?page={{num}}">{{num}}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class ='btn btn-warning'href="?page={{page_obj.next_page_number}}">Next</a> <a class ='btn btn-warning'href="?page={{page_obj.paginator.num_pages}}">Last</a> {% endif %} {% endif %} -
Django web app "Not allowed to load local resource /.css file"
I cant load css file in my web page it just gives me a simple page without css elements as shown in the screenshot and says it cant load local resource Page and inspect elememt I've loaded the static files in settings STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT=os.path.join(BASE_DIR,'assets') added url static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) used this in html {%load static%} <head> <style> {% include "assets/styles/style.css" %} </style> <meta charset="UTF-8"> <title>LOGIN</title> <link rel="stylesheet" href="{% static 'assets/style.css' %}"> </head> also did manage.py loadstatic followed the docs dont know where i went wrong -
Django.db.utils.ProgrammingError: relation does not exist
Django.db.utils.ProgrammingError: relation does not exist an error is occurring. I am new to Heroku and trying to solve the issue. I found some resources on StackOverflow but it doesn't help me out with my problem. I also try to make migrations from Heroku run bash but the same error is shown while trying to perform makemigrations the access is getting denied from Heroku. this is the error capture from heroku run console. -
How can I import a python file coded by myself and then see what it does on a django website?
I am currently working on my website, which is a translator which you input a phrase and it gets translated into an invented language. Here's the code of the translator function: def translator(phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper: translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper: translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper: translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper: translation = translation + "C" else: translation = translation + "c" return translation However, I am stuck in showing this funcion in my web, here's the code in views.py: from .translate import translator def translator_view(request): return render(request,'main/translator.html') def translated_view(request): text = request.GET.get('text') print('text:', text) translate = translator dt = translator.detect(text) tr = translated.text context = { 'translated': tr } return render(request, context, 'main/translated.html') Here's the template where you introduce the text: <form action="{% url 'translated' %}" method= "get"> <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> … -
Login with Django and Ajax does nothing
Here is my form: <form action="#" method="post"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Enter Username:</label> <input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"> </div> <div class="form-group"> <label for="exampleInputEmail1">Enter Password:</label> <input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off"> </div> <button class="btn btn-primary" id = 'login_button'>Login</button> </form> And the script: <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script> var login_button = $('#login_button') login_button.click(function(){ var username = $('#username').val() var password = $('#password').val() $.ajax({ url: '{% url 'td_app:do_login' %}', type: 'get', data: { 'username': username, 'password': password }, dataType: 'json', success: function (data){ console.log(data.result) } }).done(function (){ console.log(data.result) }) }) </script> In my views.py: def do_login(request): username = request.GET.get('username') password = request.GET.get('password') user = authenticate(username=username, password=password) data = {} if user: if user.is_active: login(request, user) data['result'] = 'success' return HttpResponseRedirect(reverse('td_app:index')) else: data['result'] = 'failed' return JsonResponse(data) And finally my urls.py: url(r'^api/do_login/$', views.do_login, name='do_login') However all of these doesn't work and it doesn't even give me any errors. It just completely refreshes the whole page and does nothing. I tried putting alerts but on the success and done section but it doesn't show it up. Any thoughts/advices? Thanks a lot! -
How to download videos on Django (youtube_dl)
I am making a website for downloading videos from YouTube and not only. For this I use the youtube_dl library. When the button is clicked, I redirect to the file link. I also made a site about programs for Windows, and when I redirect to a file link, it was downloaded. It doesn't work with video, the video just opens in the browser. So this is how to download videos? views.py: from django.shortcuts import render, redirect from .models import Video import youtube_dl import uuid def index (request): last_video = Video.objects.last () current_video = Video.objects.get (pk = last_video.pk) return render (request, 'main / index.html', {'current_video': current_video}) def video_loader(request, video_id): video_url = request.GET.get('url', '') filename = str(uuid.uuid4()) ydl_opts = { 'format': 'bestvideo', 'outtmpl': f'media/videos/{filename}.%(ext)s' } if video_url: with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([video_url]) Video.objects.create(name = filename, url = video_url, file = f'videos/{filename}.mp4') else: pass current_video = Video.objects.get(pk=video_id) return redirect(current_video.file.url) Html form: <form class="banner__form" id="banner__form" method="POST" action="{% url 'video_loader' current_video.pk%}"> {% csrf_token %} <input class="banner__input" id="banner__input" type="text" placeholder="Enter link" autocomplete="off" name='url' maxlength="100"> <button type="submit" class="fas fa-search fa-2x banner__btn" id="banner__btn"></button> </form> If you still need something, I will throw it off. -
Splitting django project in two big modules and getting import problems
I want to start a new enterprise project which will be very large and will have a thorough business logic. I want to split it into two "sub-projects", one with the models, api and business logic (called "business"), and the other with the views for the web app (called "webapp"). The idea of separating the web app (views) from the models, api and business logic is because I want these 3 lasts to be the service for both web app and mobile too. The layout looks like this: project/ + business/ | + __init__.py | + rest_urls.py | + business_app_1/ | | + __init__.py | | + controllers.py | | + models.py | | + serializers.py | + business_app_2/ | | + __init__.py | | + controllers.py | | + models.py | | + serializers.py + project/ #this one is just the main configuration django app | + __init__.py | + settings.py | + urls.py | + wsgi.py + webapp/ | + __init__.py | + urls.py | + view_app_1/ | | + views.py | + view_app_2/ | | + views.py | + view_app_n/ | | + views.py I just ran a test because I never made a complex layout like … -
django-summernote codemirror theme setting
I would like to to set custom theme for 'codemirror' mechanism at django-summernote. In Readme.md of django-summernote it says (https://github.com/summernote/django-summernote/blame/master/README.md#L222): You have to include theme file in 'css' or 'css_for_inplace' before using it. I found codemirror themes there: https://codemirror.net/demo/theme.html https://github.com/codemirror/CodeMirror/tree/master/theme in settings.py I've added: SUMMERNOTE_CONFIG = { 'codemirror': { 'mode': 'htmlmixed', 'lineNumbers': 'true', 'theme': 'monokai', } } Question: where to put css files - somewhere in site-packages of django-summernote or inside my django app? If in my app - where in static/ folder. I've tried both above options but it didn't worked. How to do it properly? -
Would it be possible to filter results based on an aggregated child field using django-filter?
I have invoices with items in them. Item's have prices. Now I wish to sum the items and based on the sums, filter the invoices. Here are the models class Invoice(models.Model): title = models.CharField(max_length = 150) reciept_image = models.ImageField(upload_to='invoice_receipts/%Y/%m/%d', null = True, blank = True) date = models.DateTimeField(default=datetime.now) class Item(models.Model): invoice_id = models.ForeignKey(Invoice, on_delete=models.PROTECT) item_name = models.CharField(max_length = 150) amount = models.DecimalField(max_digits=9999, decimal_places=2) The Serializers are class InvoiceSerializer(serializers.ModelSerializer): item_set = ItemSerializer(many = True, read_only = True) class Meta: model = Invoice fields = ['id', 'title', 'reciept_image', 'date', 'item_set'] class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['id', 'invoice_id', 'item_name', 'amount'] I simply cannot seem to wrap my head around this. I hope this isn't too advance a functionality for SQLite. -
duplicate key value violates unique constraint django rest framework
I have App named Company and in models.py there is a model named CompanyProfile models.py class CompanyProfile(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, verbose_name='ID',) full_name = models.CharField(max_length=255, unique = True, default='NA') contact_person_email = models.EmailField(unique=True, null=True, blank=True) def __str__(self): return str(self.full_name) serializers.py class CompanyProfileSerializer(serializers.ModelSerializer): """List all the Company Profile""" class Meta: model = CompanyProfile fields = '__all__' read_only_fields = ['id'] ``` views.py ````python class CompanyProfileViewSet(viewsets.ModelViewSet): """Update and Detail for Company Profile""" queryset = CompanyProfile.objects.all() serializer_class = CompanyProfileSerializer permission_classes = (permissions.IsAuthenticated,) lookup_field = 'id' def update(self, request, id ,*args, **kwargs): instance = self.get_object() import pdb; pdb.set_trace() if instance.full_name != request.data.get("full_name"): instance.full_name = request.data.get("full_name") if instance.contact_person_email != request.data.get("contact_person_email"): instance.contact_person_email = request.data.get("contact_person_email") instance.save() return super().update(request, *args, **kwargs) Now if you see above am actually comparing each field and checking weather update is possible there or if the field needs to be updated? 1. Doing this one each field is quite cumbersome as I have already set the required validation But now I have to check on each field whether the user has updated them or not! 2. If I don't have an update in any of the fields then it gives me this error already exists and sometimes as some field are marked unique in …