Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Django projec via Git to Azure Web App failed (Linux)
I developed a simple Django app, it was pushed to git. When I deployed to Azure Web App, it failed with the following. I tried to research the zip issue. There aren't much information. Can someone help? I have put ALLOWED_HOSTS = ['*'] in setting.py. The app is running at localhost fine. I tried many deploy many times, and also retried by creating new web app. Still the same issue. My python is 3.8 Deployment Failed with Error: Error: Failed to deploy web package to App Service. Error: Request timeout: /api/zipdeploy?isAsync=true&deployer=GITHUB_ZIP_DEPLOY -
error with slug in django - template it show all posts data in each post
error with slug in django - template it show all posts data in each post when i create new post and write my data it's show all data from other posts why is that ? and how i can fix it ? also how i can add auto generation slug ? models.py : from django.urls import reverse from django.utils.text import slugify class Android(models.Model): title = models.CharField(max_length=50,default="",help_text="this is title for slug not post!") name = models.CharField(max_length=50,default="") app_contect = models.CharField(max_length=240,default="") app_image = models.ImageField(upload_to='images/',null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) post_tag = models.CharField(max_length=50,default="",choices = BLOG_SECTION_CHOICES) slug = models.SlugField(null=True,uniqe=True) # new def get_absolute_url(self): return reverse('android_posts', kwargs={'slug': self.slug}) # new def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class Meta: ordering = ('-post_date',) views.py : def android_posts(request,slug): android_posts = Android.objects.all() context = {'android_posts':android_posts} return render(request,'android/android_problems_fix.html', { 'android_posts': android_posts }) html page : {% for android in android_posts %} <h1 id="font_control_for_header_in_all_pages">{{android.name}}</h1> <hr> <p id="font_control_for_all_pages">{{android.app_contect}}</p> {% endfor %} -
Django, boardcast of HttpResponseRedirect
I create a web site on django and get errors. I have need broadcast response on view of method. Params may not exist. Help please. Code with views method where need get response: def blog_once(request, post_id): try: post = Blog.objects.get(id=post_id) except: raise Http404('Статья не найдена :(') comments = post.comment_set.order_by('-pub_date') count = post.comment_set.count() return render(request, 'blog/details.html', {'post': post, 'comments': comments, 'count': count, 'GOOGLE_RECAPTCHA_SITE_KEY': settings.GOOGLE_RECAPTCHA_SITE_KEY}) Code with HttpResponseRedirect: def leave_comment(request, post_id): try: post = Blog.objects.get(id=post_id) except: raise Http404('Статья не найдена :(') if request.POST['author'] != '' and request.POST['text'] != '': response = 'Ваш комментарий добавлен!' if request.FILES: post.comment_set.create(author=pymysql.escape_string(request.POST['author']), image=request.FILES['image'], text=pymysql.escape_string(request.POST['text'])) else: post.comment_set.create(author=pymysql.escape_string(request.POST['author']), text=pymysql.escape_string(request.POST['text'])) else: response = 'Вы не заполнили имя или текст сообщения!' return HttpResponseRedirect(reverse('blog_once', args=(post.id,))) -
ValueError: Field 'id' expected a number but got 'index.html'
I am trying to create a simple to-do list app using Django. But face this error will running the server ValueError: Field 'id' expected a number but got 'index.html'. models.py from django.db import models class List(models.Model): item = models.CharField(max_length=200) completed = models.BooleanField(default=False) def __str__(self): return self.item + '|' + str(self.completed) urls.py from . import views urlpatterns = [ path("index",views.index, name="home"), path("delete/<list_id>/", views.delete , name="delete"), ] views.py from django.http import HttpResponse from django.shortcuts import render, redirect from .models import List from .forms import ListForm from django.contrib import messages # Create your views here. def index(request): if request.method == 'POST': form = ListForm(request.POST or None) if form.is_valid(): form.save() all_items = List.objects.all messages.success(request,('Items has been Added to List !!')) return render(request,'home.html', {'all_items': all_items}) else: all_items = List.objects.all return render(request,'index.html',{'all_items': all_items}) def delete(request, list_id): item = List.objects.get(pk=list_id) item.delete() messages.success(request,('Item has been deleted')) return redirect('index') index.html {% extends 'home.html' %} {% block content %} {% if messages %} {% for message in messages %} <div class="alert alert-warning alert-dismissable" role="alert"> <button class="close" data-dismiss="alert"> <small><sup>x</sup></small> </button> {{ message }} </div> {% endfor %} {% endif %} {% if all_items %} <table class="table table-bordered"> {% for things in all_items %} <tr> <td>{{ things.item }}</td> <td><center>{{ things.completed }}</center></td> <td><center><a … -
Plotly slider missing when plotted on a webpage
I have plotted a choropleth map with a slider using Ploty. The slider and the choropleth both appears fine when I plot it on a Jupyter notebook or on Colab notebook but when I used the same plot to display on a webpage using Plotly Dash the slider disappears from the plot and only the choropleth map is shown. Below Code is when plotted on Jupyter Notebook data_slider = [] for month in world_df['Date'].unique(): df_month = world_df[world_df['Date'] == month] for col in df_month.columns: df_month[col] = df_month[col].astype(str) data_one_month = dict( type='choropleth', locations = df_month['Country'], z=df_month['Confirmed'].astype(float), locationmode='country names', colorscale = "purples", ) data_slider.append(data_one_month) steps = [] for i in range(1,int(len(data_slider))): step = dict(method='restyle', args=['visible', [False] * len(data_slider)], label='Day {}'.format(i) ) step['args'][1][i] = True steps.append(step) sliders = [dict(active=0, pad={"t": 1}, steps=steps)] layout = dict(geo=dict(scope='world', showcountries = True, projection={'type': 'equirectangular'}, ), sliders= sliders ) fig = dict(data=data_slider, layout=layout) iplot(fig, show_link = True) Plot output when plotted on Jupyter Below code is when plotted on a webpage using Plotly Dash data_slider = [] for month in world_df['Date'].unique(): df_month = world_df[world_df['Date'] == month] for col in df_month.columns: df_month[col] = df_month[col].astype(str) data_one_month = dict( type='choropleth', locations = df_month['Country'], z=df_month['Confirmed'].astype(float), locationmode='country names', colorscale = "purples", ) data_slider.append(data_one_month) steps … -
Django tabularinline from different app models
I am new with Django. My question is how to showing the data as Tabularinline in DetailView in django from two different apps, my issue is how to show the results in the HTML form, the results are shown in the django admin but i cant show them in the html code i wrote, here is the codes: 1st App: CustomeUser class CustomUser(AbstractUser): bio= models.CharField(max_length=300, null= True, blank=True) memberOf = models.ManyToManyField("Team", blank=True) class Team (models.Model): title = models.CharField(max_length=200) user= models.ManyToManyField(get_user_model()) date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated= models.DateTimeField(auto_now=True,blank=True, null=True ) def __str__(self): return self.title def get_absolute_url(self): # new return reverse('team_detail', args=[str(self.pk)]) second app Project class Client(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="client_team") title = models.CharField(max_length=150, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) def __str__(self): return self.title class Project (models.Model): team= models.ForeignKey(Team,on_delete=models.CASCADE ) client=models.ForeignKey(Client,on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150, null=False, blank=False) notes = models.TextField( null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated = models.DateTimeField(auto_now=True, blank=True, null=True) purchase_number= models.CharField(max_length=50, null=True, blank=True) PO_date = models.DateTimeField( blank=True, null=True) completion_date = models.DateTimeField( blank=True, null=True) i modified app1. admin.py to show the Tabularinline form. from projects.models import Project, Client class ProjectInline(admin.TabularInline): model = Project fields = ['title','client', 'purchase_number'] class TeamAdmin(admin.ModelAdmin): inlines = [ ProjectInline, … -
How to disable autoplay in iframe. Without using video tag
I need to be able to disable autoplay in an iframe because I want to be able to display the file. And the thing is I don't know what is the file type cause it will be a file the user selected. So like it can be a text file, image, or a video the best I would is the iframe cause I can put any file to be displayed. And that's the reason I don't want to use the video tag cause the file could even be an image or a text file. So I can be able to do that. If it means to be done by JS I wouldn't mind, but NOT JQUERY. And all these files are stored in a Django model so I get the file in a URL or link. So I hope someone could help -
How can I get a comment that corresponds to a post in django rest framework?
I'm going to make an api that only brings up comments from the post when I send a request to the router with comments attached to the pk value of the post. So urls as follows.After writing py and views.py, I sent the request and 404 error occurred. How can I get comments by composing an api? Here's the code I made. Thanks in advanced. urls.py urlpatterns = [ path('post', CreateReadPostView.as_view({'post': 'create', 'get': 'list'})), path('post/<int:pk>', UpdateDeletePostView.as_view({'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})), path('post/<int:post.pk>/comments', CreateReadCommentView.as_view({'post': 'create', 'get': 'list'})), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class CreateReadCommentView (ModelViewSet) : serializer_class = CommentSerializer permission_classes = [IsAuthenticated] queryset = Comment.objects.all() def perform_create (self, serializer) : serializer.save(author=self.request.user) -
how to get a specific object in detailview django
i've these class ModelA(models.Model): admin = models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank=True) name = models.CharField(max_length=30) class ModelB(models.Model): users = models.CharField(max_length=30) balance = models.DecimalField(max_digits=20,decimal_places=3) def __str__(self): return self.users between ModelA and ModelB there is no any relations my forms.py class ModelAForm(forms.ModelForm): name = forms.ModelChoiceField(queryset=ModelB.objects.all()) class Meta: model = ModelA fields = ['name'] class ModelBForm(forms.ModelForm): class Meta: model = ModelB fields = ['users'] and in my views.py in DetailView of ModelA i have to return balance field in the ModelB class ModelAView(DetailView): model = ModelA template_name = 'templates/tem.html' context_object_name = 'objs' queryset = ModelA.objects.all() def get_object(self): id = self.kwargs.get('pk') return get_object_or_404(ModelA,pk=id) # i need to get balance field in ModelB for the exact object , i tried this but doesn't work #def get_balance(self): #users = ModelB.objects.all().values_list('users',flat=True) #if ModelA.objects.filter(name__in=users): # name = ModelA.objects.filter(name__in=users) # balance = ModelB.objects.get(name=name).balance # return balance #else: # return False but the above solution dont work and raised this error int() argument must be a string, a bytes-like object or a number, not 'ModelA' i need to display balance field in the ModelA DetailView !? is it possible please note : i dont want to make any connection between ModelA and ModelB i appreciate your helps ... regards -
Using firebase to sign up and authenticate users for a React & Django Rest Framework app
I have a Django Rest Framework backend with a React client. I want to use Firebase authentication in the following way: Ability to register and authenticate users via Django Rest Framework. Email registration should be supported. (I'm mainly interested in using Firebase to avoid building custom logic for email verification, password resets, etc) Ability to Django Rest Framework -
AWS S3 bucket serves image locally but on production image is not loading
I am having a problem with AWS S3 bucket. I searched and couldn't find a solution, I have a Django project hosted on Heroku and serve static images using s3 bucket. Some days back I deleted my old IAM credentials created new now the images works locally but on production it doesn't serve this images. By checking on the image URL I noticed the app locally could access the IAM credentials from env variables but on production it is still using the old deleted credentials. Here are my AWS settings setting environmental variables for S3 AWS_ACCESS_KEY_ID = os.environ.get('MY_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('MY_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('MY_AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = 'us-east-2' AWS_DEFAULT_UCL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Thanks for your help in advance. -
pass two of pk into url
If the 'school year' value is changed, 404 does not appear. I want data to be displayed only when both 'school_year' and 'pk' have the right values in url. for example If you have data that (School_Year = 2020, pk = 33) when you enter url https://190.0.1/190/190/33 and https://190.0.1/190/whatthell/33 Both are the same results. However, I would like to display the result only when both values are correct. i really dont know if i explained correctly, thanks. view.py class StudentDetail(DetailView,FormView): model = Student template_name = 'student/member.html' context_object_name = 'student' form_class = AddConsultation def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['pk'] = Student.objects.filter(pk=self.kwargs.get('pk')) return context url.py path('student/<school_year>/<pk>/', views.StudentDetail.as_view(), name='student_detail'), html link <a href='{% url 'student_detail' student.school_year student.pk %}'> models.py class Student(models.Model): school_year = models.CharField( max_length=10, choices=SCHOOL_YEAR_CHOICES, default='2021N', verbose_name='school year' ) ... etc -
Having trouble in routing ( giving urls or path) in Django Rest Framework
This is my main project urls . Now I have an app which is routed by path('', include('mysite.urls')),. Now I have a folder named crmAPi for creating apis. This api folder is not an app though, just a folder. I route the urls by using path('api', include("mysite.crmapi.urls")),. urlpatterns = [ path('', include('mysite.urls')), path('admin/', admin.site.urls), path('api', include("mysite.crmapi.urls")), ] Now, this is my crmApi urls. The problem is I can access to first path, i can see airilnes list. No, matter what i do, i cannot acces flightdetails. What is the problem with the route?? help pleaseee?? even i create a different listview, again I cannot the route, only the arilines one, I can access. urlpatterns = [ path('', views.AirlinesListAPIView.as_view(), name='api'), path('api/flightdetails', views.FlightDetailsListAPIView.as_view(), name='flightdetails'), ] This is my view. class AirlinesListAPIView(ListAPIView): # permission_classes = [AllowAny] serializer_class = AirlinesListSerailizer queryset = Airlines.objects.all() permission_classes = (IsAdminUser,) class FlightDetailsListAPIView(ListAPIView): # permission_classes = [AllowAny] serializer_class = FlightDetailsListSerailizer queryset = FlightDetails.objects.all() permission_classes = (IsAdminUser,) -
django model not in urls.py
I am new to python and django and I want to know the best way to set things up. I have a model called OauthProviders which I set up to encrypt some fields before save in the ModelViewSet (override perform_create method). I dont want to create routes (urls) for this model. Now, if I want to access this model in the code (I can with OauthProvider.objects.all() of course), but I have a few questions: how do I enter data to this model NOT in code? If I use the admin portal for it, it doesn't execute my custom perform_create method, so it gets added to the database in plain text What is the best way to decrypt a message if I retrieve data? -
django update query is not working but works in shell
I have a function in django , it's work well but queryset model not update def SLATarget(instanceID): SLAstatus = 2 print(SLAstatus) print(instanceID) ProcessInstance.objects.filter(no=instanceID).update(SLAstate=SLAstatus) run with SLATarget("1221") result of print is 2 1221 -
How can I import an external python file in django without raising errors in views.py
I am currently working on my website, which is a translator which you input a phrase and it gets translated into my own language. However, it is raising errors because it is not detecting the import. Here's the code of the translator function: def translator(phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper: translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper: translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper: translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper: translation = translation + "C" else: translation = translation + "c" return translation However, I am stuck in showing this funcion in my web, here's the code in views.py, here’s where the problem is shown from .translate import translator def translator_view(request): return render(request,'main/translator.html') def translated_view(request): #here is the main problem text = request.GET.get('text') print('text:', text) translate = translator dt = translator.detect(text) tr = translated.text context = { 'translated': tr } return render(request, context, 'main/translated.html') I knows the solution, please answer this post because I'm genuinely stuck -
Annotate with aggregate of related queryset
I'm having trouble getting my head around a django ORM query. I have the following models: class Container(models.Model): name = models.CharField(...) class ContainerItem(models.Model): amount = models.PositiveSmallIntegerField(...) date = models.DateTimeField(...) container = models.ForeignKey(Container) class Group(models.Model): container = models.ForeignKey(Container) start_datetime = models.DateTimeField(...) end_datetime = models.DateTimeField(...) For a Group queryset, I need to annotate the groups with the sum of the amount fields of the ContainerItems that fall within the group start_datetime and end_datetime. This is what I've got so far, but I keep getting 'This queryset contains a reference to an outer query and may only be used in a subquery.' items = ContainerItem.objects.filter( container=OuterRef('container'), date__gte=OuterRef('start_datetime'), date__lt=OuterRef('end_datetime') ) total_amount_qs = items.aggregate( total_amount=Sum('amount'), ).values('total_amount') Group.objects.all().annotate(amount_sum=Subquery(total_amount_qs) -
NoReverseMatch at / Reverse for 'user_login' not found. 'user_login' is not a valid view function or pattern name
New to Django 2. I have checked all the earlier post related to this error but could not find my mistake. Below are the details : Project - learning_users ; App - basic_app. There are 4 templates - base.html, index.html, login.html, registration. html. views.py from basic_app.forms import UserForm, UserProfileInfoForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required # Views def index(request): return render(request, 'basic_app/index.html') @login_required def special(request): return HttpResponse("You are logged in, Nice !") @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid and profile_form.is_valid: user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'basic_app/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else : return HttpResponse('User Not Active') else: print("Someone tried to login and failed") print("Username : {}, password : {}".format(username, password)) return HttpResponse("Invalid Login Details") else: return render(request, 'basic_app/login.html', … -
AssertionError at /api/movies/ 'MovieViewSet' should either include a `queryset` attribute, or override the `get_queryset()` method
Iam trying to access http://localhost:8000/api/movies/. But, it showing like this ..AssertionError at /api/movies/ 'MovieViewSet' should either include a queryset attribute, or override the get_queryset() method. I attached my code below models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator,MaxValueValidator class Movie(models.Model): title = models.CharField(max_length = 32) description = models.TextField(max_length =300) def __str__(self): return self.title class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) class Meta: unique_together =(("user","movie"),) index_together =(("user","movie"),) serializers.py from rest_framework import serializers from .models import Movie,Rating class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('id','title','description') class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id','stars','user','movie') urls.py from django.contrib import admin from django.urls import path from rest_framework import routers from django.conf.urls import include from .views import MovieViewSet,RatingViewSet router = routers.DefaultRouter() router.register('movies',MovieViewSet,basename='movies') router.register('ratings',RatingViewSet,basename='ratings') urlpatterns = [ path('', include(router.urls)), ] views.py from django.shortcuts import render from rest_framework import viewsets from .models import Movie,Rating from .serializers import MovieSerializer,RatingSerializer class MovieViewSet(viewsets.ModelViewSet): query_set = Movie.objects.all() serializer_class = MovieSerializer class RatingViewSet(viewsets.ModelViewSet): query_set = Rating.objects.all() serializer_class = RatingSerializer -
AWS: This XML file does not appear to have any style information associated with it. The document tree is shown below. (Django)
I'm using S3 services to store my projects media files but they are not showing. This is the problem the django's debugger displays when I open an image to a new tab. I'm on EU Paris Region and basically this is the message shown. This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> <AWSAccessKeyId>#################</AWSAccessKeyId> <StringToSign>AWS4-HMAC-SHA256 20200927T094200Z 20200927/eu-west-3/s3/aws4_request ###</StringToSign> <SignatureProvided>#####</SignatureProvided> <CanonicalRequest>###</CanonicalRequest> <RequestId>84D23A1D58F00C2D</RequestId> </Error> I've searched everywhere but none seem to have a solutions for django based applications My settings.py: AWS_S3_REGION_NAME = 'eu-west-3' AWS_ACCESS_KEY_ID = '################' AWS_SECRET_ACCESS_KEY = '##########################' AWS_STORAGE_BUCKET_NAME = '########' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' (p.s I have hashtaged the sensitive informations) -
Observing django-background-tasks metrics with Prometheus
I am trying to collect application-specific Prometheus metrics in Django for functions that are called by django-background-tasks. In my application models.py file, I am first adding a custom metric with: my_task_metric = Summary("my_task_metric ", "My task metric") Then, I am adding this to my function to capture the timestamp at which this function was last run successfully: @background() def my_function(): # my function code here # collecting the metric my_task_metric.observe((datetime.now().replace(tzinfo=timezone.utc) - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds()) When I bring up Django, the metric is created and accessible in /metrics. However, after this function is run, the value for sum is 0 as if the metric is not observed. Am I missing something? Or is there a better way to monitor django-background-tasks with Prometheus? -
How to stop response until page get full load with pdfkit.from_url in python
I am converting url to pdf file by using pdfkit.from_url. Here when ever I hit that url then with in fraction to seconds it is converting to pdf(here it is not waiting to load all data in page url). my problem is how to stop pdfkit.from_url until page data get load full. Please give me slolution. This is my code pdf_file = pdfkit.from_url(url, path + 'assigned_id' + '_' + str(assign_code) + '.pdf', options=options) -
Is it really necessary to use virtualenv for a new Django or Flask project?
I started to learn Flask and Django, and it is preferred to create a virtualenv before installing the dependencies system-wide or globally. But isn't installing globally would help using the dependencies for other projects as well. Also, creating virtualenv and installing Django/Flask for every project would take up system memory. -
Did Debug=(os.getenv("DEBUG_VALUE")=='True') but still showing debug info on all devices
I have hide my debug value and security key in env variable. but after accessing a unknown page on my website. it shows debug information. what am I doing wrong? # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.getenv("DEBUG_VALUE") == 'True') DEBUG_VALUE = 'True' in env var. and I have done heroku config:set Secret_Key="***" and Debug_value='True' -
TemplateSyntaxError at /notes/list/ add requires 2 arguments, 1 provided
I am trying add pagination in my notes list but i am having an 2 argument error. I don't know to fix it. Can you guys tell me how can I solve it? notes/views.py class NotesListView(LoginRequiredMixin,ListView): login_url = '/accounts/login/' model = Notes context_object_name = 'notes_data' paginate_by = 3 def get_queryset(self): return Notes.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') notes/notes_list.html {% if is_paginated %} {% if page_obj.has_previous %} <a class ='btn btn-warning'href='?page=1'>first</a> <a class ='btn btn-warning'href="?page={{page_obj.previous_page_number}}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if num == page_obj.number %} <a class ='btn btn-warning'href="?page={{num}}">{{num}}</a> {% elif num > page_obj.number|add.'-1' and num < page_obj.number|add.'1' %} <a class ='btn btn-success'href="?page={{num}}">{{num}}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class ='btn btn-warning'href="?page={{page_obj.next_page_number}}">Next</a> <a class ='btn btn-warning'href="?page={{page_obj.paginator.num_pages}}">Last</a> {% endif %} {% endif %}