Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check if user had filled questionnaire before with Django
I'm working on a questionnaire and I made a page where user have a list of which questionnaires to fill and which did he filled before but I have stucked. I like to check if the user filled a form/questionnaire before and if he didn't show him the questionnaire link. My solutions doesn't work because it checks the db just if the user filled the questionnaire but if he did not (no row for him in the db) it shows a blank cell in my table. (I don't know if exists query could be a solution but I can't made it work) main.html {% for i in oke_vezetoi %} {% if i.vezetoi_ok == True %} <td><button class="btn btn-sm btn-outline-info"> <a href="{% url 'stressz:vezetoi_item' %}">Kitöltöm</a></button> <td><i class="fas fa-running fa-2x text-dark"></i></td> {% else %} <td class="text-success text-uppercase">Kitöltötted</button> <td><i class="fas fa-check fa-2x text-success"></i></td> {% endif %} {% endfor %} views.py def main(request): oke_vezetoi = Vezetoi.objects.filter(user_name=request.user) oke_stressz = Stressz_teszt.objects.filter(user_name=request.user) context = { 'oke_vezetoi': oke_vezetoi, 'oke_stressz': oke_stressz, } return render(request, 'stressz/main.html', context) models.py class Vezetoi(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) vezetoi_v01 = models.IntegerField( null=True) vezetoi_v02 = models.IntegerField( null=True) vezetoi_v03 = models.IntegerField( null=True) vezetoi_v04 = models.IntegerField( null=True) vezetoi_v05 = models.IntegerField( null=True) vezetoi_v06 … -
How to save boolean value in to database while pressing html button using django
How to save the boolean value as true to database also route to another page. While we press continue button to save True value to db using django model also route to another page as welcome page. #models.py class Tutorial(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_tutorial = models.BooleanField(verbose_name=_('tutorial'), default=False) #views.py def tutorial_page(request): return render(request, "home/tutorial_page.html") #urls.py from . import views as homeview path('tutorial-page/', homeview.tutorial_page) #tutorialpage.html <article> <h2>demo</h2> <p>press <a href="https://localhost:8000/welcomepage/">continue</a> to skip the tutorial on next time </p> </article> -
Django redirect user upon login failure at /complete/auth0/
I'm using Django with Auth0 for authentication. Sometimes the login fails on Auth0 and redirected to my Django server with /complete/auth0/ with a token indicating error. This reaches my backend at the AUTHENTICATION_BACKENDS class, calling the function auth_complete, which calls process_error. This throws an exception and reaches the http500 page. The question is how should I handle that within these functions? How can I redirect the user to some page (e.g /login_failed.html) to show the client and them decide what to do -
Why can't I enter the admin interface in django after costumizing the user model?
So I have been trying to customize the user model of my django program, my model.py looks like this from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.core.validators import MaxValueValidator, MinValueValidator from django.utils.translation import gettext_lazy as _ from django.utils import timezone # Create your models here. class costumer_base_manager(BaseUserManager): def create_user(self, email, username,firstname, lastname, password, contact, **other_fields): if not email: raise ValueError("Please provide email") email = self.normalize_email(email) user = self.model(email=email, username=username, firstname=firstname, lastname=lastname, password=password,contact=contact, **other_fields) print(password) user.set_password(password) print(password) user.save() return user def create_superuser(self, email, username,firstname, lastname, password, contact, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', False) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must assign is_staff = True') return self.create_user(email, username, firstname, lastname, password, contact, **other_fields) class costumer(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email"),unique=True, blank=False) username = models.CharField(max_length=100, unique=True) firstname = models.CharField(max_length=100, blank=False) lastname = models.CharField(max_length=120, blank=False) start_date = models.DateTimeField(default=timezone.now) about = models.TextField(_("about me"), max_length=500, blank=True) investing_style = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(3)]) contact = models.PositiveIntegerField(default=0,validators=[MinValueValidator(9000000001), MaxValueValidator(9999999999)]) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = costumer_base_manager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'firstname', 'lastname', 'contact'] def __str__(self): return self.username and it worked after makemigrations and migrate I am also able to create super user here after createsuperuser As you can see I actually printed … -
How to pass multiple values for query_serializer in swagger?
In the below code I am trying to give two values to query_serializer , but it throws SyntaxError: positional argument follows keyword argument, how to handle it ? class SampleView(APIView,LimitOffsetPagination): permission_classes = (permissions.IsAuthenticated,) @swagger_auto_schema( query_serializer=SampleSerializer,PaginationSerializer, responses={status.HTTP_200_OK: UserCommentsSerializer(many=True), status.HTTP_404_NOT_FOUND:[]}, operation_id="comments", ) -
For loop results line by line printing in template using django view
Hi I am newbie to django and I am trying to print the for loop results in a template using django view but I am not able to print all the lines My view: def upload(request): cells= [(1,2,3,4),(3,3,4,5)] i = 0 for cell in cells: a,b,c.d = cell[0],cell[1],cell[2],cell[3] I=[b+d,a+c] i=i+1 print(I) return render(request,'res.html',{"text":I}) res.html: {% for i in text %} <div class="row"> {{ i }} </div> {% endfor %} when I tried only for loop in python IDE my output is [6, 4] [8, 7] but when I tried in django view I am getting only first row [6, 4] and also not able to print this in res.html Please help me out from this thanks in advance -
Pyinstaller for Microservice architecture to support multiple services to one Executable file
We are developing an application driven by a microservices architecture. Django as ORM to the Mobile Application and the database. We additionally have about 4 more python micro-services communicating through WebSockets. We are trying to make these 4+1 ( 4 microservices and 1 Django application ) into one executable file. We are able to make our Django application an executable file separately but not as an integrated architecture. The other 4 microservice files are all pure python code and they communicate using WebSockets as mentioned already. Additionally, we have a caching system by Redis and a data pipeline system by RabbitMq. Is there a way to integrate them all together to one python executable file using PyInstaller or maybe any other method? Let me know if the question is not clear, I will try to explain better than this. -
django to get the field from one model to another model in serailizer
models.py class Batch(models.Model): created_date = models.CharField(max_length=20, blank=True, editable=False) description = models.CharField(max_length=200) user = models.ForeignKey(MyUser, on_delete=models.CASCADE) def save(self, *args, **kwargs): self.created_date = str(date.today()) super(Batch, self).save(*args, **kwargs) def __str__(self): return self.description class File(models.Model): file_path = models.FileField(upload_to=upload_image) batch = models.ForeignKey(Batch, on_delete=models.CASCADE) def __str__(self): return "%s - %s" % (self.batch.user, self.batch) serailzer.py class BatchSerializer(serializers.ModelSerializer): class Meta: model = Batch fields = "__all__" class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = "__all__" As i need to display the description in api from the Batch models output : "data": { "id": 159, "file_path": https://scanner.net/media/accounts/9/60/pexels-photo-4245826.jpeg, "batch": 60 } The expected output in the views is need to get the description from anothe model based on the batch_id expected output "data": { "id": 159, "file_path": https://scanner.net/media/accounts/9/60/pexels-photo-4245826.jpeg, "batch": 60 "description" : abc {description based on batch_id} } please help me , i'm a newbie to django-rest and API -
Python - How do I get classes that rely on each other to be defined in the same file?
I have the following code used in Django: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): groups = models.ManyToManyField(group) class group(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="course", null=True) name = models.CharField(max_length=50) description = models.CharField(max_length=300) def __str__(self): return self.name I made this code to get a user model in django that allows for more fields. However, the new user class requires the group field since a user can join many groups. This is causing an error since the group is defined after class. What do I do to fix this issue? What I really need is just a way to add extra fields to the default User class so I tried it like so from another SE post. -
Django Todo App - Filter by foreign keys results in TypeError
this is my model: from django.contrib.auth.models import User class Task(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title With the following view and URL pattern I get my the todos: class TaskView(viewsets.ModelViewSet): queryset = Task.objects.all() ## get all todos serializer_class = TaskSerializer router.register("todos", views.TaskView) However, I want the todos for a specific owner. I tried this: class TaskView(viewsets.ModelViewSet): queryset = Task.objects.filter(id=id) serializer_class = TaskSerializer router.register("todos/<int:id>", views.TaskView) This results in the following error: TypeError: Field 'id' expected a number but got <built-in function id>. using get instead of filter resulted in the same problem. Why does this error happen and how can I solve it? -
django models without primary key and id
I use two primary keys. In database, this does not result in duplicate errors unless both values are duplicated. But I don't know how to solve this problem in django model. When the primary key is removed and used, an id column is created. But I do not want this. Using unique_together results in an error because the primary key is duplicated. Is there any way to solve this problem? -
Django , how to show 'secondary property' of parent in TabularInline
I try to do tabular inline admin. In the child tab, if we include a ForeignKey field, it will show the str property of that foreign model. But how to also show another property of that foreign model? Here is my models.py class RawMaterial(models.Model): name = models.CharField(max_length=15) ubuy = models.CharField(max_length=5) usell = models.CharField(max_length=5) uconv = models.DecimalField(max_digits = 5,decimal_places=2) def __str__(self): return self.name class Coctail(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Ingredient(models.Model): coctail = models.ForeignKey(Coctail, related_name='ingredient', on_delete=models.CASCADE) rawmaterial = models.ForeignKey(RawMaterial, related_name='ingredient', on_delete=models.CASCADE) qty = models.DecimalField(max_digits = 5,decimal_places=2) def __str__(self): return self.rawmaterial def rawusell(self): return self.rawmaterial.usell rawusell.short_description = 'UOM' Here is my admin.py from django.contrib import admin # Register your models here. from .models import * admin.site.register(RawMaterial) class IngredientInline(admin.TabularInline): model = Ingredient list_display = ('rawmaterial', 'qty', 'rawusell') class CoctailAdmin(admin.ModelAdmin): inlines = [IngredientInline] admin.site.register(Coctail, CoctailAdmin) and here what I got My question is : How to show rawmaterial.usell in Ingredient tab? Sincerely -bino- -
Can i get specific fields from a model as an instance?
models.py class Medicine(models.Model): reference_no = models.AutoField company_name = models.CharField(max_length=30) medicine_name = models.CharField(max_length=50) mfg_date = models.DateField("Mfg Date (MM/DD/YYYY)*") exp_date = models.DateField("Exp Date (MM/DD/YYYY)*") price = models.FloatField() quantity = models.IntegerField() def __str__(self): return self.medicine_name class Sold(models.Model): company_name = models.CharField(max_length=30) medicine_name = models.CharField(max_length=50) mfg_date = models.DateField("Mfg Date (MM/DD/YYYY)*") exp_date = models.DateField("Exp Date (MM/DD/YYYY)*") price = models.FloatField() customer = models.CharField(max_length=30) phone = models.IntegerField() quantity = models.IntegerField() amount = models.FloatField() purchase_date = models.DateField("Purchase Date (MM/DD/YYYY)*") def __str__(self): return self.customer views.py @login_required(login_url='Login') def sellmedicine(request, id): if request.method == "POST": pi = Medicine.objects.get(pk=id) fm = SellMedicineForm(request.POST, instance=pi) if fm.is_valid(): cmp = fm.cleaned_data['company_name'] med = fm.cleaned_data['medicine_name'] mfg = fm.cleaned_data['mfg_date'] exp = fm.cleaned_data['exp_date'] prc = fm.cleaned_data['price'] cus = fm.cleaned_data['customer'] phn = fm.cleaned_data['phone'] qty = fm.cleaned_data['quantity'] amt = fm.cleaned_data['amount'] pdt = fm.cleaned_data['purchase_date'] reg = Sold(company_name=cmp, medicine_name=med, mfg_date=mfg, exp_date=exp, price=prc, customer=cus, phone=phn, quantity=qty, amount=amt, purchase_date=pdt) reg.save() item = int(qty) pi.quantity -= item pi.save() return redirect('Inventory') else: pi = Medicine.objects.get(pk=id) fm = SellMedicineForm(instance=pi) return render(request, 'store/sellmedicine.html', {"form": fm}) forms.py class AddMedicineForm(forms.ModelForm): class Meta: model = Medicine fields = ["company_name", "medicine_name", "mfg_date", "exp_date", "price", "quantity"] class SellMedicineForm(forms.ModelForm): class Meta: model = Sold fields = ["company_name", "medicine_name", "mfg_date", "exp_date", "price", "customer", "phone", "quantity", "amount", "purchase_date"] i want to have something like in which i … -
Logout function in Django not working as Expected
I have not used any middleware, when i click on logout button on my Home Page template, the logout function execute without any error.but when i go back to main page without jumping to login page.. i see myself as logged in user here is my authentiCation/views.py from django.shortcuts import render from django.http import request,HttpResponseRedirect # for user creation & login form from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login # for user related Queries from django.contrib.auth.models import User # imports for test purpose from django.http import HttpResponse # Create your views here. # register page def register_Page(request): if request.method == 'POST': form= UserCreationForm(request.POST) if form.is_valid(): form.save() username= request.POST['username'] password= request.POST['password1'] user= authenticate(request,username=username,password=password) login(request,user) return HttpResponseRedirect('/') else: return HttpResponse('Either the user name is not available or you may have filled the form incorrectly') else: form = UserCreationForm() context= {'form':form} return render(request,'authentication/register_Page.html',context) # login page def login_page(request): if request.method == 'POST': username= request.POST['username'] password= request.POST['password'] # returns user if credentials are valid user= authenticate(request, username=username, password= password) # check if user var contains the user if user is not None: login(request, user) return HttpResponseRedirect('/') else: return HttpResponse('Invalid credentials') return render(request,'authentication/login.html') # logout Page def log_out(request): logout(request) return HttpResponseRedirect('logout_page') authentiCation/urls.py from … -
Databases are not being saved on my Django app deployed on Heroku
I recently deployed my portfolio using django on heroku. The App is on automatically deploy from github settings. It contains a comment-box that looks like this. You can see for yourself at --> https://anujdhillon.herokuapp.com/ The GET and POST requests are all working perfectly fine i.e when I post a new comment, it does show up in the comment list. However, after a few hours all the new comments that are posted are removed automatically and I cannot figure out why it is happening. the django source code --> https://github.com/anujdhillon/my-portfolio The component is written in ReactJS and the following is the source code for it --> import React from 'react'; class CommentSection extends React.Component{ constructor(props){ super(props); this.state = { commentList:[], activeItem: { id:null, content: '', author: '', }, editing: false, } this.fetchComments = this.fetchComments.bind(this); this.handleContentChange = this.handleContentChange.bind(this); this.handleAuthorChange = this.handleAuthorChange.bind(this); this.postComment = this.postComment.bind(this); this.getCookie = this.getCookie.bind(this) }; getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = … -
Receiver function not answering after Signal.send in Django
I'm trying to create a simple twitter bot that recieves info from different API's and posts the tweets based on the info. I'm using a Django for this (not sure if completely needed, but I'm just trying to learn the framework) so I created 2 different apps, one that recieves the information from the API and creates an object (so far this object is just a quote) and send it to another app which handles the twitter publication. The general idea is that my quote app will generate a signal which will be sent to the posting app where I created a function with a receiver decorator so it will be listening all the time. Nevertheless, for some reason the decorator is not working and after sending the signal I get no response. This is the creation of the signal: from django.dispatch import Signal new_quote = Signal(providing_args=['author', 'content']) This is the sending of the signal: quote=Quote.objects.create(author=author, content=content) new_quote.send_robust(sender=quote, author=author, content=content) The object is being created with no problem, already check that. And this is the catching of the signal. from .models import Post from django.dispatch import receiver from quotes.signals import new_quote from quotes.models import Quote @receiver(new_quote, sender=Quote) def post_tweet(Quote, **kwargs): … -
Show only one like button for all the images of user_1
I am building a Image Gallery WebApp and I am trying to show only one like button for all the images uploaded by specific user. BUT it is showing like button for every image of the user (user_1). BUT i am trying to show only like button. models.py class Galler(modyels.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) likes = models.ManyToManyField(User, related_name='gallery_like', blank=True) views.py def gallery_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) template.html {% for video in gallery %} <div class="card-footer"> <form method="GET" class="likeForm d-inline" action="{% url 'mains:gallery_like_dislike' video.id %}" data-pk="{{ video.id }}"> <span id="id_likes{{video.id}}"> {% if user in video.likes.all %} <p style="color:#065FD4;display: inline">{{video.likes.count}}</p> {% else %} <p style="color:black;display: inline">{{video.likes.count}}</p> {% endif %} </span><button name='submit' type='submit' value="like"><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i>Like</button> </form> {% endfor %} Suppose user_1 posted 6 images then below code is showing six like buttons BUT i am trying to show only one like button for all the images. I have no idea, how can i do it. Any help would be really appreciated. -
"Confirm Form Resubmission " on pressing back in the chrome browser in my django project
This is my first web development project. It is basically an e-voting website. The index page is the login page. So, when the user login using valid credentials, the website will take the user to the voting page where that contains a voting form and some other options like feedback, news updates, etc. in the Navigation bar. The login request is "POST". The vote submission request is also "POST". Here, if the user presses other option like submitting feedback or viewing the candidates, will take the user to that respective pages. And if the user presses the back button, the website should take him to the voting page again where he can again use other facilities voting, viewing candidates, or submit feedback. But the problem I face is if the user presses the back button from the 3rd page i.e., feedback page or viewing candidates page, it shows an error "Confirm Form Resubmission". Help me fix this bug. Thank You in advance. What changes should I make? Since this is my first project, there might be a lot of poor coding techniques. So, please suggest me with better codes where I should replace in my code even though if it … -
django / pass multiple models to my ListView
Hi everyone.. It's my first project and I'm trying to pass multiple models to my ListView and get them to my template/index via different context_object_names but there're seem to be shortcut or another way to do it that I'm missing models.py from django.db import models class Kunafa(models.Model): name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default=False) class Baklawa(models.Model): name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default=False) class Crunchy_kunafa(models.Model): name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default=False) class Topping(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() enter code here views.py from .models import Kunafa, Crunchy_kunafa, Baklawa, Topping from django.views.generic import ListView `class HomeView(ListView): model = Kunafa template_name = 'index.html' context_object_name = 'Kunafa' ` `class HomeView(ListView): model = Baklawa template_name = 'index.html' context_object_name = 'Baklawa'` `class HomeView(ListView): model = Crunchy_kunafa template_name = 'index.html' context_object_name = 'Crunchy_kunafa'` `class HomeView(ListView): model = Topping template_name = 'index.html' context_object_name = 'Topping'` # index/template {% extends 'base.html' %} {% block body %} `<div class="album py-5 bg-light"> <div class="container"> <div class="row"> {% for kun in Kunafa %} <div class="col-md-4"> <div class="card mb-4 box-shadow"> <img class="card-img-top" src="https://via.placeholder.com/250x200" alt="card image cap"> … -
Why is Heroku PostgreSQL row count much higher than sum of model instances from my Django app?
My Heroku PostgreSQL utilization is showing 32k rows and 20 tables, when I only have 9 different model types in my Django app, and the highest count on any of these model types is <2000. By I figure by this I should have 18,000 items max (and realistically much less because some of these models only have <100 items. Am I misunderstanding how Django models relate to PostgreSQL row counts? Are there other items being stored in the DB that I am not aware of? Thanks! -
Can I access GCS from html in django's html?
I want to read and visualize the pdb file saved in GCS in ngl viewer. The code to read a file in ngl viewer is as follows. function go(){ stage.removeAllComponents() var pdb = document.getElementById('id_pdbid').value var path = "rcsb://" + pdb stage.loadFile(path, {defaultRepresentation: true}) } Here you can simply change the url to something like https://storage.cloud.google.com/example-storage-bucket/folder/example.pdb, but it will cause CORS issues. So I want to access GCS from the script itself in html. (not using url) Is there a way to access it in html, javascript as well as using python's GCS library? Thank you in advance. -
Validating Form for Class-based view
I hope you guys could tell me how to use validation methods in my forms.py for a single field. My view is a generic.FormView and my form is forms.Form. Here is my view: class ClassSetupView(OrganisorAndLoginRequiredMixin, generic.FormView): template_name = "leads/class_setup.html" form_class = ClassSetupForm def get_success_url(self): return reverse("class-setup-sucess-page") def form_valid(self, form): # Some Other Code return super(ClassSetupView, self).form_valid(form) Here is my form: class ClassSetupForm(forms.Form): date = forms.DateField(help_text="Year-01-01",) clean_date(self): date = self.cleaned_data['date'] if date < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) return date I hope you guys could tell me if it is okay to use the clean_date(self) for the form as a way to validate the field date. I saw several examples online, but I am not sure if clean_date(self) will work for my case. Thank you. -
Django model modification
Ok, i have this django app, where the user fills in their detail and then create a web profile(username and password) from django.db import models class UserDetail(models.Model): first_name = models.CharField(max_length=225) middle_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255) email = models.EmailField() def __str__(self): return self.first_name class WebDetail(UserDetail): # user = models.OneToOneField(UserDetail, on_delete=models.CASCADE, primary_key=True,) username = models.CharField(max_length=255) password = models.CharField(max_length=255) and when i create a user that has a webdetail, it shows empty in the database(django admin) I need help to link the WebDetail to inherit from the userdetail and also they could show up in the database(django admin) Thanks for your contribution :) -
how to use in django ListView (three class model)
I create a table as shown below, and return the object of get_context_data in the first field with a for statement to display the total class name of the academy, and in the second field, I want to get the number of entry_date students for each class. In other words, you want to find the number of students who are satisfied in a specific period of each class. However, I am having a hard time figuring out the number for each class. Any help would be appreciated. [Academy App - models.py] class Academy(models.Model): class_name = models.charfield(max_length='50', blank=True, null=True) [Student App - models.py] class Student(models.Model): student_name = models.charfield(max_length='50', blank=True, null=True) sex = models.charfield(max_length='1', blank=True, null=True) age = models.charfield(max_length='3', blank=True, null=True) academy = models.Foreignkey('academy.Academy', , on_delete=models.SET_NULL, null=True, blank=True) class Attribute(models.Model): entry_date = models.DateField(blank=True, null=True) student = models.Foreignkey(Student, on_delete=models.SET_NULL, null=True, blank=True) [Academy App - views.py] class ListView(ListView): model = Academy context_object_name = 'academies' template_name = 'list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['option_radio'] = self.request.GET.get('optionRadios') context['to_date'] = self.request.GET.get('to_date') context['from_date'] = self.request.GET.get('from_date') if context['option_radio'] == 'period': context['academy_id'] = Student.objects.filter(academy_id=self.id) ---- problem context['entry_date_count'] = Attribute.objects.filter( entry_date__lte=context['to_date'], entry_date__gte=context['from_date'], student_id__in=context['academy_id'] ).count() return context [list.html] <form action="/list" method="GET"> <fieldset> <div class="radio" style="display: inline"> <label> <input type="radio" name="optionRadios" id="optionsRadios1" … -
Is it good practice to use the Django template system and/or its admin site in commercial applications?
As a beginner to web applications and front end stuff, I'm really confused about if it's good practice to use the Django template system and its admin interface in commercial applications. As far as I know, the modern approach for web apps is to modularize them between a back end and a front end. It seems that this modularity has important benefits related to separation of concerns, and that would mean: Creating a Django back end with a REST API to be used by the front end. Creating an independent React or Vue front end that makes requests to the API. With this in mind, while I read the Django tutorial, I was convinced that using templates and the admin site was not a good idea because there would be no modularity, as everything would be inside the Django project, and the UI would also be dependent on Django templates, which seems to be limited by design. But on the other hand it seems that CRUD applications for management in general would benefit a lot from the Django admin interface. I wonder if it's a terrible idea to deploy a system that is an extension of a Django admin site …