Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
remove default order by?
str(CertificationWorkItem.objects.values ('certification_id','identity_id').annotate(c=Count('identity_id',distinct=True)).query) 'SELECT "CERTIFICATION_WORK_ITEM"."certification_id", "CERTIFICATION_WORK_ITEM"."identity_id", COUNT(DISTINCT "CERTIFICATION_WORK_ITEM"."identity_id") AS "c" FROM "CERTIFICATION_WORK_ITEM" GROUP BY "CERTIFICATION_WORK_ITEM"."certification_id", "CERTIFICATION_WORK_ITEM"."identity_id" ORDER BY "CERTIFICATION_WORK_ITEM"."identity_id" ASC' this code is showing order by but idon't want it remove order by how can i do it str(IdentityAccountRelation.objects.values('account_id__application_id').annotate(ck=Count('identity_id')).query) 'SELECT "ACCOUNT"."application_id", COUNT("IDENTITY_ACCOUNT_RELATION"."identity_id") AS "ck" FROM "IDENTITY_ACCOUNT_RELATION" INNER JOIN "ACCOUNT" ON ("IDENTITY_ACCOUNT_RELATION"."account_id" = "ACCOUNT"."uuid") GROUP BY "ACCOUNT"."application_id"' like this code -
Django's AppConfig.ready() seems to be called once per thread in Apache wsgi
I have the following code in apps.py: class Pqawv1Config(AppConfig): # ... def ready(self): env_run_main=os.environ.get('RUN_MAIN') print('IS_PRODUCTION=%s, RUN_MAIN=%s' % (settings.IS_PRODUCTION, env_run_main)) if (not settings.IS_PRODUCTION) and (env_run_main != 'true'): print('Exiting because detected running in reloader.') return print('Starting up for PID=%s, argv=%s...' % (os.getpid(), sys.argv)) # Initialization of a singleton object from a C++ DLL # Raise an exception if this library was already initialized in this process In the evening I restarted the server and it printed the following in the log as expected: [Sun Sep 15 22:50:34.928549 2019] [wsgi:error] [pid 11792:tid 1176] Starting up for PID=11792, argv=['mod_wsgi']...\r However, in the morning I noticed that something strange has happened. It looks like Apache started a new thread for the web application: [Mon Sep 16 04:10:41.224464 2019] [wsgi:error] [pid 11792:tid 1160] Starting up for PID=11792, argv=['mod_wsgi']...\r And later: [Mon Sep 16 07:16:21.028429 2019] [mpm_winnt:error] [pid 11792:tid 2272] AH00326: Server ran out of threads to serve requests. Consider raising the ThreadsPerChild setting I think it's not the issue of calling AppConfig.ready() method twice because there were requests to the website in between and they were handled well. It rather looks like Django's AppConfig.ready() method is called once per worker thread of Apache process. Is this … -
How to display foreign key value instead of pk in django?
Here I am filtering staffs which has OnetoOne relation with the django User model.And the below code of function def filter_staff_users(request): also works fine as I wanted but the problem what I get is while displaying the organization name in message.I tried doing organization.name but it didn't worked. I got 'str' object has no attribute 'name' and when I tried converting int organization = int(request.GET.get('organization')) then it again throws 'int' object has no attribute 'name'. How can I display the organization name here ? models.py class Organization(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class Staff(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff') name = models.CharField(max_length=255, blank=True, null=True) organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True, related_name='staff') While adding the staff_user i added the organization as below <select name="organization"> {% for organization in organizations %} <option value="{{organization.pk}}" >{{organization.name}}</option> {% endfor %} </select> views.py def filter_staff_users(request): year = request.GET.get('year') month = request.GET.get('month') # month_name = calendar.month_name[int(month)] organization = request.GET.get('organization') print('org', type(organization)) if year and month and organization: staffs = get_user_model().objects.filter(Q(staff__joined_date__year=year) & Q(staff__joined_date__month=month) & Q(staff__organization=organization)) messages.success(request, '{} staffs found for {} {} and {}'.format(staffs.count(), year, calendar.month_name[int(month)], organization)) -
API in django with response as data stream
I need to write an API in Django 2.2. It will be consumed by a google data studio connector. As a response I am fetching records from MariaDB. The size of the response causes the memory error on my production machine. So I am trying to stream it and this is what I did. Here is the code for iterator object. (Generation is model class) class Data(object): def __init__(self): self.paginator = Paginator(Generation.objects.get_queryset().order_by('id'), 100000) self.pagenum=1 def __next__(self): data="" if self.pagenum > self.paginator.num_pages: raise StopIteration if self.pagenum==1: data="[" data += serializers.serialize('json', self.paginator.get_page(self.pagenum))[1:-1] if self.paginator.num_pages == self.pagenum: data+="]" self.pagenum+=1 return data def __iter__(self): return self and here is the code for API response data = Data() response = StreamingHttpResponse(data,content_type="application/json") return response Problem: It seems connector does not wait for the entire stream to end and returns an invalid json error. -
How to send text client to server django channel
Hi all I'm trying send data js to django with websocket but not working Could you help me where am I doing wrong? ps: I was able to send data from the server to the client error: raise ValueError("No text section for incoming WebSocket frame!") No text section for incoming WebSocket frame! WebSocket DISCONNECT /ws/ [127.0.0.1:64282] js document.addEventListener('DOMContentLoaded', function () { let webSocketBridge = new WebSocket("ws://127.0.0.1:8000/ws/"); webSocketBridge.onopen = function(action) { console.log(action); webSocketBridge.send(JSON.stringify({ "id": "client1" })); }; webSocketBridge.onmessage = function(event) { let message = event.data; as += message + "\r\n"; $('#messages').html(as); }; consumer.py import asyncio from channels.generic.websocket import AsyncJsonWebsocketConsumer class TickTockConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() while 1: await asyncio.sleep(0.1) await self.send_json("tick") await asyncio.sleep(0.1) await self.send_json(".......tock") await self.receive() -
Backup/restore of auth.permission table
I have a Django model schema that contains an external model pointing to the auth.group_permissions (and therefore auth.permission) table. As part of my system I run backups using ./manage.py dumpdata to dump to a JSON file - and restore using the corresponding ./manage.py loaddata. I've seen advice in the Django docs and the community (see this warning) suggests that backing up the auth.permission table is not advised - and so this table is not backed up (along with contenttypes and session). Of late I have been running into some issues - if I add a new table to the database then migrate, then new rows are added to the end of the auth_permission tables. However if I rebuild the database and run a migration from scratch, then the new rows are not always placed at the end of the table - they are sometimes getting added in a different order. This means that my backups - which do not include auth.permission - can sometimes point to incorrect row IDs, as the IDs will now be in a different order. This is obviously not ideal as it means my database can potentially not be correctly restored in case of catastrophic failure. … -
How combine the temporary link with the real link on Django 2.2
I ran into such a problem. I created temporary links on the site. I can’t combine the temporary link with the real link (video link). How is this possible? So that a person can access the video only through a temporary link. -
Django AJAX form error message to be displayed on the same page index.html
In urls.py urlpatterns = [ path("contact-form/", contact_form, name="contact-form"), ] In views.py def contact_form(request): form = ContactForm(request.POST or request.GET) if form.is_valid(): data = { 'success': True, } status = 200 else: data = { 'success': False, 'errors': form.errors.get_json_data(), } status = 400 return JsonResponse(data, status=status) In index.html {% block js %} {{ block.super }} <script src="{% static 'app/js/contact-form-script.js' %}"></script> {% endblock %} In template index.html, there is a form: <form id="contactForm" method="get" action="{% url 'contact-form' %}"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" id="name" name="name" placeholder="Name"> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-6"> <div class="form-group"> <input type="text" placeholder="Subject" id="msg_subject" class="form-control" name="subject"> <div class="help-block with-errors"></div> </div> </div> ... <div class="submit-button"> <button class="btn btn-common" id="submit" type="submit">Submit</button> <div id="msgSubmit" class="h3"></div> </div> </div> </div> </form> When the form is submitted I want to display error messages to #msgSubmit. Right now when the form is submitted it gets redirected to http://localhost:8000/contact-form/?name=&subject=&email=&budget=&message= and this is dumped to the page {"success": false, "errors": {"name": [{"message": "Please enter your name", "code": "required"}], "subject": [{"message": "Please enter your subject", "code": "required"}], ...}} provided for example, if Name and Subject in the form are not filled in. The requirement says, form needs to be converted to AJAX and server … -
Django Model preventing create if any of Enum item already exist
I am writing a cinema ticket booking apps. I am going through the trouble to design my models! What I want: A person can buy/book one or more than one seats in one ticket If any seats already booked in a show, those seats can't be booked again later in the same show and show an error (But in a different show, it can be booked if available) I have only issue with Seats, I am not getting how to achieve this Can anyone please help me to make this model perfect? The models is given below from django.db import models from enum import Enum class ShowType(Enum): MORNING_SHOW = 1 NIGHT_SHOW = 2 class Person(models.Mode): name = models.CharField(max_length=20) class Seats(models.Model): seat_id = models.IntegerField(primary_key=True, editable=True) name = models.CharField(max_length=2) is_available = models.BooleanField(default=True) class Show(models.Model): show_name = models.CharField(choices=ShowType, default=ShowType.MORNING_SHOW) movie = models.CharField(max_lenght=50) date = models.DateField() seats = models.OneToManyField(Seats) class Ticket(models.Model): buyers = models.ForeginKey(Person, on_delete=models.CASCADE) show = models.ForeignKey(Show,on_delete=models.CASECADE) I want a any number of seats can be booked in a ticket of a show and later those seats can't be booked again for the same show and show an error. Can anyone please help me to achieve this? -
Django MSSQL Database Query to Django ORM
I need help translating this query into Django ORM: Select * from LabelFormat A where A.LabelFormatKey in (select B.LabelFormatKey from SyncTable B where B.LastModified < A.LastModified and B.LabelFormatKey = A.LabelFormatKey and B.Site = a.Site ) -
Filter annotate When Case with foregin key
i have 2 models: class ServiceRequest(models.Model): post_time = models.DateTimeField(default=timezone.now) service = models.IntegerField(default=102) class RequestSession(models.Model): request = models.ForeignKey(ServiceRequest) post_time = models.DateTimeField(default=timezone.now) If service have value 102, it will have one or more RequestSession. I have queryset get all ServiceRequest : ServiceRequest.objects.all() My question is : How to order_by post_time if service!=102, if service=102 i want order by greatest post_time of requestsession_set? i tried annotate but i dont know how to get greatest post_time in requestsession inside When then My query: queryset.annotate(time_filter=Case( When(service_id=102, then=('requestsession_set__post_time')), default=Value('post_time'), output_field=DateTimeField(), ), ).order_by("-time_filter") -
How do i host django website through webmin/virtualmin in hostinger?
I am trying to host a django website using webmin/virtualmin.I uploaded django file, but can't access the website using domain?How can i do this? -
docker does not installs the updated pipfile
I am using docker in my project. Initially there was following packages in Pipfile [packages] django = "*" djangorestframework = "*" celery = "*" whitenoise = "*" redis = "*" django-celery-beat = "*" flower = "*" django-environ = "*" django-redis = "*" "flake8" = "*" coverage = "*" gunicorn = "*" sentry-sdk = "*" django-storages = {extras = ["boto3"], version = "*"} django-anymail = {extras = ["mailgun"], version = "*"} pillow = "*" "psycopg2-binary" = "*" django-money = "*" django-phonenumber-field = "*" phonenumbers = "*" "argon2-cffi" = "*" jsonfield = "*" future = "*" django-contrib-comments = "*" tzlocal = "*" [dev-packages] werkzeug = "*" "autopep8" = "*" "flake8" = "*" I then build my project and it worked fine. But soon after building an image, i installed following packages in my local environment using pipenv install pylint-django pylint-celery django-debug-toolbar django-extensions --dev Now that i have updated my packages list, I tried to rebuild the image using docker-compose -f local.yml build which i guess did not installed those packages so I am getting issue `ModuleNotFoundError: No module named 'debug_toolbar'. Here is my docker configuration FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps … -
Unresolved import models Django + Docker
I have a few simple classes in my Django app that are not loading/importing properly. I know that the code works as I am Dockerizing over an existing app. I am fairly sure this is a similar issue to this but I do not know how to update this to use the Python inside my Docker container. I am following this guide (so all settings/configuration is the same). I have 2 classes: a custom user class and a Company model, and I am trying to add a foreign key on the user that links it to a particular Company. On the other side, I will have a many to many relationships (a company can have multiple users). from core.models import Company VS Code says "unresolved import" when I hover on core.models -
Forbidden (CSRF cookie not set.): /paypal/ | Django
I am having problems with django-paypal, the problem occurs at the moment of receiving the paypal IPN when the payment is successfully completed. Error: Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:53:04] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:53:19] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:53:42] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:54:24] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:55:45] "POST /paypal/ HTTP/1.1" 403 2896 I don't know what is happening, I started to investigate the error but I did not achieve much, investigating I put in the file settings.py CSRF_COOKIE_SECURE as True, and even then it did not work, any solution ?. -
Create postgresql command based on DELETE REST call within Django
So I have roughly the following: class exampleSerializer(serializers.ModelSerializer): def delete(self, request, *args, **kwargs): //Custom code The goal is to access the data of the row that the delete function is gonna delete. Based on this information I need to make some extra PostgreSQL commands before the functions finishes. How can I access this data? -
Form HTML, GET method. URL with multiple keywords
I'm building a search page that allows doing a search from 1-4 keywords that through the get method sends to the results page.(eg. for those keywords: one, two tree --> website.com/search/q=one+two+tree) Right now when I add more keywords and press search it sends to the URL using just the keyword in the text input. I tried to create a string joining the keywords with the "+" but sitll doesn't work. The following code is what I have tried. This is a django webapp and in the form.py there is one charfield with an id tag named "add_keyword". The function that doesn't work is send_keywords() <body> <link rel="stylesheet" href="style.css"> <script type="text/javascript"> var keywords_array = [] function getInputValue() { if (keywords_array.length<4){ var ul = document.getElementById("keywords"); var li = document.createElement("li"); var inputVal = document.querySelector("#add_keyword").value; li.appendChild(document.createTextNode(inputVal)); ul.appendChild(li); keywords_array.push(inputVal); } if (keywords_array.length==4){ console.log("You've added the max number of keywords") } } function send_keywords() { query = keywords_array.join("+") window.location.href= window.location.href+"/search/q="+query return query } </script> <h1>Dulcis in Fundo</h1> <h2>Let's coock something, what do you have left?</h2> {% block content %} <form class="" action="/search/" method="GET"> <ul id="keywords"> </ul> {{ form }} <button type="button" onclick="getInputValue();" name="button">add</button> <button type="submit" onclick="send_keywords()">Search</button> </form> {% endblock %} </body> -
Support for partial file downloads using HTTP / REST
I have a client/server architecture in which the client needs to periodically download large files from the server. Let's say the client downloads 9Gb of a 10Gb file and then temporarily loses internet connection. When the client regains connection, I would like the client to be able to download the remaining 1Gb of the file rather than need to re-download everything from scratch. Is there any platform, libraries, frameworks, etc. which handles this? If not, does anyone have any ideas on how to best approach this problem? Server/Client Technologies Server - Python / Django / Django REST Framework Client - Android / iOS / c++ Current Server Code def post(self, request): try: user = request.user file = MyFile.objects.filter(user_id=user) response = FileResponse(open(file.path, 'rb')) return response except Exception as e: return Response({'status': str(e)}, content_type="application/json") -
OperationalError at /admin/budget/expense/add/
When trying to save a new expense on http://localhost:8000/admin/budget/expense/add/ I recieve a OperationalError message saying: no such table: budget_expense I think it may be something relating to how my models.py file is set up: from django.utils.text import slugify # Create your models here. class Project(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) budget = models.IntegerField() def save(self, * args, **kwargs): self.slug = slugify(self.name) super(Project, self).save(*args, **kwargs) class Category(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=50) class Expense(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) For more context this is what the error message looks like: Request Method: POST Request URL: http://localhost:8000/admin/budget/expense/add/ Django Version: 2.2.5 Exception Type: OperationalError Exception Value: no such table: budget_expense Exception Location: C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: C:\Python37\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\kobby\\Documents\\financio', 'C:\\Python37\\python37.zip', 'C:\\Python37\\DLLs', 'C:\\Python37\\lib', 'C:\\Python37', 'C:\\Python37\\lib\\site-packages'] Server time: Sun, 15 Sep 2019 20:00:54 +0000 I can connect to Django admin just fine and I've been able to add 'projects' however when I want to add 'expenses' that's when the error comes. Any suggestions as to why this may be? -
trying to call Django view on button submit and redirect to the same page (reloaded)
I am trying to call a view that registers players to a tournament on button click, register them in the view, then essentially refresh the page to reflect their new registration. I have here views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Tournament, TournamentRegistration def index(request): tournaments = Tournament.objects.order_by("-start_time") context = {'tournaments': tournaments} return render(request, 'tournaments/index.html', context) def tournament_detail(request, tourney_id): tournament = Tournament.objects.get(pk=tourney_id) user = request.user player_is_registered = TournamentRegistration.player_is_registered(tourney_id, user.id) print(player_is_registered) if player_is_registered: registered = 'yes' else: registered = 'no' context = {'tournament': tournament, 'player_is_registered': registered} return render(request, 'tournaments/tournament_detail.html', context) def register_for_tournament(request, tourney_id, player_id): registration = TournamentRegistration(tournament=tourney_id, player=player_id) registration.save() return redirect(tournament_detail, tourney_id=tourney_id) tournaments/urls.py: from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<tourney_id>[0-9]+)/$', views.tournament_detail, name='tournament_detail'), url(r'^(?P<tourney_id>[0-9]+)/(?P<player_id>[0-9]+)/$', views.register_for_tournament, name='tournament_registration'), ] main urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'accounts/', include('accounts.urls')), url(r'accounts/', include('django.contrib.auth.urls')), url(r'^tournaments/', include('tournaments.urls')), url(r'', TemplateView.as_view(template_name='home.html'), name='home'), ] The template for tournament registration: <body> <p>User ID: {{ user.id }}</p> <p>{{ tournament.name }}</p> <p>Start time: {{ tournament.start_time }}</p> <p>Registered: {{ player_is_registered }}</p> <form action="/tournaments/{{tournament.pk}}/{{user.id}}" method="GET"> <button type="submit">Register</button> </form> </body> I came up with this code based on examples I found online. But to my dismay, instead of refreshing and showing the same page with the player registered, … -
Django Registration Form w/ Image
I have a UserProfile Model with an image field, I can upload the image from the admin. Now, I want to implement this image upload in the registration form. views.py class UserRegisterView(FormView): template_name = 'accounts/user_register_form.html' form_class = UserRegisterForm success_url = '/login' def form_valid(self, form): username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") image = form.cleaned_data.get("image") new_user = User.objects.create(username=username, email=email, image=image) new_user.set_password(password) new_user.save() messages.add_message(self.request, messages.INFO, 'Welcome') return super(UserRegisterView, self).form_valid(form) forms.py class UserRegisterForm(forms.Form): username = forms.CharField() email = forms.EmailField() image = forms.FileField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput) def clean_password2(self): ... def clean_image(self): image = self.cleaned_data.get('image') return image user_register_form.html Image : {{ form.image }} What am I missing? Thank you -
How to temporarily disable a token in Django REST Framework
I have created a Django app using REST Framework and created user and token for authentication using the following commands: python manage.py createsuperuser --username Alex --email Alex@example.com python manage.py drf_create_token Alex I can view newly created user (Alex) and its token in Django admin panel and have no problem with authentication but I want to be able to sometimes temporarily disable a token (say for Alex for example) so that he could not authenticate. Is there anyway to disable token? Note: recreating the token is not an option because upon executing python manage.py drf_create_token Alex a completely new token will be generated. -
how to override django files?
I have a function that crops user images but I don't want the model to have 2 fields so I made a function that overrides the original file and I noticed that the function works well on normal files but when I add the function to the view new file is made but at the media directory not even the the specified folder so how can i override files by Django ? the cropping function: import os from PIL import Image def crop(corrd, file ,path,pk): image = Image.open(file) path_1 , fn = os.path.split(path) patient_dir = 'patient_{}'.format(pk) path_ = path_1+patient_dir+fn cropped_image = image.crop(corrd) resized_image = cropped_image.resize((384, 384), Image.ANTIALIAS) resized_image.save(path_) return path_ views.py if form.is_valid(): image = form.save(commit=False) x = float(request.POST.get('x')) y = float(request.POST.get('y')) w = float(request.POST.get('width')) h = float(request.POST.get('height')) print(x) print(y) print(w) print(h) crop((x,y,w+x,y+h),image.pre_analysed,image.pre_analysed.path) image.patient = patient messages.success(request,"Image added successfully!") image.save() forms.py class ImageForm(ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UploadedImages fields = ('pre_analysed', 'x', 'y', 'width', 'height', ) models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.ImageField(upload_to = user_directory_path , verbose_name = 'Image') upload_time = models.DateTimeField(default=timezone.now) so what do I need to do here? thanks in advance. -
DRF: token deleting in custom authentication not working
I use djangorestframework and django-rest-auth for authentification api. I want to use a created field of rest_framework.authtoken.models.Token for checking token expiration. So I need to delete an expired token after expires checking, but calling delete() method does not delete token object! settings.py INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', 'rest_auth', ... ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'users.authentication.ExpirationAuth', ), 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '50/hour', 'user': '100/hour' } } users.authentication.py from rest_framework.authentication import TokenAuthentication, exceptions from django.utils.timezone import get_current_timezone from datetime import datetime, timedelta from config import constants current_timezone = get_current_timezone() class ExpirationAuth(TokenAuthentication): """ Custom authentication with expiration token """ def authenticate_credentials(self, key): model = self.get_model() try: token = model.objects.get(key=key) except model.DoesNotExist: raise exceptions.AuthenticationFailed('Invalid token.') if self.expired(token): token.delete() raise exceptions.AuthenticationFailed('Token has expired.') if not token.user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return token.user, token @staticmethod def expired(token) -> bool: return token.created < (datetime.now(current_timezone) - timedelta(hours=constants.token_expiration_hours)) If the token has expired I get a message Token has expired., but this token still in the database. -
Django - Post to specific URL using form
I want to post to a specific URL. The url has the scope of deleting a database row. The URL is composed by the address + the pk of the file selected in the form catched from a model. select_file_deletion.html {% extends "index.html" %} {% block content %} <!--Here the number 2 in "/App/delete/2/" needs to be replaced with the pk of the file. The logic is working. --> <form action="/App/delete/{{ myfile.pk }}/" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <h5>Please select one file at a time from the list below to delete it from the server.</h5> {% for myfile in filename %} <input type="checkbox" name="file_name" value="{{ myfile }}"> <label> <a href="/media/{{ myfile }}">{{ myfile }}</a> <input type="hidden" value="{{ myfile.pk }}" name="pk"> </label> <br> {% endfor %} <br> <button type="submit" class="btn btn-primary">Delete</button> </form> {% endblock %} Project urls.py url(r'^delete/(?P<pk>\d+)/$', FileDeleteView.as_view(), name='APIdelete') views.py class SelectFileDelView(TemplateView): """ This view is used to select a file from the list of files in the server. After the selection, it will send the file to the server. The server will then delete the file. """ template_name = 'select_file_deletion.html' parser_classes = FormParser queryset = FileModel.objects.all() def get_context_data(self, **kwargs): """ This function is used to render …