Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to create hackerrank like Website where user can solve programming questions? [closed]
Hello Everyone Can anyone help me how to create a website like hackerrank or hackerearth where user can solve programming questions, I mean I have to create only coding problem website not whole website like hackerrank has.I want to do it in Django and Python.I have read many article related to this from that I get to known that I can use unittest for checking the answer but Exactly I don't how I have to do it and what should be the pathway So please help?This is my college project!! -
How to implememt simple django quiz
I'm trying to do a "practice words in English" quiz. The user gets 4 random words from the DB and has to choose the right option. The problem with the code is that the test whether the user chose the right word or not occurs after the selection and in fact the comparison is made in front of the next set of words. View: def quiz(request): choices = Words.objects.all().values_list("id","English_word","Hebrew_word", ) choice_list = [] for item in choices: choice_list.append(item) random.shuffle(choice_list) word = choice_list[0][1] options = choice_list[:4] random.shuffle(options) if request.method == 'POST': user_choice = request.POST.get('quiz') if user_choice == choice_list[0][2]: messsge = 'V' return render(request, 'quiz.html', {'choices':options,'word':word, "messsge":messsge,}) else: messsge = 'X' return render(request, 'quiz.html', {'choices':options,'word':word, "messsge":messsge,}) return render(request, 'quiz.html', {'choices':options,'word':word,}) HTML: <h2> {{word}} </h2> {%for choice in choices %} <form method="POST"> {%csrf_token%} <br/> <input id='quizz' name = "quiz" type="submit" value={{choice.2}} class="btn btn-primary"/> </form> {%endfor%} {{messsge}} -
Django SimpleJWT
I am using a django-simplejwt and I have a custom token view for obtaining token. My problem is, how can i override the 401 Unauthorized response from the view? https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class ObtainTokenSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['name'] = user.first_name # ... return token class ObtainToken(TokenObtainPairView): serializer_class = ObtainTokenSerializer -
how to order a choicefiled in django model
I have a choice filed and i need to sort it based on the order in CHOICES tuple and this model.py : class MeetingMember(models.Model): CHOICES = ( ("H", "Host"), ("A", "Accepted"), ("R", "Rejected"), ("I", "Invited" ) ) status = models.CharField(max_length=9, choices=CHOICES, default="I") i have already tried meta ordering : class Meta: ordering = ('status',) but it is not working i need to sort it in 'Host,Accepted,Rejected,Invited' -
Navbar problem with views context, when using slug or PK. (Django)
The slug will only work on HomeView if I add it to the HomeViews context, but I only want to add it one time, I don't want to add it to every view, but I want it to work on every view. Is there anyway I can do this? app2/models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Model1(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True, blank=False, null=False) app1/views.py from app2.models import Model1 from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.views.generic.list import ListView class HomeView(ListView): model = Model1 ordering = ['-id'] template_name = 'app1/home.html' boolean = False model1_slug = 'app2' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if Model1.objects.filter(user=self.request.user).exists(): self.boolean = True user_model1 = Model1.objects.get(user=self.request.user) self.model1_slug = user_model1.slug else: self.model1_slug = 'app2' self.boolean = False context['model1_slug'] = self.model1_slug context['boolean'] = self.boolean return context includes/navbar.html {% if boolean == False %} <li><a class="dropdown-item" href="{% url 'start-model1' %}">Start Model1</a></li> {% elif boolean == True %} <li><a class="dropdown-item" href="{% url 'my-model1' model1_slug %}">My Model1</a></li> <li><a class="dropdown-item" href="{% url 'add-model2' %}">Add model2</a></li> {% endif %} The navbar will give nothing if I'm not at the home page. -
How Can i use Nuxt and Django for production at the same time?
I have a background in Django and a some experience in Vue. I have used Vue for almost a year now, but since I need an SSR I have to use Nuxt.However, I am still very confused with how to deploy it in the server along with Django. Should I deploy them in the same server or should I deploy them in a different server with Django server for API and Nuxt for the front end? -
Get default exam as object.id
You can get or create default object Create this method: def get_default_exam(): exam = Exam.objects.get_or_create(<fields>)[0] return exam.id Then, you can use it in default: class Student(models.Model): ... exam_taken = models.ForeignKey("Exam", default=get_default_exam()) -
I am learning about django-ads using it to create a advertisement product [closed]
I have been studying about the django-ads package from python-django . been tring to create an ads app where user can save their own ads and then we distribute it to our project, i.e. the user hepls display their own ads to the website, later we can expand the product. But I am being at this point where i am not getting what to do next. I have added the ads with their target_urls onto the database. In this exapmle below of django-ads: First step they did is insert 3 ads ,in this step i facing a problem . This step takes value in dictionary form like key-value pairs, i have data which can be processed as a dictionary type. but the template_body key is where i am getting confused. I am trying to distribute the ads in the whole website. Any suggestions will be appreciated. Thank You. django-ads - Example1.wiki Insert 3 ad show's by admin Ad Show 1 name: 'ad 1' group: 'first-group' template_body: 'my ad number 1' url_pattern: None Ad Show 2 name: 'ad 2' group: 'first-group' template_body: 'my ad number 2' url_pattern: '/test/[\w_-]+/' Ad Show 3 name: 'ad 3' group: 'second-group' template_body: 'my ad number 3' … -
I want to reflect the current date & time in rest API based on the user region but I'm unable to get it
I just tried to get the list of date and time instead of DD-MM-YYYY format but I wasn't able to. When I tried to fetch one particular id it's reflecting only the time. I want to call the particular id using the username through slug. views.py from datetime import date from django.http import request from django.http.response import JsonResponse from django.shortcuts import get_object_or_404 from rest_framework import generics, mixins, serializers from rest_framework.decorators import api_view from rest_framework.fields import JSONField from rest_framework.response import Response from rest_framework.views import APIView from app.models import Userbase import datetime from .serializers import UserDetailSerializer, UserSerializer import pytz from rest_framework import viewsets from rest_framework import status from rest_framework.renderers import JSONRenderer @api_view(['GET', 'POST']) def data_list(request): if request.method == 'GET': user = Userbase.objects.all() print(user) serializer = UserSerializer(user, many=True) # json = JSONRenderer().render(serializer.data) # print(json) return Response(serializer.data) elif request.method == 'POST': serializer = UserSerializer(data=request.data) 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) @api_view(['GET', 'POST']) def data_detail(request, pk): # try: # user = Userbase.objects.get(pk=pk) # except Userbase.DoesNotExist: # return Response(status=status.HTTP_404_NOT_FOUND) # if request.method == 'GET': # serializer = UserDetailSerializer(user) # return Response(serializer.data) if request.method == 'GET': try: user = Userbase.objects.get(pk=pk) --here i want to call based on username print(user.timezone) serializer = UserDetailSerializer(user, data=request.data) zone … -
django get polygons inside coordinates
I have a coordinate that frontend gives me like "[[{"lat":45.36324254131911,"lng":2.471923828125},{"lat":46.667815881216754,"lng":2.471923828125},{"lat":46.667815881216754,"lng":6.50390625},{"lat":45.36324254131911,"lng":6.50390625}]]" This is a rectangle. I have a model where I am storing Polygon data from djgeojson.fields import PolygonField class MyCords(models.Model): geom = PolygonField() a single instance of Mycords.geom gives me data like: {'type': 'Polygon', 'coordinates': [[[5.328369, 45.251688], [5.910645, 44.980342], [6.328125, 45.375302], [6.075439, 45.859412], [5.471191, 45.698507], [5.328369, 45.251688]]]} Here I want to filter all the MyCords that lies in the given coordinates. How can I get this through queryset ? -
Exporting model data to csv file using Python Django not working
I am trying to create a but to export some data in my database to a csv file. It hits the correct part of the if statement but no CSV file is being downloaded. # ================================= # CSV Import/Export Functionality # ================================= @login_required def exportData(request, setCode): current_user = request.user if request.GET.get('product-type') == 'Cards': response = HttpResponse(content_type='text/csv') now = datetime.datetime.now() response['Content-Disposition'] = "attachment;filename=ExportData-" + setCode.upper() + "-" + now.strftime("%Y-%m-%d %H.%M.%S") + ".csv" writer = csv.writer(response) writer.writerow(['setCode', 'id', 'number', 'name', 'rarity', 'convertedManaCost', 'colors', 'standard', 'foil']) SQL_EXPRESSION = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" for cards in inventory_cards.objects.all().filter(user_id=current_user.id).extra( select={'int': SQL_EXPRESSION}).order_by('card_id__set_id__code', 'int', 'card_id__number').values_list( 'card_id__set_id__code', 'card_id', 'card_id__number', 'card_id__name', 'card_id__rarity', 'card_id__convertedManaCost'): writer.writerow(cards) return response elif request.GET.get('product-type') == 'Tokens': pass elif request.GET.get('product-type') == 'Sealed': pass -
Limit users for change their own files in django REST
how are you? I am totally new in Django and rest. I am interested in writing a project which limits users just change their own tasks(my project is task management). I know that I should use the DjangoModelPermissions but unfortunately, it does not work on my project... it does not return any error but does not work either. Thank you for helping My app urls: path("api/",views.ListTaskAPIView.as_view(),name="all_task"), path('api/<int:pk>/', views.TaskDetailView.as_view(), name='detail_task'), path("api/create/", views.CreateTaskAPIView.as_view(), name="create_task"), path("api/update/<int:pk>/", views.UpdateTaskAPIView.as_view(), name="update_task"), path("api/delete/<int:pk>/", views.DeleteTaskAPIView.as_view(), name="delete_task"), Models : class Task(models.Model): title=models.CharField(max_length=250) text=models.TextField() user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) status=models.ForeignKey('Status',on_delete=models.SET_NULL,null=True) startDate=models.DateTimeField(auto_now_add=True) endDate=models.DateField(null=True) def __str__(self): return self.title class Status(models.Model): name=models.CharField(max_length=250) def __str__(self): return self.name serializer: from rest_framework import serializers from .models import Task,Status class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['title', 'text', 'status', 'endDate'] class StatusSerializer(serializers.ModelSerializer): class Meta: model = Status fields = '__all__' Views: class ListTaskAPIView(generics.ListAPIView): serializer_class = TaskSerializer model= Task template="task_list.html" def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ query = self.request.GET.get('search') if query: object_list = self.model.objects.filter(Q(title__icontains=query) | Q(text__icontains=query)) else: object_list = self.model.objects.all() return object_list class CreateTaskAPIView(CreateAPIView): """This endpoint allows for creation of a todo""" queryset = Task.objects.all() serializer_class = TaskSerializer permission_classes = [IsAuthenticatedOrReadOnly] … -
How to find average difference between datetime field in a related table?
I have to apps buyer and seller. seller app has model Gigs and buyer app has model Orders. I want when I retrieve a gig to my rest app it should compute average completion time of order of that specific gig. But I am getting error 'decimal.Decimal' object has no attribute 'tzinfo' Models.py(seller app) from django.db.models import Avg from django.db.models import F class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if getattr(self, '_average_completionTime', None): return self._average_completionTime return self.gig.aggregate(Avg(F('orderCompletedTime') - F('orderStartTime'))) Models.py (buyer app) class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') orderStartTime = models.DateTimeField(default=None) orderCompletedTime = models.DateTimeField(default=None) created_at = models.DateTimeField(auto_now_add=True) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.all().annotate( _average_completionTime=Avg( F('gig__orderCompletedTime') - F('gig__orderStartTime') ) ) serializer_class = GigsSerializerWithAvgTime permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.retrieve(request, *args, **kwargs) Serializers.py class GigsSerializerWithAvgTime(serializers.ModelSerializer): average_completionTime = serializers.SerializerMethodField() def get_average_completionTime(self, obj): return obj.average_completionTime class Meta: model = Gigs fields = ['id','title','category','price','details','seller','images','average_completionTime'] But I am getting error 'decimal.Decimal' … -
how to use base64 with django ,and input html tag
I'm trying to save captured image from webcam to my django website 3.2 version this is what i'm tried class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my views.py #my views function ... if request.is_ajax() and request.method == 'POST': images = request.FILES.get('canvas') print("images" , images) format, imgstr = images.split(';base64,') ext = format.split('/')[-1] dataimage = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) if dataimage: photo = Document.objects.create( booking=obj, docs = dataimage ) photo.save() but print images value is none , here is my JS + html const player = document.getElementById('player'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const captureButton = document.getElementById('capture'); console.log(context) const imgFormat = canvas.toDataURL(); console.log(imgFormat) console.log(canvas) const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height); e.preventDefault(); }); navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); <input type="file" name="documents" id="document"> <video id="player" controls autoplay></video> <button id="capture">Capture</button> <canvas id="canvas" name="canvas" width=320 height=240></canvas> is there something i have to change ? i think i have to access to canvas js variable from my views.py but i dont know how to achieve it -
Django access self in PrimaryKeyRelatedField
I have Order model with columns: id, restaurant_id, user_id, comment and OrderHasItem with columns: quantity, order_id, item_id I would like to be able to allow item from the same restaurant only for OrderHasItem. class OrderHasItemCreateSerializer(serializers.ModelSerializer): item = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all(), many=False) class Meta: model = OrderHasItem fields = ['id', 'quantity', 'item'] class OrderCreateSerializer(serializers.ModelSerializer): items = OrderHasItemCreateSerializer(many=True) restaurant = serializers.PrimaryKeyRelatedField(queryset=Restaurant.objects.all(), many=False) comment = serializers.CharField(required=False) Is there a way to access self.restaurant in PrimaryKeyRelatedField? Thanks -
Django URLField Not Validating URLs
The URLField takes literally any text I pass to it. Doesn't the models.URLField have a validation on it? Model: class TesterManager(models.Manager): pass class Tester(models.Model): objects = TesterManager() url = models.URLField(unique=True) View @action(detail=False, methods=['POST']) def create_url(self, request): test = Tester.objects.create(url=request.data['url']) # Why does this not catch non-URLs??? # response -
what should i do toprogram in my domain that i purchased?
Today I bought a domain name in GoDaddy. I changed the nameservers to Cloudflare and got a free SSL certificate from there. How do I connect the domain that I purchased to python [i use flask/Django to program the website] -
Why is logging to a Django model a Blasphemy?
In all Django projects I write, I have a common application, and in that application I put things that are useful to the project as a whole. One such thing is an Activity or Event model like this: class Activity(models.Model): SUMMARY_LENGTH = 72 def __str__(self): return '%d:- %s' % (self.id, self.summary) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.PROTECT) created = models.DateTimeField(db_index=True, auto_now_add=True, editable=False) activity_type = models.PositiveIntegerField(choices=ActivityTypeEnum.choices, default=ActivityTypeEnum.LOG) summary = models.CharField(max_length=SUMMARY_LENGTH, help_text='Text Shown in Staff Activity Log') show = models.BooleanField(default=False, help_text='Show in Staff Activity Log') page_url = models.URLField(max_length=128, blank=True) ip_address = models.GenericIPAddressField(blank=True, null=True) extra_detail = models.TextField(blank=True) class Meta: ordering = [ '-created' ] def save(self, *args, **kwargs): if len(self.summary) > self.SUMMARY_LENGTH: self.summary = self.summary[:self.SUMMARY_LENGTH] return super(Activity, self).save(*args, **kwargs) Then I have a helper function one liner that I can put anywhere in my code where I can log something, with different log types for different kind of events. def record_activity(activity_type=ActivityTypeEnum.LOG, summary='', extra_detail='', show=True, makeme_string=None, job=None, request=None): """ Record System Wide Activity Stuff. Not a member function, becuase importing the model class everywhere is to be avoided """ if makeme_string: try: string_bit = json.dumps(makeme_string, sort_keys=True, indent=4, separators=(',', ': '), default=str) except: string_bit = 'Could not dump the makeme_string' extra_detail += '\n=======================\n%s' % string_bit … -
Django CKEditor Background Color
I'm using django ckeditor, and when i click any button (for example: iframe button), the background color is black so its hard to see and edit Here is my code for django ckeditor config CKEDITOR_CONFIGS = { 'default': { 'toolbar': [["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Subscript", "Superscript", "Iframe"], ['Undo', 'Redo'], ["Maximize"]], }, } Is there a way to change a color background? Is the problem in django ckeditor? django? or my browser? any idea? Thankyou. -
Google App Engine GitHub Action: Error: Unexpected token � in JSON at position 0
I'm trying to deploy my Django API on to Google App Engine using GitHub CI/CD, but I'm getting a strange error that doesn't provide any stack trace in my deploy job. My build job with unit tests and code coverage passes. main.yaml: name: Python application on: push: branches: [ main ] pull_request: branches: [ main ] defaults: run: working-directory: src jobs: build: runs-on: ubuntu-latest services: postgres: image: postgres:10.8 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github_actions ports: - 5433:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python 3.9 uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Test with Unittest env: SECRET_KEY: ${{ secrets.SECRET_KEY }} DB_NAME: ${{ secrets.DB_NAME }} DB_USER: ${{ secrets.DB_USER }} DB_PASSWORD: ${{ secrets.DB_PASSWORD }} DB_HOST: ${{ secrets.DB_HOST }} DB_PORT: ${{ secrets.DB_PORT }} DB_ENGINE: ${{ secrets.DB_ENGINE }} run: | coverage run manage.py test && coverage report --fail-under=75 && coverage xml mv coverage.xml ../ - name: Report coverage to Codecov env: SECRET_KEY: ${{ secrets.SECRET_KEY }} DB_NAME: ${{ secrets.DB_NAME }} DB_USER: ${{ secrets.DB_USER }} DB_PASSWORD: ${{ secrets.DB_PASSWORD }} DB_HOST: ${{ secrets.DB_HOST }} DB_PORT: ${{ secrets.DB_PORT }} DB_ENGINE: … -
Building my first Django app - need guidance [closed]
I'm getting down to building my first Django App for my portfolio, and would like some guidance. Brief - the app will be a booking system that allows logged in users (customers) to book delivery slots on a selected date & a specific time. Think of it as a B2B portal for customers who are delivering their shipments to a distribution center (DC) and need to select a Delivery Date & Delivery Time for their shipment to be received at the DC's docks. e.g. Delivery Date = 29-Sep, Delivery Time = 09:00 Rules of booking: Delivery Time slots will be fixed for each day (7:00, 09:00, 11:00, 13:00) There is no limit to the number of bookings a customer can make If customer A has already booked a specific date & time e.g. 29-Sep, 09:00 and customer B also tries to book the same slot, the portal should feedback "The requested slot is already occupied, please choose another delivery time" If all the time slots on a specific date are already occupied, the portal should feedback "All the slots on this date are occupied, please choose another delivery date" The customer will be allowed to change or delete their booking … -
balance not getting correctly in the accounts ledger app
I'm trying to make a ledger app. the 2nd and 3rd row is of the same bill with 2 transactions.The bill value is the total amount of the bill and I use mathfilters in template to calculate the balance. In this case thats not possible since there are 2 transactions. Template <h1>Ledger</h1> <table id="table"> <thead> <td class="no-sort">Sl No</td> <td class="no-sort">BILL DATE</td> <td class="no-sort">ORDER NO</td> <td>BILL VALUE (Rs)</td> <td>PAYMENT (Rs)</td> <td>BALANCE (Rs)</td> </thead> {% for data in order_list_data %} <tr> <td>{{forloop.counter}}</td> <td>{{data.invoice__bill_date}}</td> <td>{{data.invoice__bill_no}}</td> <td>{{data.customer_gross_sum}}</td> <td>{{data.invoice__transaction_invoice__transaction_amount}}</td> <td></td> </tr> {% endfor %} </table> Views class LedgerView(TemplateView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): order_list = Order.objects.filter( is_deleted=0, order_status__in=[4], order_type=0) order_list_data = order_list.values('user_id', 'invoice__bill_no', 'invoice__bill_date', 'invoice__transaction_invoice__transaction_amount', 'invoice_id').annotate( customer_gross_sum=Sum('invoice__original_amount')-Sum('invoice__discount_amount')+Sum('invoice__tax_amount'), dcount=Count('user_id'), customer_paid_sum=Coalesce(Sum('invoice__transaction_invoice__transaction_amount'), Value(0))) transaction_list = Transactions.objects.filter( is_active=1,transaction_status= True).order_by('-invoice_id') transaction_amount = transaction_list.values( 'invoice__transaction_invoice__transaction_amount') context = { "order_list_data": order_list_data } template = loader.get_template('custom_admin/ledger/ledger.html') return HttpResponse(template.render(context, request)) -
how to generate a excel report of the customers?
class customer(models.Model): name = models.CharField(max_length=50) class info(models.Model): email = models.EmailField(max_length=250) phone_number = models.CharField(max_length=10, blank=False, null=False, unique=True) name = models.ForeignKey(customer,on_delete=models.CASCADE) class detail(models.Model): proof = models.ForeignKey(customer,on_delete=models.CASCADE) aadhar = models.ImageField(upload_to='images/', height_field=None, width_field=None, max_length=100,default=True) -
Django decorator, redirect user to 404 if they access unauthorized page?
I have created a decorator using users_passes_test and it works perfectly, but my requirement is as follows, If user is not authenticated: Then user needs to be redirected to login page Else, if user is authenticated but doesnt have access to the page: Then they need to be redirected to 404page How to modify my decorator according to the above need ? from django.contrib.auth.decorators import user_passes_test from django.contrib.auth import REDIRECT_FIELD_NAME def is_student(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): actual_decorator = user_passes_test( lambda u: (u.is_authenticated and u.role == 'student'), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator This is my decorator, please help ! -
Show logs and progress of a cmd command live on a web Page python
When the user clicks a button in django web page, it should run a cmd command with which it should also show the progress and logs of the command live on the page. I am able to run the command through a python function but not able to display logs and progress simultaneously. Pls help. Thanks in advance.