Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO REST FRAMEWORK perform_create dont work
The code in the perform_create function isn't working. It says that POST method is done, but nothing saves. Maybe create or validate functions in serializer confronts with it? class SaveStats(CreateAPIView): queryset = Stats.objects.all() serializer_class = StatisticsSerializer def perform_create(self, serializer): print("checking") serializer.save() def post(self, request, *args, **kwargs): if (int(request.POST['views']) < 1) or (int(request.POST['clicks']) < 0) or (int(request.POST['cost']) < 0): return JsonResponse({"wrong input": "try again"}, status=status.HTTP_400_BAD_REQUEST) return JsonResponse({"status": "Stats saved"}, status=status.HTTP_200_OK) class StatisticsSerializer(serializers.Serializer): date = serializers.DateField() views = serializers.IntegerField() clicks = serializers.IntegerField() cost = serializers.IntegerField() def create(self, validated_data): return Stats(**validated_data) def update(self, instance, validated_data): instance.date = validated_data.get('date', instance.date) instance.views = validated_data.get('views', instance.views) instance.clicks = validated_data.get('clicks', instance.clicks) instance.cost = validated_data.get('cost', instance.cost) return instance def validate(self, attrs): if (attrs['views'] < 1) or (attrs['clicks'] < 1) or (attrs['cost'] < 1): raise serializers.ValidationError({"wrong input": "try again"}) print(attrs['views']) return attrs -
Date math with Django SQL Explorer
I have implemented Django SQL Explorer on a project and am attempting to build a query that will pull entries between today's date and 12 months prior to today's date, but I'm having a difficult time figuring out how SQL Explorer does date math. So far, about the only thing I've been able to discover is that SQL Explorer uses current_date for today's date. So: SELECT current_date; returns: 2021-10-02 I've tried using the MySQL implementation (since that's the database my project is using): SELECT current_date - INTERVAL 12 MONTH; returns: near "12": syntax error About the closest I've been able to come is some very simple math that just work on the year and strips all the rest of the date information away: SELECT current_date - 1; returns: 2020 Can anyone please help me figure out how to return the date 12 months prior to today's date in Django SQL Explorer? SELECT current_date SELECT current_date - [12 MONTH]; should return: 2021-10-02 2020-10-02 Thanks in advance! -
Why I am getting Django page not found error?
I am not understanding why I am getting this Page not found (404) Raised by:django.views.static.serve here is my code: app views.py: class SESmail(TemplateView): template_name = 'mail/account_confirmation.html' app urls.py urlpatterns = [ path('confirmmail/',SESmail.as_view(), name='confirmmail'), ] root urls.py urlpatterns = [ path('admin/', admin.site.urls), #my others url.... path('', include('sesmail.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py: INSTALLED_APPS = [ .... 'sesmail', ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) I am not understanding why I am getting this error? I added app name in my settings.py and also added url configuration properly in app urls.py and root urls.py. Where I am doing wrong? -
How to get data from views.py
There is one table called Option, and in order to save the value of Option 1, Option 2, views designated Option 2 and saved it to the table. What should I do to retrieve this saved data? There is one table called option, and it is difficult to recall because option 2 is not a table name. How can I solve this problem? views.py if request.method == "POST": form = OptionForm(request.POST) if form.is_valid(): option2 = Option() option2.name = form.cleaned_data['second_option'] option2.product_code = product option2.save() I wrote it in this way and received it from the view. {% for option in option_object %} {% if option.option_code.option_code == value.option_code %} {% if option.product_code == product %} <select type="text" class="form-control" id="optionSelect"> <option value="none">옵션을 선택하세요.</option> <optgroup label="{{option.name}}"> {% endif %} Here, I want to receive the value of option 2 stored in the option table. -
Django raiting for shop-item
I have a model in which I have a field rait = models.PositiveIntegerField (default = 0). Maximum 5 stars. For example, I now have a product that has 4 ratings, ie 4 gold stars 1 white. This should be done in the template django. How to do it? -
Unexpected keyword argument
Here is my model Model from Account.models import User from django.db import models class Seller(models.Model): seller = models.OneToOneField(User, on_delete = models.CASCADE) email = models.EmailField(max_length = 90, unique = True) country = models.CharField(max_length = 60) phone = models.CharField(max_length= 20, unique = True, blank = True, null = True) address = models.TextField() zipcode = models.CharField(max_length = 10) form from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from .models import Seller from Account.models import User class SellerCreationForm(UserCreationForm): name = forms.CharField(required = True) email = forms.EmailField(required = True) phone = forms.CharField(required = False) country = forms.CharField(required = True) address = forms.CharField(required = True) zipcode = forms.CharField(required = True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_seller = True user.name = self.cleaned_data.get('name') user.save() seller = Seller.objects.create(user=user) seller.email = self.cleaned_data.get('email') seller.phone = self.cleaned_data.get('phone') seller.country = self.cleaned_data.get('country') seller.address = self.cleaned_data.get('address') seller.zipcode = self.cleaned_data.get('zipcode') seller.save() return user views from django.shortcuts import render, redirect from django.views.generic import CreateView from .forms import SellerCreationForm from django.contrib.auth.forms import AuthenticationForm from Account.models import User class RegisterSeller(CreateView): model = User form_class = SellerCreationForm template_name = 'registration/registerseller.html' def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/') I tried to create a project with multiple users types … -
Is ther any way to split the uploaded file name extension and display it in diffrent html element?
I uploaded files from the index.html page and extensions are .jpg, .pdf, Docx, and mp4 into my project and able to display only jpg files and used scr for that and I need to use if else condition according to extension and display in HTML elements. so that I need to split the file name and get that extension and accordingly used if-else condition. I am not able to split files for the index.html page using split(). please help and all code included below index.html {% for i in phone %} <!-- <img src="{{i.document.url}}" alt="Girl in a jacket" width="200" height="200; display: flex;"> --> <h1>{{i.document.url}}</h1> <h2>{{i.document.path}}</h2> {% endfor %} views.py def Home(request): if request.method == 'POST': if len(request.FILES) == 0: return redirect("/drive") else: photo = request.FILES['doc'] Upload.objects.create(document = photo) return redirect("/drive") if request.method == "GET": photo = Upload.objects.all() context = { 'phone': photo } return render(request, 'Home.drive.html', context) modles.py from django.db import models # Create your models here. class Upload(models.Model): document = models.FileField(upload_to='documents') Note: Waiting for positive response and please i am beginner so that i need full code instead of hint. -
redirect to created object after form submission
Goal: To redirect to the 'build log' after the form is submitted view: @login_required def buildLogCreate(request, pk): post = Post.objects.get(pk=pk) if request.user.id != post.author_id: raise PermissionDenied() currentUser = request.user form = BuildLogForm() if request.method == 'POST': form = BuildLogForm(request.POST, request.FILES) if form.is_valid(): formID = form.save(commit=False) formID.author = request.user formID.post_id = pk formID.save() return redirect('build-log-view', formID.pk) context = { 'form':form, } return render(request, 'blog/buildlog_form.html', context) The url structure setup is post->buildlog(subpost) ie: /post/118/build-log/69/ The form gets successfully submitted but I get the error NoReverseMatch at /post/118/build-log-form/ Reverse for 'build-log-view' with arguments '(69,)' What confuses me is the url is still on the post form and not build log view but the argument 69 is the correct build log id so it should be working. url to be redirected to path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), -
Best Practice to run Django/Vue application on Production
I have a Django/Vue app and when I am developing, I run two different servers, one for Django on port 8082 and one for Vue with yarn serve on port 8080. I want to deploy this application to AWS. I created dist files with npm run build and I configured Django to access templates in this dist directory and in my views.py I routed to this static html files generated by build process. Is it a good practice to run Django/Vue apps on production or should I be running two different servers for production as well? -
How to change user based on their personal value using python
I have a table in my models named as Referralcode ReferralActiveUser class ReferralActiveUser(models.Model): user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) user_active = models.BooleanField(default=False) referral = models.ForeignKey( User, related_name='comp_active_user', on_delete=models.SET_NULL, null=True, blank=True) I want to loop over this table and change the status of user based on their pv(personal value) but I'am confused or I don't know how to do this. What I want is assume this is a users in my table [ { "id": 1, "user": 2, "user_active": "0", "referral_by": 1 }, { "id": 2, "user": 3, "user_active": "0", "referral_by": 2 }, { "id": 3, "user": 4, "user_active": "0", "referral_by": 2 }, { "id": 4, "user": 5, "user_active": "0", "referral_by": 2 } ] here "user":1 is first user who started this program and all other users are child of "user":1 it's like tree structure and I want to loop over user and check each user pv and change it's status like this referral_users = ReferralActiveUser.objects.all() min_value=20 for user in referral_users: if user.pv >= min_value: user.status = True user.save() else: # Find users referred by this user inactive_users = referral_users.filter(referral_by=user.user) for j in inactive_users: j.referral_by = # want to add parent of this user j.save() user.status = False user.save() INFO … -
Change chunk_vendors/app js file import urls in public index.html in a Django/Vue application
I want to serve my chunk vendors or app js files under static/js/chunk_vendors.js rather than /js/chunk_vendors.js because I want to point to the dist directory generated for production build by npm run build and my static url in Django is /static so every static file should be access via a url starting with /static. But npm run build generates an html file with chunk_vendors.js url /js/chunk_vendors.js. How can I tell Vue Cli to generate html files with /static prefix? -
m2m_change signal not work form admin site but work from shell
I have a model class Category(models.Model): name = models.CharField(unique=True, max_length=45, blank=False, null=False) perants= models.ManyToManyField('self',through="CategoryParent",symmetrical=False,blank=True) and the CatigoryPerants is : class CategoryParent(models.Model): chiled_filed=models.ForeignKey("Catigory", on_delete=models.CASCADE,related_name="parent_of_category",blank=False) parent_filed=models.ForeignKey("Catigory", on_delete=models.CASCADE,blank=False) and I try to run a signal in signal.py: @receiver(m2m_changed, sender=Catigory.perants.through ) def CatigoryParentSignals(sender, instance, action, pk_set, **kwargs): print("Some text or throw Validation Expiation or doin any thing") The problem is when I add new parent to the Category from Shell with .parents.set([parents]) or.parants.add(parent) its work but when add any parent from admin site this signal isn't work -
Django REST Frameworking: modify PrimaryKeyRelatedField queryset for GET requests
Is it possible to give PrimaryKeyRelatedField a get_queryset function that is called when doing a GET request? Currently it's only getting called when I'm doing a POST or PUT request, but I want to be able to limit which relations get shown in a GET request, or as the result of a PUT or POST request. The use case is that I have a model with a many to many relationship, some of which the user has access to, and some not. So I want to only include the ones the user has access to in the result. Specifically, take this example: class Quest(models.Model): name = models.CharField(max_length=255) is_completed = models.BooleanField(default=False) characters = models.ManyToManyField(Character, blank=True) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) class Character(models.Model): name = models.CharField(max_length=255) is_hidden = models.BooleanField(default=False) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) So a quest has an array of characters, some of which can be marked as hidden. My serializer looks like this: class QuestSerializer(DmNotesModelSerializer): characters = CharacterPrimaryKeyRelatedField(many=True) class Meta: model = Quest fields = "__all__" class CharacterPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): return Character.objects.filter(campaign_id=self.context.get("view").kwargs.get("campaign_id")) This makes the characters array writable, AND I am limiting the characters you can add to ones that belong to the same campaign as the quest itself. This … -
Using the Django Admin Template
I'm trying to use the Django admin templates to login in some users in my website. The point is: I wouldn't like to create my own templates (.html) so I'm trying to find out a way to make it simple! Here is my admin.py inside auditoria.app from auditoria_app.urls import app_name class AuditoriaAdminArea(admin.AdminSite): site_header = 'Área Restrita' site_url = app_name auditoria_site = AuditoriaAdminArea(name='AuditoriaAdmin') My urls.py inside auditoria_app from . import views app_name = 'auditoria_app' urlpatterns = [ # Home Page path('', views.index, name='index'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My urls.py from auditoria_app.admin import auditoria_site urlpatterns = [ path('admin/', admin.site.urls), ##path('', include('auditoria_app.urls')), ## this is the correct urls after logged in path('', auditoria_site.urls), ] After the login is completed, Django is redirecting the user to the Admin Panel. How can I redirect them to my home page instead? Cheers! -
accessing self.request.user.profile in django generic views
I'm working on an API in Django rest framework and I am using generics.RetrieveUpdateAPIView here is my class: class updateProfile(generics.RetrieveUpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer and here is my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) short_intro = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_image = models.ImageField( null=True, blank=True, upload_to="profiles/", default="profiles/user-default.png", ) social_github = models.URLField( max_length=200, blank=True, null=True, validators=[validate_url_github] ) social_twitter = models.URLField( max_length=200, blank=True, null=True, validators=[validate_url_twitter] ) social_linkedin = models.URLField( max_length=200, blank=True, null=True, validators=[validate_url_linkedin] ) social_youtube = models.URLField( max_length=200, blank=True, null=True, validators=[validate_url_yt] ) social_website = models.URLField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False ) I want to access the request.user.profile I have tried the view as : class updateProfile(generics.RetrieveUpdateAPIView): queryset = request.user.proifle //and also self.request.user.proile serializer_class = ProfileSerializer how can I access the profile of the user in this class-based view -
Not getting all field in Django form to enter the details
I wanted to use my both models farmer(Foreign key for tractor) and tractor in a single form but i am not getting the fields of tractor in web page to enter its value i am only getting fields of farmer. my models.py class Farmer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone =models.CharField(max_length=10) address = models.TextField(max_length=200) email_address = models.EmailField() def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.full_name() class Post(models.Model): tractor_price = models.IntegerField(max_length=150) implimentaion = models.CharField(max_length=50) purchase_date = models.DateField(auto_now=False) slug = models.SlugField(unique=True, db_index=True, null=True,blank=True) tractor_company = models.CharField(max_length=50) tractor_model = models.CharField(max_length=50) description = models.TextField(validators=[MinLengthValidator(10)]) date = models.DateField(auto_now_add =True) farmer = models.ForeignKey( Farmer, on_delete=models.SET_NULL, null=True, related_name="posts") my view.py Only add_post function def add_post(request): if(request.method == "POST"): farmer_form = FarmerForm(request.POST) post_form = Post(request.POST) if(farmer_form.is_valid() and post_form.is_valid()): farmer = farmer_form.save() post = post_form.save(False) post.farmer = farmer post.save() return redirect(reverse("tractor.views.posts")) else: farmer_form = FarmerForm(request.POST) post_form = Post(request.POST) args = {} args.update(csrf(request)) args["farmer_form"] = farmer_form args["tractor_form"] =post_form return render(request,"tractor/form.html",args) forms.html <div class="form-group"> <form method="POST" style="margin-left: 40px; margin-right: 100px" enctype="multipart/form-data" action="{% url 'tractor:add_post' %}" > {% csrf_token %} {{post_form}} {{farmer_form}} <input type="submit" class="btn btn-dark" value="Submit" /> </form> </div> forms.py class PostForm(ModelForm): class Meta: model = Post fields = ("tractor_price","implimentaion","purchase_date","tractor_company","tractor_model","description") class FarmerForm(ModelForm): class Meta: model = Farmer fields = … -
is the any other way to upload image from frontend using upload section ? getting not displayed and upload from index.html page
I have tried to upload the image from the index.html page and also created; modles.py, views.py, urls.py and soon but I have upload and it is successfully uploaded in the mentioned directory in models.py but failed to view that image in front showing cut pic image views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Upload # Create your views here. # Imaginary function to handle an uploaded file def Home(request): if request.method == 'POST': photo = request.POST['doc'] Upload.objects.create(document = photo) context ={ } if request.method == "GET": photo = Upload.objects.all() context = { 'phone': photo } return render(request, 'Home.drive.html', context) models.py from django.db import models # Create your models here. class Upload(models.Model): document = models.ImageField(upload_to='documents') index.html {% load static %} <!DOCTYPE html> {% block content %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>PB-2021</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/index.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-5.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/> </head> <body> <nav style="font-size: 1em; list-style-type: none; display: block; margin: 0; padding: 0; overflow: hidden; position: sticky; top: 0; z-index: 1;"> <input type="checkbox" id="check"> <label for="check" class="checkbtn"> <i class="fas fa-bars"></i> </label> <label class="logo">AMRIT SHAHI</label> <ul> <li><a class="active" href="{% url 'PBAPP:home' %}">Home</a></li> <li><a href="#">About</a></li> <li><a … -
Django logout is not logging out user
I have done a lot of searching and all I can really find are variants of the following: from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page. Here is the code from my view: from django.contrib.auth import logout def leave(request): logout(request) return redirect("index") However, it neither logs the user out nor goes to the index page. I also have: path('accounts/', include('django.contrib.auth.urls')), in my urls page. I tried prefixing my urls with "accounts/" but that just resulted in errors. -
I'm using python apscheduler in django to remind users of created notices. I'm stuck at trying to make the date that they want to be reminded dynamic
My task is to create reminders for notices. If I hardcode, I get the reminder on the cli from the API but I want to make it dynamic so users can pick the date or time they want to be reminded of their notice. Please help! This is the updater.py file from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler from .jobs import notice_reminder def notice_me(): notice_remind = notice_reminder.newly_created_notice_reminder if notice_remind: print(notice_remind) else: print("No recent notice reminders!") """ The dummy data """ dynamic_data = [ { "title": "Notice Reminder", "schedule_time": "00:50:00", "schedule_date": "10-2-2021" } ] print(dynamic_data[0].get("schedule_date")) # Get Date and Time Dynamically dynamic_data = notice_reminder.newly_created_notice_reminder if any(notice_reminder.newly_created_notice_reminder) else "dynamic_data" dynamic_date_time = f"{dynamic_data[0].get('schedule_date')} {dynamic_data[0].get('schedule_time')}" print(f"Date Time: {dynamic_date_time}") dynamic_date = datetime.strptime(dynamic_date_time, '%m-%d-%Y %H:%M:%S') print(f"Dynamic Date Time: {dynamic_date}") def start(): scheduler = BackgroundScheduler() scheduler.add_job( notice_me, "date", run_date = f"{dynamic_date}" ) scheduler.start() This is my serializer file for the view notices option from rest_framework import serializers from django.utils import timezone from datetime import date # Time Zone time = timezone.now() # Get Current Time current_time = f"{time.hour + 1}:{time.minute}:{time.second}" # Get Current Date current_date = f"{time.month}-{time.day}-{time.year}" class NoticeReminderSerializer(serializers.Serializer): title = serializers.CharField(max_length=255) time_created = serializers.TimeField(default=current_date) date_created = serializers.DateField(default=current_time) schedule_time = serializers.TimeField() schedule_date = serializers.DateField() This is … -
Django with Javascript es6 resource not working
enter image description here Hi,I recently developed a 3D model project based on THREEJS,using es6 gramar. It's works fine with tomcat,and nodejs http-server but it can't work on python backend ,Django Framework. Give me this error above. There's no CORS problem since the static resource runs on server -
Decision in Back-end [closed]
I have an important question. How can I understand when using Go, Django, PHP, Java, or another language for Back-end. I am really confused. Please explain to me the parameters which are important for the decision. -
Django aggregate sum throwing `int() argument must be a string, a bytes-like object or a number, not 'dict'`
I am trying to create a serializer to aggregate some data regarding a users inventory, however it is throwing the following error: Exception Value: int() argument must be a string, a bytes-like object or a number, not 'dict' I am not sure what time missing here. I am trying to sum the fields of standard and foil for a given user. Model.py class inventory_tokens(models.Model): ... standard = models.IntegerField(default=0) foil = models.IntegerField(default=0) serializers.py class InventorySerializers(serializers.Serializer): total_Cards_Unique = serializers.IntegerField() total_Cards = serializers.IntegerField() total_Standard = serializers.IntegerField() total_Foil = serializers.IntegerField() views.py # Inventory Data class InventoryData(views.APIView): def get(self, request): user_id = self.request.user data = [{ "total_Cards_Unique": inventory_cards.objects.filter(user_id=user_id).count(), "total_Cards": 0, "total_Standard": inventory_cards.objects.filter(user_id=user_id).aggregate(Sum('standard')), 'total_Foil': inventory_cards.objects.filter(user_id=user_id).aggregate(Sum('foil')), }] results = InventorySerializers(data, many=True).data return Response(results) full traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/account/inventory/inventory-data/ Django Version: 3.2.7 Python Version: 3.7.9 Installed Applications: ['base.apps.BaseConfig', 'account.apps.AccountConfig', 'administration.apps.AdministrationConfig', 'magic.apps.MagicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'psycopg2', 'background_task', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "W:\My Drive\Projects\Card Companion\card_companion\card_companion_venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "W:\My Drive\Projects\Card Companion\card_companion\card_companion_venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "W:\My Drive\Projects\Card Companion\card_companion\card_companion_venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "W:\My Drive\Projects\Card Companion\card_companion\card_companion_venv\lib\site-packages\django\views\generic\base.py", line … -
Django axes limit a custom model
I use SMS verification service in my project and I would like to prevent any abuse to this. I already implemented Axes to track and limit login attempts. How if I want to track/limit attempts to this service as well? Thanks! -
How to make pagination when send POST Form to Django View
I'd like to use paginations in django when send post method to my view: It returns the values properly when click in submit, but when I click in "next page" it returns empty table. html: <form action="{% url 'maintenance_issue_search' %}" method="POST" enctype="multipart/form-data" id="form" name="form"> {% csrf_token %} <div style="text-align:left;" class="form-row"> <div class="form-group mr-2"> <label for="date">Date Start</label> <input class="form-control" id="date" name="date" placeholder="YYYY-MM-DD" value="{{ start_date }}" type="date" required> </div> <div class="form-group mr-2"> <label for="date1">Date End</label> <input class="form-control" id="date1" name="date1" placeholder="YYYY-MM-DD" value="{{ end_date }}" type="date" required> </div> <div style="text-align:left;" class="form-group"> <label for="select_status">Status</label> <select name="select_status" id="select_status" style="float:left;" class="form-control" multiple> <option value="Pending" selected>Pending</option> <option value="On Going">On Going</option> <option value="Consent OK">Consent Ok</option> <option value="Approve OK">Approve Ok</option> <option value="Completed">Completed</option> <option value="Not Approved">Not Approved</option> </select> </div> <section class="buttons"> <div style="text-align:center;float:left" class="form-group"> <div class="form-group col-md-6"> <button type="submit" class="btn btn-info">Search </button> </div> </div> </section> </div> </form> <!--Pagination--> {% if issue_list.has_other_pages %} <ul class="table-pagination"> {% if issue_list.has_previous %} <li><a href="?page=1">First</a></li> <li><a href="?page={{ issue_list.previous_page_number }}">Previous</a></li> {% endif %} <span class="current"> Page {{ issue_list.number }} of {{ issue_list.paginator.num_pages }} </span> {% if issue_list.has_next %} <li><a href="?page={{ issue_list.next_page_number }}">Next></a></li> <li><a href="?page={{ issue_list.paginator.num_pages }}">Last></a></li> {% endif %} </ul> {% endif %} Views: def maintenance_issue_search(request): start_date = request.POST.get('date') end_date = request.POST.get('date1') status = request.POST.getlist('select_status') all_issue_list = … -
i need to show some data in table but those data's are not in a same table ,how to show that data in one table in django
Views.py def meterstatistics(request): varr = Meters_table.objects.all() vark = Meter_Data_table.objects.all() Lastkwh = Meter_Data_table.objects.last() Lasttime = Meter_Data_table.objects.last() d = { 'Lastkwh': Lastkwh, 'Lasttime': Lasttime, 'vark': vark, 'varr': varr } return render(request, 'meterstatistics.html', d) models.py class Meters_table(models.Model): Meter_id = models.AutoField(unique=True, editable=False, primary_key=True) Account_id = models.CharField(max_length=128) Location_id = models.CharField(max_length=150, help_text="(ID of the locations table)") RR_No = models.CharField(max_length=128) Meter_type = models.CharField(max_length=150, help_text="(Industry,Residential & Transformer)") Meter_make = models.CharField(max_length=150) Meter_model = models.CharField(max_length=150) Usage_type = models.CharField( max_length=150, help_text="(Industry,Residential & Transformer)") def __str__(self): return self.Usage_type class Meter_Data_table(models.Model): id = models.AutoField(unique=True, editable=False, primary_key=True) Meter_id = models.CharField(max_length=150) IMEI_Number = models.CharField(max_length=150) KWH = models.CharField(max_length=128) KVAH = models.CharField(max_length=150) PF = models.CharField(max_length=150) BMD = models.CharField(max_length=128) Meter_time_stamp = models.DateTimeField(max_length=150) Receive_time_stamp = models.DateTimeField(max_length=150) def __str__(self): return self.Meter_id HTML <table id="table"> <thead class="thead-light bg-primary"> <tr> <th scope="col">Meter_id</th> <th scope="col">DCU IMEI</th> <th scope="col">RR No</th> <th scope="col">Last KWH</th> <th scope="col">PF</th> <th scope="col">Last Meter Time Stamp</th> <th scope="col">Location</th> <th scope="col">Frequency</th> <th scope="col">Relay</th> <th scope="col">Action</th> </tr> </thead> <tbody> <tr> {% for i in vark %} <td>{{i.Meter_id}}</td> <td>{{i.IMEI_Number}}</td> <td>{{i.RR_No}}</td> <td>{{i.KWH }}</td> <td>{{i.PF}}</td> <td>{{i.Meter_time_stamp }}</td> <td></td> <td></td> <td><label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label></td> <td> <a href="{% url 'graph' %}"><i style="font-size: 30px;" class="fa fa-eye" aria-hidden="true"></i> </a> <a href="metertableedit/{{i.Meter_id}}"><i style="font-size: 30px;" class="fa fa-pencil-square-o" aria-hidden="true"></i></a> <!-- <a href="delmetertable/{{i.Meter_id}}"><i style="font-size: 30px;" class="fa fa-trash" aria-hidden="true"></i></a> --> …