Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serving gzip content from Django TemapleView
I am using TemplateView to render my pages. Recently I started using webpack to compress my js files into a gzip format. I now want to modify my Template view to render the gzip file. Currently I'm setting the TemplateView's component field to <my_component>.js and I want to change it to <my_component>.js.gz. For that I need to set up the content-encoding header param of the response to 'gzip'. Is there a way to do it somehow in the TemplateView class? I dont want to change the class because I dont really want to deal with the HttpResponse builerplate. -
Configure batabase for production/project managment
My ultimate goal is to create a Django based (so with Python) web application to handle production activities (at work). In other word, something similar to project managment app, with different task for each project etc. But, before thinking about Django "world", I was thinking about how to define the underlying database. First of all let me explain what I mean. Let's assume that I have to produce object OBJ1. To do that I have to complete a certain number of tasks, say TSK1, TSK2,TSK3. The same for OBJ2, OBJ3 and so on... So, each "Object" has its own (different from object to object) sequence of tasks, with their own duration. Now I may have to produce 5 pieces for OBJ1, 40 for OBJ2, and so on, and every "instance" of OBJx could have different delivery date (tasks have different duration, from 1 hour to 7 days for example, it depends). I'd like to be able (at the end of the project) to add every OBJs to a page where I can update the tasks status, to control the progress and check for delay and so on. At the end... I'd like to be able to "handle": different project (obj) … -
Django Crispy Forms - Display List of Dictionaries
Take the following list of dictionaries as an example: {"host": "test-01", "service": "tomcat"}, {"host": "test-02", "service": "tomcat"}, {"host": "test-03", "service": "tomcat"}, {"host": "test-04", "service": "tomcat"}, {"host": "test-05", "service": "postgres"}, {"host": "test-06", "service": "tomcat"}, {"host": "test-07", "service": "tomcat"}] I essentially want to create a HTML message for each dictionary saying what service is going to be restarted on what server. However, I'm not sure what the best way of going about this is. I've tried the below to no avail: views.py def restart_es_services_confirm(request): systems = [{"host": "test-01", "service": "tomcat"}, {"host": "test-02", "service": "tomcat"}] form = ServicesConfirm(request=request) if request.method == 'POST': return HttpResponseRedirect('restart_services.html') else: form = ServicesConfirm(request=request) return render(request, 'restart_services_confirm.html', {'form': form}, {'systems': systems}) restart_services.py class ServicesConfirm(forms.Form): reconfirm = forms.BooleanField(required=True, label='I confirm these services can safely be restarted.',widget=forms.CheckboxInput(attrs={})) def __init__(self, *args, **kwargs): request = kwargs.pop("request") super().__init__(*args, **kwargs) systems = request.session['systems'] for system in systems: host = system['host'] service = system['service'] message = ("Restart " + service + " on " + host) self.helper = FormHelper() self.helper.add_input(Button('cancel', 'Cancel', css_class='button button--wide button--black', formvalidate='formnovalidate', onclick="window.location.href = '{}';".format(reverse('home')))) self.helper.add_input(Submit('deploy', 'Deploy', css_class='button button--wide button--white')) self.helper.form_method='POST' self.helper.layout = Layout( Fieldset( 'Confirmation', Row( Column('reconfirm', css_class='form-group col-md-14 mb-0') ) ) ) restart_services_confirm.html: <!doctype html> <html lang="en"> {% load static %} … -
Django - How to query a list inside of a filter method
I am new to Django and I want to query a list inside of an object. I have a list of Batches and each batch has a BatchComment list. Both of them has a User property. What I want to do is get batches where user has a comment and only get ones where the last comment is not made by the user. How can I achieve this? Currently I am retrieving batches that user has comment by Batch.objects.filter(comments__user=self.request.user) I want something like Batch.objects.filter(comments__user=self.request.user).filter(comments_last__user!=self.request.user) -
input_formats in Django ModelForm DateTimeInput throwing TypeError
I have seen a lot of questions on this and all the answers seem to be because input_formats was incorrectly being placed on the DateTimeField on the model and not on the form. Well, I'm trying to do this on the ModelForm and I'm still getting an error. Can anyone see where I may be going wrong here? models.py class Vacancy(models.Model): deadline = models.DateTimeField(blank=True, null=True) forms.py class CreateVacancyForm(ModelForm): class Meta: model = Vacancy fields = ["deadline"] widgets = { "deadline": forms.DateTimeInput(format='%d/%m/%Y %H:%M', input_formats=['%d/%m/%Y %H:%M'], attrs={ 'class': 'form-control' }) } The error: line 56, in Meta "deadline": forms.DateTimeInput(format='%d/%m/%Y %H:%M', TypeError: __init__() got an unexpected keyword argument 'input_formats' I am using Django version 3.1.1 -
How to handle 0,1 or more queryset results
How can i handle if queryset have to give me 0,1 or more results? Something like this i thought could work, but it didn't... class Board_dets_view (DetailView): template_name = 'board.html' model = Board def get_context_data(self, **kwargs): context = super(Board_dets_view, self).get_context_data(**kwargs) id_board = self.object.id #se get dà errore, uso filter, se da errore filter restituisco vuoto if not Column.object.filter(board_id=id_board): #se filter non funziona ho 0 o 1 risultati if not Column.object.get(board_id=id_board): # se get non funziona ho 0 risultati return context #restituisco vuoto #ho un risultato e proseguo if not Column.object.filter(board_id=id_board): id_column = Column.object.get(board_id=id_board) context['column_list'] = Column.object.get(board_id=id_board) context['card_list'] = Card.object.filter(column_id=id_column) return context if not Column.object.get(board_id=id_board): id_column = Column.object.filter(board_id=id_board) context['column_list'] = Column.object.filter(board_id=id_board) context['card_list'] = Card.object.filter(column_id=id_column) return context -
Django - retrieve api url from template and pass to views
I am using Cryptocompare.com api to load news from cryptocurrencies world. In the template I am looping through it show it on the home-page. I would like to add feature that if you click send button it will send an email to you with the link for the news you just clicked. What is the best way to do it? I tried that, but I dont know how to link the clicked element with the url in views. def home(request): # Grab Crypto News api_request = requests.get('https://min-api.cryptocompare.com/data/v2/news/?lang=EN') api = json.loads(api_request.content) return render(request, 'crypto/crypto_home.html', {'api': api}) def SendLink(request): if request.method == 'POST': subject = 'Link to crypto news' from_email = 'test@gmail.com' message = 'Hello {}, here is your link:'.format(request.user) to_email = [request.user.email] send_mail( subject, message, from_email, to_email ) return HttpResponseRedirect(reverse('crypto-home')) Template: {% for x in api.Data %} <div class='col-sm'> <div class="card"> <img class="card-img-top" src="{{ x.imageurl }}" alt="{{ x.source }}"> <div class="card-body"> <h5 class="card-title">{{x.title}}</h5> <p class="card-text">{{ x.body|safe }}.</p> <div class="btn-group btn-group-sm" role='group'> <a href="{{x.url}}" target="_blank" class="btn btn-primary">Read More</a> <form method="post" action="{% url 'send_link' %}"> {% csrf_token %} <button id="{{x.id}}" target="_blank" class="btn btn-primary">Send to e-mail</button> </form> </div> </div> </div> </div> {% endfor %} I would like to add link from template 'x.url' to … -
don´t create duplicated objects. django, python
I created a script to avoid creating duplicate objects but it still created the same objects when I run the command 3 times it creates them 3 times over and over again. I would like you to help me and know what is wrong with my code. from django.core.management.base import BaseCommand from jobs.models import Job import json from datetime import datetime import dateparser class Command(BaseCommand): help = 'Set up the database' def handle(self, *args: str, **options: str): with open('static/newdata.json', 'r') as handle: big_json = json.loads(handle.read()) for item in big_json: if len(item['description']) == 0: print('Not created. Description empty') continue dt = dateparser.parse(item['publication_date']) existing_job = Job.objects.filter( job_title = item['job_title'], company = item['company'], company_url = item['company_url'], description = item['description'], publication_date = dt, salary = item['salary'], city = item['city'], district = item['district'], job_url = item['job_url'], job_type = item['job_type'], ) if existing_job.exists() is True: print('This Job already exist') else: Job.objects.create( job_title = item['job_title'], company = item['company'], company_url = item['company_url'], description = item['description'], publication_date = dt, salary = item['salary'], city = item['city'], district = item['district'], job_url = item['job_url'], job_type = item['job_type'], ) self.stdout.write(self.style.SUCCESS('added jobs!')) -
Django: While condition in annotations
I got stuck in making a query in which I want to annotate a field and make use of while condition. PROJECT CONFIGURATION PYTHON = 3.9 Django = 3.1.3 My models: class Worker(models.Model): name = models.CharField('Worker Name', max_length=100, unique=True) joining_date = models.DateField('Joining Date', auto_now_add=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.name = self.name.title() super(Worker, self).save() def __str__(self): return self.name class Meta: db_table = 'workers_details' class Article(models.Model): name = models.CharField('Article Name', max_length=200, unique=True) date_created = models.DateField('Created Date', auto_now_add=True) def __str__(self): return str(self.name) + str(self.id) class Meta: db_table = 'articles' class ArticleDetail(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) date_created = models.DateField(auto_now_add=True) last_updated = models.DateField(auto_now=True) work_type = models.CharField('Type of Work', max_length=255) def __str__(self): return str(self.article.name) + " " + str(self.work_type) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.work_type = self.work_type.title() super(ArticleDetail, self).save() class Meta: db_table = 'article_details' class ArticleRate(models.Model): article_detail = models.ForeignKey(ArticleDetail, on_delete=models.CASCADE) effective_date = models.DateField("Effective Date") rate = models.FloatField("Rate") def __str__(self): return str(self.article_detail.article.name) + " " + str(self.article_detail.work_type) + " " + \ str(self.rate) class Meta: db_table = 'article_rate' class DailyRecord(models.Model): date = models.DateField() worker_name = models.ForeignKey(Worker, on_delete=models.PROTECT) rate = models.ForeignKey(ArticleRate, on_delete=models.PROTECT) pieces = models.IntegerField('No. Of Pieces') minutes_printing = models.FloatField('Screen Printing Time') def __str__(self): return str(self.date) + " " + str(self.worker_name.name) + " " + … -
how to run some web scrapping script in django webapp
i want to create a django webapp for electronic component selection tool. one of its functionality will be to show all products available. i have written script to do so. which works well in code editor. it shows output like this: (1, 'Automation and Control') (2, 'Accessories') (3, 'Controllers - Accessories') . . . i have recently started learning django.and i know how to create views, render html pages etc. what i am really struggling with is how to and where to use my script in the django webapp so that when user is directed to home page all the products will be shown code that i have written: import requests import bs4 res = requests.get("https://www.digikey.in/products/en") soup = bs4.BeautifulSoup(res.text,"lxml") base_url = "https://www.digikey.in" mydivs = soup.find_all("a", {"class": "flymenu__item-title"}) name_link = {} count = 1 for i in mydivs: name = i.getText() link = i.get('href') name_link[name] = link count = 1 name_num = {} for i in name_link.keys(): name = i name_num[count] = name count += 1 for pair in name_num.items(): print(pair) what i expect is where to put this code in django app so that when user visits http://127.0.0.1:8000/ output shown as above will be shown to user -
Django test render_to_string() without request
I want to write a test for my function: def render_email_body(ticket, action_type, comment): return render_to_string( action_to_body_template[action_type], { "issue_key": ticket.get_pk(), "comment": comment }, ) Basically I want to check if generated text comes from templates/emails/bodies/some_file.html (action_to_body_template[action_type] points to the location of the file). However assertTemplateUsed function takes a request as a parameter. So my question is how can I check which template was used, without a request. -
Why does WebSocket onmessage event not work
When I send data to the WebSocket nothing happens and messages don't appear in the div elements. I don't know where is a problem: in consumer class or in javascript. Here is my javascript: {% extends 'base.html'%} {% block title %}Chat room for '{{ course.title }}'{% endblock %} {% block content %} <div id = 'chat'> </div> <div id = 'chat-input'> <input id = 'chat-message-input' type = "text"> <input id = 'chat-message-submit' type = "submit" value = "Send"> </div> {% endblock %} {% block domready %} //creating url to connect to websocket var url = 'ws://' + window.location.host + '/ws/chat/room/' + '{{ course.id }}/'; var chatSocket = new WebSocket(url); // this func is called every time a message recieved through the WebSocket chatSocket.onopen = function(){ chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data.message; console.log('message') // accessing the chat div element and appending a div element with the message var $chat = $('#chat'); $chat.append('<div class = 'message'>' + message + '</div>'); // scroll to show all messages $chat.scrollTop($chat[0].scrollHeight); // scrollHeight is used to get a hight value of the given element console.log('OK'); }; chatSocket.onclose = function(e){ console.error('Chat socket closed unexpectedly'); }; var $input = $('#chat-message-input'); var $submit … -
Testing django mail and attachment return empty
I'm trying to test mails with attachment, I'm attaching the files something like this: # snippet of send_pdf_mail mail = EmailMessage( subject=subject, body=message, from_email=from_email, to=recipient_list, ) dynamic_template_data.update({'subject': subject}) mail.content_subtype = 'html' mail.dynamic_template_data = dynamic_template_data mail.template_id = dynamic_template_id if attachment: attachment.open() mail.attach(basename(attachment.name), attachment.read(), guess_type(attachment.name)[0]) attachment.close() return mail.send(fail_silently=False) then my test is something like this: f = open('tests/test.pdf', 'rb') user.pdf.save('test.pdf', File(f)) f.close() send_pdf_mail(user) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to[0], user.email) But when I try to check if there are attachment via: print(mail.outbox[0].attachments) It returns an empty list so I'm not sure why but I tested the code and I can confirm that this indeed includes an attachment when sending an e-mail. -
Django wizard forms and dynamic formset creation
Usually, in a wizard, we declare forms or formsets in static way, for example with something like: form_class=formset_factory(MyForm, min_num=1, extra=5) # let's say this is step '4' But now, what if I need data from step 3, to know how to define the min_num or extra value for the formset of step 4? I was thinking of doing such thing in the get_form() method: def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) # .... elif step == '4': step3_data = self.storage.get_step_data('3') # ... here I would parse step 3 data, to be able to define: computed_step_4_min_num = 5 computed_step_4_extra = 10 # And here I would need to call formset_factory(min_num=computed_step_4_min_num, extra=computed_step_4_extra), # but how? This is obviously not the right place for this call. While it's easy to edit form fields attributes in the get_form() method, I did not find a way to define the right number of forms of a formset, in a dynamic way. I read documentation but I could have missed it. Thanks for your help. -
Can i make HTML forms in Django without using django forms API and Model Forms
If yes, what the pros and corns if no, what the pros and corns Actually, I want to build HTML forms without the Django Form API and ModelForm -
Creating Two Custom Singin Forms using django_allauth
I am creating a small system that has two users, both of these users need singup forms. To allow social accounts and ease of use i have used django_allauth. But i ran into a problem of creating two custom signin forms with different fields. i have used multiple stackoverflow answers but unfortunately none have helped if anything they are now adding to the confusion ... Multiple user type sign up with django-allauth Multiple signup, registration forms using django-allauth I find it hard to believe that this is not a use case that comes up a lot, someone must have done this before. My current code has 2 custom signup forms, 2 custom sign-up views and two custom URLs where the forms should be rendered. But they are both using the same form and I have no idea why. can anyone shed any light on the situation? from .models import GraduateUserProfile from django import forms from allauth.account.forms import SignupForm import datetime def year_choices(): return [(r, r) for r in range(2015, datetime.date.today().year + 1)] def current_year(): return datetime.date.today().year class GraduateUserSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(GraduateUserSignupForm, self).__init__(*args, **kwargs) self.fields['first_name'] = forms.CharField(required=True) self.fields['last_name'] = forms.CharField(required=True) self.fields['phone_number'] = forms.CharField(required=True) self.fields['degree_course_name'] = forms.CharField(required=True) self.fields['graduation_year'] = forms.TypedChoiceField(coerce=int, … -
Define permissions to existing users for viewing or modifying other users
I'm currently learning my way around the permission framework in Django and I'm looking to define a set of permissions to a user, which defines if they can see or modify other users in the system. I'm using the django.auth framework on a multi-schema database where each schema has its own set of users. I want to essentially apply this, but to the built-in users model. class Meta: permissions = ( ("can_view_users", "Can view all users"), ("can_modify_users", "Can modify all users"), ("can_password_reset_users", "Can reset passwords for all users"), ("can_delete_users", "Can delete all users"), ) However I cannot seem to find any documentation on applying this logic to the built-in authentication framework. -
Django Rest Framework - 'User' object has no attribute 'payments'
I have been spending quite a lot of time trying to understand this error I got. From models.py class Company(models.Model): name = models.CharField(max_length=100, unique=True, default="") email = models.CharField(max_length=100, unique=True, default="") password = models.CharField(max_length=100, unique=True, default="") bsb = models.IntegerField(default=0) account = models.IntegerField(default=0) sign_up_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Payment(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="payments") name = models.CharField(max_length=100, unique=True, default="") bsb = models.IntegerField(default=0) account = models.IntegerField(default=0) created_date = models.DateTimeField(auto_now_add=True) paid_date = models.DateTimeField(default=datetime.now() + timedelta(days=36500)) status = models.IntegerField(default=0) and from serializers.py from rest_framework import serializers from .models import Payment, Company class PaymentSerializer(serializers.ModelSerializer): company = serializers.ReadOnlyField(source='company.name') class Meta: model = Payment fields = ['company', 'name', 'bsb', 'account', 'created_date', 'paid_date', 'status'] class CompanySerializer(serializers.ModelSerializer): payments = serializers.PrimaryKeyRelatedField(many=True, queryset=Payment.objects.all()) class Meta: model = Company fields = ["name", "email", "password", "payments", "bsb", "account", "sign_up_date"] As you can see, I have included the related_name as "payments" for company attribute in Payment class. But when I go to http://localhost:8000/bill_payer/resources/company I got the following error: AttributeError: 'User' object has no attribute 'payments' I have verified that my Company class do indeed have the payments class through manage.py shell. Any idea? I am new. Here's views.py in case it is important: class PaymentList(APIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get(self, request): payments … -
Got AttributeError when attempting to get a value for field `email` on serializer `UserViewSerializer`
I am trying to attribute Likes to the articles but i don't know why i am getting this error. Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class LikeUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='userlikes') profile = models.ForeignKey(User,on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now=True) Serializers.py class UserViewSerializer(serializers.HyperlinkedModelSerializer): userlikes = UserSerializer(many=True) class Meta: model = User fields = ('id','email','username','userlikes',) I defined everything right,no typo or so. -
how to execute Python script including Argparse, CV2 on web?
I am creating a webpage by using this face swap Python code. But I don’t know how to execute the command on the web application created with Django. https://github.com/wuhuikai/FaceSwap Here is a concept of the webpage: enter image description here To execute the python script, need to type like this as explained. python main.py --src imgs/test6.jpg --dst imgs/test7.jpg --out results/output6_7.jpg --correct_color However, wondering if it is possible to execute on the web application with a trigger button. Thank you for your help in advance. #! /usr/bin/env python import os import cv2 import argparse from face_detection import select_face from face_swap import face_swap if __name__ == '__main__': parser = argparse.ArgumentParser(description='FaceSwapApp') parser.add_argument('--src', required=True, help='Path for source image') parser.add_argument('--dst', required=True, help='Path for target image') parser.add_argument('--out', required=True, help='Path for storing output images') parser.add_argument('--warp_2d', default=False, action='store_true', help='2d or 3d warp') parser.add_argument('--correct_color', default=False, action='store_true', help='Correct color') parser.add_argument('--no_debug_window', default=False, action='store_true', help='Don\'t show debug window') args = parser.parse_args() # Read images src_img = cv2.imread(args.src) dst_img = cv2.imread(args.dst) # Select src face src_points, src_shape, src_face = select_face(src_img) # Select dst face dst_points, dst_shape, dst_face = select_face(dst_img) if src_points is None or dst_points is None: print('Detect 0 Face !!!') exit(-1) output = face_swap(src_face, dst_face, src_points, dst_points, dst_shape, dst_img, args) dir_path = … -
django channels async consumer blocking on http request
I have the following async consumer: class MyAsyncSoncumer(AsyncWebsocketConsumer): async def send_http_request(self): async with aiohttp.ClientSession( timeout=aiohttp.ClientTimeout(total=60) # We have 60 seconds total timeout ) as session: await session.post('my_url', json={ 'key': 'value' }) async def connect(self): await self.accept() await self.send_http_request() async def receive(self, text_data=None, bytes_data=None): print(text_data) Here, on connect method, I first accept the connection, then call a method that issues an http request with aiohttp, which has a 60 second timeout. Lets assume that the url we're sending the request to is inaccessible. My initial understanding is, as all these methods are coroutines, while we are waiting for the response to the request, if we receive a message, receive method would be called and we could process the message, before the request finishes. However, in reality, I only start receiveing messages after the request times out, so it seems like the consumer is waiting for the send_http_request to finish before being able to receive messages. If I replace await self.send_http_request() with asyncio.create_task(self.send_http_request()) I can reveive messages while the request is being made, as I do not await for it to finish on accept method. My understanding was that in the first case also, while awaiting for the request, I would be … -
Store a list of values in Django keys with a single submit
I can get the values of all fields as below in the views.py if request.method == 'POST': teacher_get = request.POST.get('teacher') department_get = request.POST.get('department') subject_get = request.POST.get('subject') semester_get = request.POST.get('semester') answers = [v for q, v in request.POST.items() if q.startswith('question_')] Now I want to store these values in the Student class which most of its fields are foreign key. class Student(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) department = models.ForeignKey(Department, on_delete=models.CASCADE) semester = models.ForeignKey(Semester, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) For example, a student login to the form page and start answering questions, at the end when he/she clicks submit button, All questions have their answer. In other words, after submission I have for example 15 Student objects which each object belongs to a specific question. My form looks like this: <form action="{% url 'question'%}" method="POST"> {% csrf_token %} <select name="teacher"> {% for teacher in teacher %} <option value="{{ teacher.name }}">{{ teacher.name }}</option> {% endfor %} </select> </div> <div> <select name="department"> {% for department in department %} <option value="{{ department.name }}">{{ department.name }}</option> {% endfor %} </select> </div> <div> <select name="semester"> {% for semester in semester_choices %} <option value="{{ semester.0 }}">{{ semester.1 }}</option> {% endfor %} … -
How commit transaction.atomic()
I have view with atomic transaction. @transaction.atomic def my_view(request): try: with transaction.atomic(): conn = connect_to_db conn.execute("some raw sql query") #do some another stuff except Exception as e: #handle errors # here need to commit transaction I'm not sure, how can I commit transaction, after try catch block. Any help appreciate -
how to restrict other people than admin to access specific url in django?
hello guys so i have this django project which has 2 application inside it one is the website that only admin have access and one is call back server, currently right now only the feature inside of website i know to restrict people to access it because i make condition where it need to login and is an admin to access it, but the login page i have not done anything to restrict other people to access it so i need you guys help how can i restrict other people that not admin to access the login page? , here's my code for now hope it help. view.py (dashboard) def loginscreen(request): if Account.objects.count() <= 0: return redirect("setup_superadmin") elif request.user.is_authenticated and request.user.gambar != '': return redirect("mikrotikadmin/dashboard") else: if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username,password=password) if user is not None: get_account_admin = Account.objects.get(username=username) user.is_online = True user.save() login(request,user) if get_account_admin.gambar != '': return redirect("mikrotikadmin/mikrotiklogin") else: messages.error(request,"account blum lengkap") return redirect("admin_info") else: messages.error(request,"account tidak ada") return redirect("/") else: return render(request,"login.html") url.py (dashboard) urlpatterns = [ path("",views.loginscreen), path("logout",views.logoutscreen,name="logout"), path("setup_superadmin",views.setup_superadmin_server,name="setup_superadmin"), path("admin_account",views.akun_admin,name="admin_account"), path("admin_info",views.halaman_isi_info_admin,name="admin_info"), path("akun_manager",views.akun_manager,name="akun_manager"), ]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Detecting Django/Python None value inside JS code
Actually, it is a question of best practice and elegance. Imagine I have JS code like this: my_js_func() { let var_coming_from_backend = {{ some_var || '' }} if (...) { } } What is the most proper way to check some_var is None? Currently, I am doing that this way: let var_coming_from_backend = {{ some_var|default:'' }} if (var_coming_from_backend == '') { } But it seems like junk code to me.