Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add search field when add Answer in Django admin panel
I have Answer model in this field i have answer_dependens_on model class Answer(models.Model): question_id = models.ForeignKey( "app.Question", on_delete=models.CASCADE, related_name='answers') answer_title = models.CharField(max_length=100, null=True, blank=True) answer_weight = models.DecimalField(max_digits=9, decimal_places=4, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) answer_dependens_on = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) class Meta: verbose_name = 'Answer' verbose_name_plural = 'Answers' def __str__(self): return "answer={}; question={}".format(self.answer_title, self.question_id) i whant add search in this field -
Why Error when running code for show similar post with taggit in django 3?
I'm currently learning django by following the book Django by example from antonio mele and have reached the stage of how to display the same post using tags. I feel that I have followed the contents of the book well, but still stuck here Error in web browser It happened with the code I made like this: coding in models.py from django.db import models # Create your models here. from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset()\ .filter(status='published') class Post(models.Model) : STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date= 'publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_post') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() tags = TaggableManager() class Meta : ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args = [self.publish.year, self.publish.month, self.publish.day, self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on … -
getting database error on form validation in djongo
i have create a custom user model in django using djongo driver and whenever i tries to add a user with same name or email is show this error but i want to show them error on form i also have a post model which uses the user model class as foreign key so whenever i try to add post with user i ``` class User(AbstractBaseUser, PermissionsMixin): userna='' username = models.CharField( _("username"), max_length=150, unique=True, help_text=_( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." ), validators=[UnicodeUsernameValidator], error_messages={ "unique": _("A user with that username already exists."), }, primary_key=True ) email = models.EmailField( _("email address"), max_length=150, unique=True, error_messages={ "unique": _("A user with that email address already exists."), }, ) first_name = models.CharField(_("first name"), max_length=150, blank=False) last_name = models.CharField(_("last name"), max_length=150, blank=False) date_of_birth=models.DateField(_("date of birth"),blank=False) country=models.CharField(_("country"),max_length=250,blank=False) state=models.CharField(_("state"),max_length=250,blank=False) city=models.CharField(_("city"),max_length=250,blank=False) gender=models.CharField(max_length=10,choices=GENDER_CHOICES,default="Male") profile_photo=models.ImageField(upload_to= upload_to) is_staff = models.BooleanField( _("staff status"), default=False, help_text=_("Designates whether the user can log into this admin site."), ) is_active = models.BooleanField( _("active"), default=True, help_text=_( "Designates whether this user should be treated as active. " "Unselect this instead of deleting accounts." ), ) date_joined = models.DateTimeField(_("date joined"), default=timezone.now) objects = UserManager() EMAIL_FIELD = "email" USERNAME_FIELD = "email" REQUIRED_FIELDS = ['username', 'first_name', 'last_name','date_of_birth','country','state','city','gender'] ``` … -
How to debug a django python custom command in emacs?
How can I debug the closepoll.py buffer in emacs? While every other python script just needs C-c C-c nobody seems to know how to do it with django. I've asked this question with maybe too much detail and a bounty here as well without success. -
How to calculate the remaining number of goods?
I have a table where the receipt of printer paper to the warehouse and their distribution are recorded. How to find the remaining amount of printer paper? For example, there is a table: RedordID Amount Status 000001 30 arrived 000002 2 send 000003 1 send 000004 3 send 000005 10 arrived 000006 1 send It means that the result sholud be 33 (add "arrived" and subtract "send": +30-2-1-3+10-1=33). How to do it? My code: Models.py class PaperReport(models.Model): office = models.CharField('Office', max_length=255) amount = models.CharField('Number', max_length=255) status = models.CharField('Status', max_length=255) dateaction = models.DateField('Date of action') def get_absolute_url(self): return reverse('paper_list') Views.py class PaperReportView(ListView): model = PaperReport template_name = 'paper_list.html' ordering = ['dateaction'] paper_list.html <div> <h2>Number of printer paper in stock: <!-- {{calculation must be there and the result is 33}} --> </h2> <h2>Info about paper</h2> {% for case in object_list %} <div> <p>{{case.dateaction}} for {{case.office}}: {{case.amount}} pieces were {{case.status}}</p> </div> {% endfor %} </div> -
How to filter data by two fields in django model?
Here is queryset and I want to filter by two django fields. #models.py class ExmapleModel(models.Model): first_field = models.IntegerFiled() second_field = models.IntegerField() and here views #views.py class ExampleApiView(ListAPIView): queryset = ExmapleModel.objects.all() serializer_class = ExmapleModelrSerializer permission_classes = (AllowAny,) def get_queryset(self): qs = super().get_queryset() ... if condition: return qs.filter(lambda item: item.first_field < item.second_field) return qs I tried to filter like this, but of course it doesn't work qs.filter(lambda item: item.first_field < item.second_field) -
Set Order of Python Module Reference
Scenario: I am creating a Django python service and trying to run through celery. I have setup python3.7, virtual env, installed requirements successfully and created dependency infrastructure. When I try to run the service, I am getting an error: module 'aspose.email' has no attribute 'message_from_bytes' Root cause is: One dependency library kombu is using this import File "/home/siddhesh/codebase/pstconverter-node/myenv2/lib/python3.7/site-packages/kombu/asynchronous/aws/connection.py", line 3, in <module> from email import message_from_bytes Ideally, the email module should be imported from /usr/lib/python3.7/ and not from aspose library which is inside site-packages Question: How can I tell python to first search for this module from inside the python built-in lib instead of site-packages? In short, how can I set the ordering of lookup. My sys.path result: ['', '/usr/lib/python3.7', '/usr/lib/python37.zip', '/usr/lib/python3.7/lib-dynload', '/home/siddhesh/codebase/pstconverter-node/myenv2/lib/python3.7/site-packages'] -
Django ORM Facing issue in Group By in 3 levels of table
Models: Employee - name, email CuttingJob - employee (ForeignKey), count OrderCuttingDetail - product_name, amount I want to show the employee wise cutting count and it’s amount. employees = Employee.objects.annotate( total_cutting_job_count=Sum(‘cutting_jobs__count’), total_cutting_job_amount=ExpressionWrapper(F(‘total_cutting_job_count’) * F(‘cutting_jobs__order_cutting_detail__amount’), output_field=DecimalField()), ).all() But while running this query, employees are duplicated. Need to group the records based on employee’s name. Kindly suggest a solution for this. I want to show the total amount based on employee wise. Kindly provide a solution for this. -
Django Python ORM models filter case
I need to filter out queryset. My model is like below: class TimeInfo(models.Model): month = models.CharField(_("Дата"), max_length=20) day_of_week = models.CharField(_("День недели"), max_length=15) order_num = models.IntegerField(_("Очередность"), null=True, blank=True) open_time = models.DateTimeField(_("Начало поста")) close_time = models.DateTimeField(_("Время разговения")) Data: qs = [{ "id": 2313, "month": "25 марта", "day_of_week": "Суббота", "order_num": 3, "open_time": "2023-03-25T19:24:00+06:00", "close_time": "2023-03-25T05:18:00+06:00", "locality": 79 }, { "id": 2314, "month": "26 марта", "day_of_week": "Воскресенье", "order_num": 4, "open_time": "2023-03-26T19:26:00+06:00", "close_time": "2023-03-26T05:16:00+06:00", "locality": 79 },] Let's suppose today is 25 of march if datetime.now() is greater than close_time have to return next day: { "id": 2314, "month": "26 марта", "day_of_week": "Воскресенье", "order_num": 4, "open_time": "2023-03-26T19:26:00+06:00", "close_time": "2023-03-26T05:16:00+06:00", "locality": 79 } return todays result if smaller than or equal to { "id": 2313, "month": "25 марта", "day_of_week": "Суббота", "order_num": 3, "open_time": "2023-03-25T19:24:00+06:00", "close_time": "2023-03-25T05:18:00+06:00", "locality": 79 } -
Django cannot add null data from url to database
I create model like this which it should recieve null value without error class ReceiveData(models.Model): api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE) field1= models.FloatField(null=True) field2= models.FloatField(null=True) field3= models.FloatField(null=True) I use is_float to check float def is_float(element: any) -> bool: #If you expect None to be passed: if element is None : return False try: float(element) return True except ValueError: return False def device(request): key = request.GET.get('key') f1 = request.GET.get('f1') f2 = request.GET.get('f2') f3 = request.GET.get('f3') if DeviceKey.objects.filter(api_key=key).exists(): if(is_float(f1) or is_float(f2) or is_float(f3)) recv_data = ReceiveData( api_key = key, field1 = float(f1), field2 = float(f2), field3 = float(f3) ) recv_data.save() I send data by URL link this without f3. http://127.0.0.1:8000/device/?key=002&f1=25&f2=26 It show error like this. field3 = float(f3), TypeError: float() argument must be a string or a number, not 'NoneType' I don't send f3 in URL I think it should be null but it show TypeError. How to fix it? -
Issues Scaling Django Channels application
We have a Django Channels application which in a nutshell functions something like this Client makes /start HTTP request which returns a unique id, say 123. This unique id is written to the database Client makes /start/123 WS request which is handled by channels consumer to create the web-socket after confirming that id 123 does exist in the database Client makes /message/123 HTTP request which server immediately responds to with 200OK after confirming id 123 is valid, but then after doing necessary processing, asynchronously responds to this message on the corresponding web-socket Client waits to read the response on the web-socket Channels layer is Redis and all Database calls are wrapped in sync_to_async with THREAD_SENSITIVE True. We want to support 25,000 concurrent users/clients. We used below setup for testing, all are Ubuntu machines. Setup To simulate the load, we tried a simple Python load simulator. This is what it does In a new thread, make /start call Based on the response to the first call, make /start/unique-id WS call while (True): make /message/unique-id HTTP call wait for the response on web-socket sleep(1 to 5 seconds) It has configuration for number of threads to spawn and initial ramp-up time for all … -
How to link HTML file in Django?
I have just started learning Django, and I am trying to display an HTML file (test.html). However, whenever I go to the /secreturl link, it gives me an error message. This is my views.py from django.shortcuts import render from django.http import HttpResponse def homePage(response): return HttpResponse("this is the home page") def loginPage(response): return HttpResponse("this is the login page") def playPage(response): return HttpResponse("this is the play page") def testPage(response): return render(response, "test.html") This is my urls.py from django.urls import path from . import views urlpatterns = [ path("",views.homePage,name="home"), path("home/",views.homePage,name="home"), path("login/",views.loginPage,name="login"), path("play/",views.playPage,name="play"), path("secreturl/",views.testPage,name="test"), ] And this is my other urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("pw.urls")), ] test.html is just a plain html file I have tried following tutorials online and seen other StackOverflow questions, but I did not come across an answer that I need. -
Using a single helper function as SerializerMethodField in multiple Serializers
I have a helper function that gives me the name of the vendor def get_vendor_name(self, obj): return ( obj.affiliate_organisation.current_vendor_version.name if obj.affiliate_organisation and obj.affiliate_organisation.current_vendor_version else None ) The function will be used by multiple serializers as SerializerMethodField. Is there a better way to define the function once instead of copy pasting it in every serializer separately and resuing the same code block. -
Return a GeoJSON object from python to Mapbox GL JS within the Django framework
I have some python code with manipulates and analyzes geospatial data, with the result/output being a GeoJSON file (or Geodataframe actually). I would like to pass this object back to a web page, to be plotted (as a choropleth map) on a Mapbox GL JS map. I'm having a lot of trouble getting the geoJSON back into the javascript environment to accomplish this. Any advice on the best way to do this? I have tried a number of options including converting to JSON, serializing, but nothing seems to work. If anyone knows how, please elaborate. If there is any additional information around what to include in the different files (the python function doing the analysis and generating the geodataframe, the views.py file returning the info, and the javascript code to convert it into a usable object within the javascript environment), that would be greatly appreciated. -
OSError:[Errno 38] Function cannot be implemented
Somebody please. I was working with ImageField and FileField some days ago and each time I go to the admin site to create and update an object an "OSError[Errno 38] Function not implemented" is always raised up. I tried setting null for the image field, and yes, the obeject is saved each time I save it or edit it without any the image, but when I uploaded an image, it will pop up the error. I tried creating a new project but still the same thing. I also tried saving it manually by using the Field File save method on field, but each time I tried to runserver, the same error poped up. I follow a lot of videos on YouTube and what they all did are the same, creating an image or filefield, setting up a MEDIA_URL,MEDIA_ROOT, and adding the path to the base url.py of their project, and once they did that, they were all able to save any object and photos. But It kept bringing that error for me, I don't know if it is my phone related. Please help me sir/ma. I've been on it for a long while now and I know quiet well that … -
Where to find information of Django internals and design
where can I find information of Django internals more updated that https://www.youtube.com/watch?v=tkwZ1jG3XgA ? It is a very good tutorial, but it is almost 20 years old. In RoR there is a lot of documentation, even books on how to make a toy RoR, but in Django, I cannot find anything except the old video I mentioned and this very short presentation: https://www.youtube.com/watch?v=7Famf5Sc_jg&ab_channel=EuroPythonConference Thanks in advance -
How to store unknow number of entries in django sqlite module
I have the following form which the user select a product and quantity. Product_name Quantity product1 3 product2 2 + Add Product And a button to add a extra field in the table, the button can be used any number of times to add extra products. How can i store the users orders in the database? Result: a database with fields of users orders. -
How to count the number of objects depending on the status?
I have the code which counts the number of elements of each type. Views.py from django.db.models import Count class HomeView(ListView): model = TypeCartridge template_name = 'home.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) type_counts = TypeCartridge.objects.values('type').annotate(total=Count('type')) context['type_counts'] = type_counts return context home.html: <div> {% for cartridge in object_list %} <div> <p>Number {{ cartridge.num}}: {{ cartridge.type }}, status {{ cartridge.status }}</p> </div> {% endfor %} <h2>Type Counts</h2> <ul> {% for type_count in type_counts %} <li>{{ type_count.type }} - {{ type_count.total }}</li> {% endfor %} </ul> </div> For example, I have a table: num type Status 0000001 Samsung Installed 0000002 Samsung NotInstalled 0000003 Xerox Installed 0000004 Brother NotInstalled 0000005 Brother NotInstalled 0000006 Brother NotInstalled 0000007 HP Installed 0000008 HP Installed And the result of my code is the following: Samsung - 2 Xerox - 1 Brother - 3 HP - 2 But I would like the code to count only elements with status "Installed". The result should be : Samsung - 1 Xerox - 1 HP - 2 How to improve the code? -
how to convert DateField field while returning a filtered result in DJANGO
I have the following table in django: models.py class Activity(models.Model) name = models.CharField(max_length=50) date_created = models.DateField() here is the way i create an instance of that table from datetime import date Activity.objects.create(name="Foo", date_created=str(date.today())) I know that auto_now_add=True can be used to store the date but at the moment it's out of the question and I need to find a solution exactly like the models is above. Is there a way to format the date_created field while querying all instances of the table Activity using .values() below in the views.py views.py activity = Activity.objects.filter(name="soccer").values() I am currently getting the following error: TypeError: Object of type date is not JSON serializable activity = Activity.objects.filter(name="soccer").values() -
Issue with complex lookup in Django
Below are my Django models. I'd like to write signal that will do the following: User updates project that contains let's say 3 Spider objects. Each Spider object contains config_file so signal should get list of all Spider objects and update group from all config files from the list. In the end when the user updates group name in Project all config_files should change group name as well. class Project(models.Model): name = models.CharField(max_length=200, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') is_shared = models.BooleanField(default=False) group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True, default=1) class Spider(models.Model): name = models.CharField(max_length=200, default="", unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') project = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, related_name='project_spider') config_file = models.ForeignKey(BaseFileModel, on_delete=models.SET_NULL, null=True, default='') class BaseFileModel(models.Model): file = models.FileField(upload_to=custom_upload_files, null=True, default='') group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True, default=1) version = models.IntegerField(default=1) I tried to write pre_save signal but it doesn't work as expected because file field in BaseFileModel is null after spider.config_file.save() and not all config files have group updated. The problem I have is that there is no direct connection between BaseFileModel and Project and I am not sure how to write lookup/query to update all config files after updating project group. @receiver(pre_save, sender=Project) def update_spiders_group(sender, instance, … -
how do i prepopulate a dynamic html template for updating a instance
I'm trying to prepopulate the text fields in a form template with an existing instance, I can select the instance and can even user {{instance}} to see the variables but unfortunately can't figure out how to fill in the fields with the instance vars. If i do instance.cpacity for example it will display the correct value but in every field, and as this must be dynamic i need to make it so that each field has its own text box and is prepopulated, ive managed to do this with it being dynamic for "create "but i am struggling with this Sorry for the spelling punctuation and grammar, I am dyslexic Template.html as you can see the {{instance}} in the middle is where my input would be views.py my example input in views.py again i tried using the instance in the context but i dont know what html functions can help me get the neccesary variables in the loop! -
Custom header "X-API-Version" throws CORS error Django REST framework
I tried to add a custom header called "X-API-Version" to check if the front-end is up to date, but despite following the documentation instructions I got a CORS error. Access to XMLHttpRequest at 'http://192.168.5.39:8001/api/host/login/' from origin 'http://localhost:9000' has been blocked by CORS policy: Request header field x-api-version is not allowed by Access-Control-Allow-Headers in preflight response. I already installed the django-cors-headers package, added it to INSTALLED_APPS, added 'corsheaders.middleware.CorsMiddleware' and 'django.middleware.common.CommonMiddleware' in MIDDLEWARE and I also added x-api-version to CORS_ALLOW_HEADERS and CORS_ORIGIN_ALLOW_ALL = True but the error still persists. What could I do to prevent this error from happening? Is there another way to add a custom header? Thanks for helping Here is the settings file: from corsheaders.defaults import default_headers from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. import django.core.mail.backends.smtp BASE_DIR = Path(_file_).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG', False) EMAIL_BACKEND = django.core.mail.backends.smtp.EmailBackend SERVER_EMAIL = EMAIL_HOST_USER # VARIAVEIS DE AMBIENTE API VIASAT IXC_TOKEN = os.environ.get( 'TOKEN', '*' ) IXC_API = … -
rest_framework and Django urlpatterns for api_root raising 500 Internal Server Error
Using rest_framework with Django to create the REST API for my application. But when I load the webpage (GET /api/v1/) on my browser I get a 500 Internal Server Error with the following output: AssertionError at /api/v1/ Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method. Request Method: GET Request URL: http://localhost:8000/api/v1/ Django Version: 4.1.7 Exception Type: AssertionError Exception Value: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method. Exception Location: D:\projects\warehauser\env\lib\site-packages\rest_framework\permissions.py, line 208, in _queryset Raised during: main.views.api_root Python Executable: D:\projects\warehauser\env\Scripts\python.exe Python Version: 3.10.6 Python Path: ['D:\\projects\\warehauser\\warehauser', 'C:\\Users\\omega\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\omega\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\omega\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\omega\\AppData\\Local\\Programs\\Python\\Python310', 'D:\\projects\\warehauser\\env', 'D:\\projects\\warehauser\\env\\lib\\site-packages'] Server time: Fri, 24 Mar 2023 23:42:41 +1100 Here is my urls.py # urls.py from django.urls import path, include from . import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('', views.home, name='home',), path('api/v1/', views.api_root), path('api/v1/products/', views.ProductList.as_view(), name = 'product-list'), path('api/v1/products/<int:pk>/', views.ProductDetail.as_view(), name = 'product-detail'), path('api/v1/orders/', views.OrderList.as_view(), name = 'order-list'), path('api/v1/orders/<int:pk>/', views.OrderDetail.as_view(), name = 'order-detail'), path('api/v1/users/', views.UserList.as_view(), name = 'user-list'), path('api/v1/users/<int:pk>/', views.UserDetail.as_view(), name = 'user-detail'), ] urlpatterns = format_suffix_patterns(urlpatterns) Here is my views.py # views.py from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from django.contrib.auth.decorators import login_required from django.http … -
Django Python: How to make the 'feed.html' Paginator an Infinite Scroll?
I'am working on a Social Media Website, I use Django, Python. I would like to make an Infinit Scroll Paginator to have a User-Friendly Surf experience. For now it shows a Select Bar at the end, f.e. 1, 2, 3, Last. How to make an Infinit Scroll Paginator where it laods when you scroll to the end? feed.html {% if posts.has_other_pages %} {% if posts.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{posts.previous_page_number}}">Previous</a> {% endif %} {% for num in posts.paginator.page_range %} {% if posts.number == num %} <a class="btn btn-info mb-4" href="?page={{num}}">{{num}}</a> {% elif num > posts.number|add:'-3' and num < posts.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{num}}">{{num}}</a> {% endif %} {% endfor %} {% if posts.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{posts.next_page_number}}">Load more Shots</a> <a class="btn btn-outline-info mb-4" href="?page={{posts.paginator.num_pages}}">Last</a> {% endif %} {% endif %} views.py @login_required def posts_of_following_profiles(request): profile = Profile.objects.get(user = request.user) users = [user for user in profile.following.all()] posts = [] qs = None for u in users: p = Profile.objects.get(user=u) p_posts = p.user.post_set.all() posts.append(p_posts) my_posts = profile.profile_posts() posts.append(my_posts) if len(posts)>0: qs = sorted(chain(*posts), reverse=True, key=lambda obj:obj.date_posted) paginator = Paginator(qs, 6) page = request.GET.get('page') try: posts_list = paginator.page(page) except PageNotAnInteger: posts_list = paginator.page(1) … -
I can't run my code, it has an unreachable error
I'm writing a page to introduce myself but I have some errors and don't know how to fix it when runserver it can't query the data. My code can still runserver but after opening the web, I get an error like this Exception Value: Cannot choose from an empty sequence Here is my code thanks. models.py from django.db import models class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() job_title = models.CharField(max_length=100) summary = models.TextField() education = models.TextField() work_experience = models.TextField() skills = models.TextField() profile_picture = models.ImageField(upload_to='images') def __str__(self): return self.name class Education(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) school = models.CharField(max_length=200) degree = models.CharField(max_length=200) major = models.CharField(max_length=200) start_year = models.PositiveIntegerField() end_year = models.PositiveIntegerField() specialization = models.CharField(max_length=200, blank=True) specialization_url = models.URLField(blank=True) certificate = models.CharField(max_length=200, blank=True) certificate_url = models.URLField(blank=True) image = models.ImageField(upload_to='images/', blank=True) def __str__(self): return f"{self.degree} in {self.major} from {self.school}" views.py from django.shortcuts import render from .models import Person import random def self_introduction(request): people = Person.objects.all() person = random.choice(people) context = {'person': person} return render(request, 'self_introduction.html', context)