Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding github database to a Django project
from django.http import HttpResponse from django.shortcuts import render import hashlib, bcrypt from urllib.request import urlopen, hashlib import time def main(request): return render(request,'main.html') def HashBrut(request): sha1hash = request.POST.get('decoder','default') LIST_OF_COMMON_PASSWORDS =str(urlopen('https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10-million-password-list-top-10000.txt').read(), 'utf-8') time.sleep(5) I am trying to access this"LIST_OF_COMMON_PASSWORDS" from github inside my django project. The python functions works fine in terminal but when i use it inside my views.py file in Django project and try to execute it on the web file, it gives 'A server error occurred. Please contact the administrator.' error. I am new to Django and i don't know what is going wrong. -
How to modify existing data in database on the admin site
from django.contrib import admin from .models import Types @admin.register(Types) class TypesAdmin(admin.ModelAdmin): list_display = [x for x in list(Types._meta._forward_fields_map.keys())] search_fields = ['firsts', 'seconds'] list_filter = ['firsts'] I can only add data, but I can't modify existing data on the admin site. I can only add data, but I can't modify existing data on the admin site. -
Bootstrap4 Custom file input with django-crispy-forms?
I´d like to reproduce the 'custom file input' layout with Django-crispy-forms. Here is the Bootstrap4 custom file input: https://getbootstrap.com/docs/4.0/components/input-group/#custom-file-input <div class="input-group mb-3"> <div class="custom-file"> <input type="file" class="custom-file-input" id="inputGroupFile02"> <label class="custom-file-label" for="inputGroupFile02">Choose file</label> </div> <div class="input-group-append"> <span class="input-group-text" id="">Upload</span> </div> </div> I guess I need to use AppendedText from Django-crispy-forms but I don't get how to do it. -
Unable to add field to Django model
I have the following model: class HadesUser(models.Model): # Database attributes user_id = models.BigAutoField(primary_key=True) django_user = models.OneToOneField(User, on_delete=models.PROTECT, null=False) is_active = models.BooleanField(default=True) created_by = models.ForeignKey('HadesUser', on_delete=models.PROTECT, null=True, db_column='created_by', related_name='%(class)s_created_by') created_datetime = models.DateTimeField(default=datetime.now, blank=True) last_modified_by = models.ForeignKey('HadesUser', on_delete=models.PROTECT, null=True, db_column='last_modified_by', related_name='%(class)s_last_modified_by') last_modified_datetime = models.DateTimeField(default=datetime.now, blank=True) Now I want to add a new field, should be easy, right? So I add: timezone = definition_name = models.CharField(max_length=30, default='UTC', blank=True) Then I just run: python manage.py makemigrations However, I get: (venv) E:\HadesAPI>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: HadesAPI.HadesUser.timezone: (models.E006) The field 'timezone' clashes with the field 'timezone' from model 'HadesAPI.hadesuser'. This error message is so super not clear at all. I am not using "timezone" anywhere, what could be the issue here? -
Coverage test shows the same result
I want my models.py and views.py coverage test percent above 95 however it's been the same over changes that I've made on the tests.py and also most parts of my code in tests.py are shown as missed and they are red even the setUp part and I haven't been successful to realize where the problem is. any help would be highly appreciated models.py import datetime from django.db import models class Author(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() date_of_death = models.DateField(null=True) def is_alive(self): return self.date_of_death is None def get_age(self): if self.date_of_death is None: return datetime.date.today() - self.date_of_birth else: return self.date_of_death - self.date_of_birth def __str__(self): return f'{self.first_name} {self.last_name}' class Book(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Author, on_delete=models.CASCADE) summary = models.TextField() date_of_publish = models.DateField() def get_age(self): return datetime.date.today() - self.date_of_publish def __str__(self): return self.title views.py from django.shortcuts import render from library_management.models import Book def booklist(request, author_age, book_age): books = Book.objects.all() good_books = [] bad_books = [] for book in books: if book.get_age().days // 365 < book_age: if book.author.get_age().days // 365 < author_age: good_books.append(book) else: bad_books.append(book) else: bad_books.append(book) return render(request, 'booklist.html', { 'good_books': good_books, 'bad_books': bad_books }) tests.py from django.test import TestCase from library_management.models import Author, Book def Test_class(TestCase): def setUp(self): … -
Using Latex in Djngo project with django_tex , pdflatex
I am trying to use Latex to build PDFs in Django project using django_tex , pdflatex. I have made setting such that in django setting.py , under INSTALLED_APPS, TEMPLATES . When server started running and the method is called , it is throwing an error while compiling the latex file . Command 'cd "/tmp/tmpvk2or_tb" && pdflatex -interaction=batchmode texput.tex' returned non-zero exit status 127. is the error. I am attaching my code part in Views.py and also my latex file . Views.py from django_tex.shortcuts import render_to_pdf template_name = 'test.tex' context = {'content':'this is the pdf content'} return render_to_pdf(request, 'test.tex', context, filename='test.pdf') test.tex \documentclass{article} \begin{document} \section{ {{ content }} } \end{document} Can someone suggest something on this . And Is latex is the better option to generate pdfs with all backgrounds and all than using xhtml2pdf ? Thanks in advance -
How do I Save and create Two Model user at same time in django?
I have following models Users and Teacher User model is inherited from AbstractBaseUser and Teacher is one to one relation with User. Below is Teacher User Model. class TeacherUser(BaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE, ) faculty = models.CharField(max_length=100) faculty_code = models.CharField(max_length=100) is_full_time = models.BooleanField(default=False) joined_date = models.DateField() objects = TeacherUserManager() Now problem is I want the only one form to be filled by teacher while registering the teacher user.So I tried this in TeacherSerialzier. class CreateTeacherUserSerializer(TeacherUserSerializer): class Meta(TeacherUserSerializer.Meta): fields = ( 'faculty', 'faculty_code', 'is_full_time', 'joined_date' ) class CreateUserSerializer(UserSerializer): techer = CreateTeacherUserSerializer(source='teacheruser') class Meta(UserSerializer.Meta): fields = ( 'username', 'fullname', 'email', 'phone_number', 'password', 'techer' ) extra_kwargs = { 'password': { 'write_only': True, 'style': {'input_type': 'password'} } } The default form given is as below (image). Now on my views.py I tried creating my user and teacher users class CreateUserView(generics.CreateAPIView): serializer_class = serializers.CreateUserSerializer permission_classes = (AllowAny,) def perform_create(self, serializer): return usecases.CreateUserUseCase(serializer=serializer).execute() and The main logic section where I tried creating users is as below usecases.py User = get_user_model() class CreateUserUseCase: def __init__(self, serializer): self._serializer = serializer self._data = serializer.validated_data def execute(self): self._factory() def _factory(self): teacher_user = self._data.get('teacheruser') By default when I fill the above image form I get ordered dictionary and there comes another … -
View with different filter django
I have this view class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') Where I show all posts by a User on a page. I would like to add filters on in my 'side menu', to show on same page only posts by that user AND a selected status. Like below: class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) return Post.objects.filter(author=user, status='Reported').order_by('-date_posted') How can I make 'status' a variable which would be changed my bootstrap button? So what a user choose in a radio or dropdown menu will be a type os 'status' and only that one will be shown. Do I need to call a function each time or? -
how to show current user login posts show in dashboard in django
I am trying to show only login user posts show in the dashboard. Tell me how to show posts in the dashboard. this is my code and how to solve my problem tell me. form.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','decs'] labels = {'title': 'Title', 'decs': 'Decription'} title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control',})) decs = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control',})) views.py def dashboard(request): if request.user.is_authenticated: current_user = request.user posts = Post.objects.filter(user=current_user) else: redirect('/login/') return render( request, "dashboard.html", {'posts':posts} ) Models.py class Post(models.Model): title = models.CharField(max_length=100) decs = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def get_absolute_url(self): return reverse('author-detail', kwargs={'pk': self.pk}) Dashboard.html <h3 class="my-5">Dashboard </h3> <a href="{% url 'addpost' %}" class="btn btn-success">Add Post</a> <h4 class="text-center alert alert-info mt-3">Show Post Information</h4> {% if posts %} <table class="table table-hover bg white"> <thead> <tr class="text-center"> <th scope="col" style="width: 2%;">ID</th> <th scope="col" style="width: 25%;">Title</th> <th scope="col" style="width: 55%;">Description</th> <th scope="col" style="width: 25%;">Action</th> </tr> </thead> <tbody> {% for post in posts %} <tr> <td scope="row">{{post.id}}</td> <td>{{post.title}}</td> <td>{{post.decs}}</td> <td class="text-center"> <a href="{% url 'updatepost' post.id %}" class="btn btn-warning btn-sm">Edit</a> <form action="{% url 'deletepost' post.id %}" method="post" class="d-inline"> {% csrf_token %} <input type="submit" class = "btn btn-danger btn-sm" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> {% else %} <h4 class="text-center … -
I got error when I turn DEBUG true on settings file
I got Error500 when I turn DEBUG True on settings.py but everything is okay when DEBUG is False. python manage.py collectstatic is okay too. Here my settings.py. I will appreciated your help. I use Django 2.2 version. Django settings """ Django settings for samamarche project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import dj_database_url import os import django_heroku -
REST API taking too much time to respond
I have built an API using Django & django-rest-framework. The Django Server is currently deployed on Heroku's Free Hobby Dyno. this is how my API call looks right now, GET https://feasta-postgres.herokuapp.com/menu/get_category/?admin_id=5 I am currently testing my API through POSTMAN. PROBLEM I have noticed that when I call this API for the First time, it takes too much (~1 second) time to respond. Then it becomes Faster for the subsequent calls. Then after some interval it again becomes slow. This is the event waterfall for my first request call, This is the event waterfall for my subsequent request calls, As we can see in the first image, the handshakes are eating up most of the time. Questions Is there any way to optimize the first request? If yes then How? Will this also occur when I call this API from a Deployed React website or is this only a Postman problem? My Best Guess I am using a Free Heroku Dyno, that's why Heroku is being "lazy" to process my request. Upgrading it to the paid one will do my job. -
DRF This field is required
I am working on a DRF backend API and React client. Whenever I send the data back to the server I get an error category: this field is required which is true, but I am providing that field. I have modified the actual create() viewset function in order to add additional data to the logic: class QuestionViewSet(viewsets.ModelViewSet): """ API endpoint that allows user to view and edit Question model """ queryset = Question.objects.all().order_by('-updated_at') serializer_class = QuestionSerializer permission_classes = [permissions.IsAuthenticated] filterset_fields = ['created_by', 'created_at', 'updated_at', 'status', 'score'] def create(self, request, *args, **kwargs): serializer = QuestionSerializer(data=request.data, context={'request': request}) if not serializer.is_valid(): return Response(serializer.errors, status=400) serializer.save(created_by=request.user) return Response({ 'question': serializer.data }) I am getting that 400 status response whenever I send a message that is printed in the same backend console: <QueryDict: {'question': ['test'], 'category': ['2']}> The serializer itself: class QuestionSerializer(serializers.ModelSerializer): category = CategorySerializer() answers = AnswerSerializer(many=True, source='answer_set', allow_null=True, required=False) expert = UserSerializer(required=False) moderator = UserSerializer(required=False) created_by = UserSerializer(required=False) class Meta: model = Question fields = [ 'id', 'category', 'question', 'status', 'expert', 'moderator', 'created_by', 'created_at', 'updated_at', ] I have tried changing category for category_id but it does not work either. My client function is something like this: const query = useQuery(); const urlSufix … -
Unable to Add New Blank Field in Django (DataError)
I am try to create an django application with Seller, Books apps. It was running fine but I wanted to add one more field in my db and added one more field in books\models.py with blank=True. I am trying to add new blank field but unable to migrate. I try to run the code : python manage.py migrate. Error and and code is: models.py from django.db import models from datetime import datetime from book_sellers.models import Seller # Create your models here. class Book(models.Model): seller = models.ForeignKey(Seller,on_delete = models.DO_NOTHING) bname = models.CharField(max_length=100) isbn = models.CharField(max_length=40,blank=True) genre1 = models.CharField(blank=True,max_length=32,choices=[("1","Motivational"),("2","Fiction"),("3","Business"),("4","Children"),("5","Health"),("6","Story")],) genre2 = models.CharField(blank=True,max_length=32,choices=[("1","Motivational"),("2","Fiction"),("3","Business"),("4","Children"),("5","Health"),("6","Story")],) genre3 = models.CharField(blank=True,max_length=32,choices=[("1","Motivational"),("2","Fiction"),("3","Business"),("4","Children"),("5","Health"),("6","Story")],) writerName = models.CharField(max_length=100,blank=True) price = models.IntegerField() number_of_enquiry = models.CharField(max_length=100,blank=True) description = models.CharField(max_length=1000) photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/') list_date = models.DateTimeField(default = datetime.now(),blank = True) is_published = models.BooleanField(default = True) def __str__(self): return self.bname ** Getting this Error ** Traceback (most recent call last): File "C:\Users\HP\OneDrive\Desktop\PROJECT\BookStore\manage.py", line 22, in <module> main() File "C:\Users\HP\OneDrive\Desktop\PROJECT\BookStore\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\HP\OneDrive\Desktop\PROJECT\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = … -
Checkbox filter django
I'm improving my English, be patient I'm using django-filter and in some part of my HTML I have this structure {% if viagens.count == 0 %} <div class="row justify-content-center"> <h3 class="text-danger">O colocador nao fez nehuma viagem</h3> </div> {% else %} <div class="row"> <form action="" method="GET"> {% csrf_token %} # here I want a checkbox that automatically submit the form </form> </div> {% for viagem in viagens %} <p>Placeholder</p> {% endfor %} {% endif %} I don't have javascript knowledge, I need this with pure HTML and Django -
CDN script link not found in Django using bokeh
In my Django base template, I need to download a bokeh script from CDN: <!DOCTYPE html> <html> <head> <link href=”https://cdn.bokeh.org/bokeh/release/bokeh-2.3.1.min.css" rel=”stylesheet” type=”text/css”> <link href=”https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.3.1.min.css" rel=”stylesheet” type=”text/css”> <script src=”https://cdn.bokeh.org/bokeh/release/bokeh-2.3.1.min.js"></script> <script src=”https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.3.1.min.js"></script> {{ script | safe }} <title> Hello World! </title> </head> <body> {{ div | safe }} </body> </html> The bokeh documentation here advises the exact location for its respective version. And they do exist. Without the script, a Django view that is supposed to render a bokeh chart at div does not show anything. Below is my views.py: from django.shortcuts import render from bokeh.plotting import figure, output_file, show from bokeh.embed import components def homepage(request): #Graph X & Y coordinates x = [1, 2, 3, 4, 5] y = [1, 2, 3, 4, 5] #Set up graph plot for displaying line graph plot = figure(title = 'Line Graph', x_axis_label = 'X-Axis', y_axis_label = 'Y-Axis', plot_width = 400, plot_height = 400) # Plot line plot.line(x, y, line_width = 2) # Store components script, div = components(plot) # Return to Django homepage with component sent as arguments which will then be displayed return render(request, 'pages/base.html', {'script': script, 'div': div}) Am I missing anything with respect to the bokeh part here? Thanks. -
using django-tables2 in dashbord
Trying to put django table into dashboard.html page. I can visualize my table in another html file but cant fix how to put inside the dashboard page models.py class Asset(models.Model): type = models.ForeignKey(AssetType, on_delete=models.CASCADE) lc_phase = models.ForeignKey("Asset_Life_Cycle.LifeCyclePhase", on_delete=models.CASCADE) name = models.CharField(max_length=30) # BaseSpatialField.srid() geom = models.GeometryField() views.py from .models import Asset import django_tables2 as tables class AssetTable(tables.Table): class Meta : model = Asset class AssetTableView(tables.SingleTableView): queryset = Asset.objects.all() table_class = AssetTable template_name = 'deneme.html' Tried this but didnt work {% for asset in queryset %} <p>Name {{asset.name}} </span> </p> {% endfor %} -
Django ORM "|" operator returning duplicate items
Say I have a Model class that looks something like: class User: ... projects = models.ManyToManyField(Project, blank=True) subscribed_projects = models.ManyToManyField(Project, blank=True) I have some view logic that returns the contents of both querysets: return self.request.user.projects.all() | self.request.user.subscribed_projects.all() In my particular scenario, assume that the same project won't be in both. Here's the current relationships for one of the users: >>> me = User.objects.get(id=1) >>> me.projects.all() <QuerySet [<Project: A>, <Project: B>, <Project: C>, <Project: D>, <Project: E>]> >>> me.subscribed_projects.all() <QuerySet [<Project: F>]> Here's the part I cannot explain: >>> me.projects.all() | me.subscribed_projects.all() <QuerySet [<Project: A>, <Project: B>, <Project: C>, <Project: D>, <Project: D>, <Project: E>, <Project: F>]> Project "D" appears twice here, even though it only appears in one of the querysets! Now, I can achieve the behavior I want by adding distinct() or using union() instead, but why is it behaving this way? -
service on gke pod that was running fine for a year suddenly starts failing with db connection error
I have been a running a service on gke for more than a year without any problems, but just yesterday I started seeing "some backend services are in an UNHEALTHY" state on the kubernetes services/ingress dashboard. When I look into the pod I see the error message below. I never had any problem before and haven't changed anything with my configuration. How should I go about fixing this ? /usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py”, line 217, in ensure_connection self.connect() File “/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py”, line 195, in connect self.connection = self.get_new_connection(conn_params) File “/usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py”, line 178, in get_new_connection connection = Database.connect(**conn_params) File “/usr/local/lib/python3.7/site-packages/psycopg2/init.py”, line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused -
Filtering objects with json data | Django
When i try to filter the object with the name that i got from the json data the queryset is empty but when i try to filter it with hardcoded value the queryset exists. The name is exactly same in the json data and in the object but it returns empty. name = w.get('name') its type is str. The value is new_template_duke_1 Can you please help why the queryset is empty in this line templates = templates.filter(template_name=name) waba = res.get('waba_templates') templates = MerchantWhatsappTemplate.objects.filter( merchant=merchant, approved=False, rejected=True ) qs = templates.filter(template_name="new_template_duke_1") print(qs) <<<<<<<< Not empty if not templates.exists(): return for w in waba: category = w.get('category') name = w.get('name') <<<<<< "new_template_duke_1" status = w.get('status').upper() rejected_reason = w.get('rejected_reason') templates = templates.filter( template_name=name ) print(templates) <<<<<<< Empty queryset -
How to upload image file with react and django rest framework
Hello All I'm working on a fullstack app using react on the frontend and django on the backend, I'm using the default session authentication and also serving react as a django template through index.html file. I'm currently serve my pages through the django server itself, so everything is will be under the URL: http://localhost:8000/ and I'm also using redux to manage the state. I'm trying to update the UserProfile model by uploading the user image from react and store it in the backend server but it saves the image filename instead of creating a new media folder. UserProfile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_no = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') bio = models.TextField(max_length=500, default='') skills = models.CharField(max_length=255, default='') avatar = models.ImageField( default='', blank=True, null=True, upload_to='avatars') def __str__(self): return self.user.username settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECRET_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Getting an Import Error While trying to Run Cron Job with Django App
I'm trying to create a CRON job to run a script every minute however I'm getting the error: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Inside my crontab -e command: * * * * * /usr/bin/python3 /Users/user/Documents/Program/App/manage.py command Running this my terminal says I get new mail every minute but when I click on the message I get the above importError. I am using a .env file at the root of my directory to keep my API keys secure but I don't think that's important.I'm also not using a virtual environment at the moment but I have tried and however I can't find the correct python version installed into the virtual environment. Running this command python3 ./manage.py command from the command works as expected which is why this is really confusing. -
Django Admin not limiting choices on ManyToMany field
I suddenly am having a problem with my django admin panel. I have the following models: class Role(models.Model): name = models.CharField("Name", max_length=32) class Person(models.Model): name = models.CharField("Name", max_length=64) role = models.ForeignKey(Role) class Team(models.Model): rep = models.ManyToManyField( Person, related_name="rep_on", limit_choices_to={'role__name': 'Sales Rep'}) eng = models.ManyToManyField( Person, related_name="eng_on", limit_choices_to={'role_id__name': "Engineer"}) (The two options in the limit_choices_to dictionaries are the two methods I've tried. In the past it seemed like role_id__name worked, but now it doesn't.) If I create roles for the Sales Rep and Engineer, and create a bunch of people and attach roles, when I create a Team in the admin, I get dropdowns like I expect: There are two problems. Each dropdown contains every Person object, so limit_choices_to doesn't seem to work at all, and of course these relationships are generic "TEAM-PERSON RELATIONSHIPS" and I'd like to be able to at least label those correctly. I swear this worked before, and now it's not working. Any ideas as to what could be causing this? -
Django query by related object with calculated value
I have this Class structure: class A(models.Model): pass class B(models.Model): CHOICE_1 = 'example-1' CHOICE_2 = 'example-2' CHOICE_3 = 'example-3' EXAMPLE_CHOICES = [ (CHOICE_1, 'Example 1'), (CHOICE_2, 'Example 2'), (CHOICE_3, 'Example 3') ] choice = models.CharField(max_length=20, choices=EXAMPLE_CHOICES) important = models.BooleanField() parent = models.ForeignKey(A, on_delete=models.CASCADE, related_name="child") I need to get all A objects that have related B objects filter by: At least one child have important=True At least one child have CHOICES_1 or CHOICE_2 in choice attr. So far the query would be: A.objects.filter(child__important=True, child__choice__in=[CHOICE_1, CHOICE_2]) HERE IT COMES THE QUESTION Also, I need to get an extra calculated field which value should be: If A has only CHOICE_1 childs --> calculated value = "Example 1 only" elif A has only CHOICE_2 childs --> calculated value = "Example 2 only" elif A has childs, some CHOICE_1 and some CHOICE_2 --> calculated value = "Both" -
How to read csv file using pandas from django server
I'm learning Django I have a CSV file in the Django server now I want to show it on an HTML page. can you help me that how to show it on the HTML page? OR How to read a csv file using pandas in html page? -
Django multiple models relationship
I'm making some models and I want to be able to create a match. Each match has its own game. Every game can have a set of rules. The user, when creating the match can choose the game and also, choose one or many rules of the respective game, to apply to the match. Also, the user can create a custom rule. How this is going to be, in terms of models? And how it would work? About the custom rule, I can create a new field for it on the Match model. I thought that the models could be something like that: class Match(models.Model): game = models.OneToOneField(Game) custom_rule = models.CharField(max_length=100) class Game(models.Model): name = models.CharField(max_length=100) class GameRule(models.Model): game = models.ForeignKey(Game) rule = models.CharField(max_length=100) But I'm not sure if it would work. Can someone help me?