Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement as new Django application whose data are based on MS Access?
I need to implement a new version from scratch of an old software (the new version will be web based). The data is already available in a MS Access database. The company wants to use the new application while the old one is still on production. The technology I chose to develop the new version is Django. The issue is the database technology. I want to use postresql. Is there a way to easily implement the new version while being based on MS Access + postgresql in parallel? I cannot modify the old software to adapt its backend to postgres and Django does not seem to provide support for MS Access on Linux. Is there an alternative way here? -
Will .save() data from Api directly to db be faster than sending it from a Django form?
I am pulling a lot of data from an API to my django template and I keep getting a 504 timeout error so it never finishes. I can cut the data I am calling in half and it prints just fine. Will I get any error if I pull the data from the api and save it to my db straight from my view?? -
How to return an HTML file in Django that is NOT a template?
I have a particular HTML file that I want to show in Django. This file is generated externally and will not use Django template syntax. In fact, it includes some syntax that confuses the Django template generator (like {{ #something }}) and makes it return an error. What is the best way to return this particular HTML page in a way that does not trigger the template syntax to be used? I use this now, and it works, but is this the recommended way? Any drawbacks? def annual_report(request): from django.http import HttpResponse html_content = open("templates/reports/annualreport.html") return HttpResponse(html_content) -
Listing only specific values in OneToOneField Django
I have two models. The first one is a tools/models.py and the second one is projects/models.py. The tools model has a OneToOneField which refer to my projects model. But I don't want to show the project's name if the project status IS 'DONE' So how can I set a condition before adding the models.OneToOneField ? Thanks.. -
how do i send an email to verify someones email address in DRF
hello i have tried a tutorial on how to send an email verification https://www.youtube.com/watch?v=BXg-b20Xusw but when i create a user it doesn't send an email for verification here is my code views.py class UserCREATEView(generics.ListCreateAPIView): queryset = Users.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] authentication_classes = [] def create_user(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() user = Users.objects.get(email=serializer.data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relative_link = reverse('email-verify') absurl = 'http://' + current_site + relative_link + "?token=" + str(token) email_body = "Hello " + Users.username + ' use the link below to verify your email. \n' + absurl data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify Account'} Util.send_email(data) return Response(serializer.data, status=201) else: return Response(serializer.errors, status=400) class Verifyemail(generics.GenericAPIView): def get(self): pass utils.py class Util: @staticmethod def send_email(data): email=EmailMessage(subject=data['email_subject,'], body=data['email_body,'], to=[data['to_email']]) email.send() .env export EMAIL_HOST_USER={myemail} export EMAIL_HOST_PASSWORD={my password} settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS=True EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_HOST_USER= os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD= os.environ.get('EMAIL_HOST_PASSWORD') is there anything i am missing? -
Issue with Custom Authentication Background and Custom Login Form
I am working on a django app where I have to authenticate users from active directory. I can do it with following code in CustomAuthenticationBackend: def authenticate(self, request, **kwargs): username = kwargs['username'] password = kwargs['password'] # type = kwargs['userType'] adConnect,message = self.is_valid_ad(username, password) if adConnect: request.session['pss'] = password try: userExist = User.objects.get(username__iexact=username) if userExist.check_password(password) is True: return userExist else: pass except User.DoesNotExist: # raise ValidationError(username+" is not allowed to access this application.") return self.createNewUserFromAD(adConnect, username, password) else: pass and in settings.py AUTHENTICATION_BACKENDS = ( 'dcw_app.CustomBackendAuth.CustomBackendAuth', 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) and in urls: path('login/', auth_views.LoginView.as_view(template_name='dcw_app/login.html'), name='login'), Problem comes when I need to add an extra field in login form. Authentication does not happen and on submit form is just reloaded. Custom form is like this in forms.py: class UserLoginForm(AuthenticationForm): errors = { 'required': 'Admin Must enter at least one role.', } def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) userType = forms.ChoiceField(error_messages=errors,required=True, label=pgettext("field label","Role"),widget=forms.Select(attrs={'class': 'form-control', 'placeholder': '', 'id': 'userType'}), choices=UserModal.USER_ROLES,) and in urls.py path('login/', auth_views.LoginView.as_view(template_name='dcw_app/login.html',authentication_form=UserLoginForm), name='login'), -
How to get years separated by centuries and decade like YY-YY?
I have a project in django and I want to get a year like 1985 separated in two scrolldowns one going from 00 to 20 and another going from 00 to 99, I tried using selectDate widgets, and also tried modifying some datepickers without success -
Unable to load custom JS file in Django admin home
I am trying to add Custom css and js in my django admin. But CSS is working but js is not working. I have checked my code. I don't think there is any error in my code. my admin.py from django.contrib import admin from .models import Blog # Register your models here. class BlogAdmin(admin.ModelAdmin): class Media: css = { "all": ('css/main.css',) } JS = ('js/blog.js',) admin.site.register(Blog, BlogAdmin) my blog.js console.log("This is blog.js"); let sc = document.createElement('script') sc.setAttribute('src', 'https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js') document.head.appendChild(sc); document.addEventListener("DOMContentLoaded", function (event) { console.log("This is blog.js"); let sc = document.createElement('script') sc.setAttribute('src', 'https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js') document.head.appendChild(sc); sc.onload = ()=>{ tinymce.init({ selector: '#id_content' }); } }); In the first line of js I have written a code console.log("This is blog.js");. But while inspecting the page I didn't see "This is blog.js" in console. It means my js is not loading in Django admin. Please look into this issue. Thanks in advance. -
Insomnia - CSRF cookie not set
I am trying to use insomnia for POST requests for testing my API in a Django application. I am getting this CSRF token error. I saw this post here Django CSRF Failed: CSRF token missing or incorrect which tells me that I need to set my CSRF Token in my headers but I get this new error in return under Live Preview "No cookies in store for URL". Does anyone know a workaround to this problem? -
Mocking external API in Django
I am trying to mock external api in Django but not sure how to do it properly. Basically, it must mock the json data from external API and then create a new object if all values are valid. The program fetches the geolocation data based on given IP address and saves the object in database if response data includes all required fields. So, how I can mock this process to test a new object creation? services.py import os import requests from .exceptions import ExternalApiException def get_location(ip): url = f'http://api.ipstack.com/{ip}' params = {'access_key': os.environ.get('ACCESS_KEY')} try: res = requests.get(url, params=params) data = res.json() return { 'ip':data['ip'], 'country_name':data['country_name'], 'region_code':data['region_code'], 'city':data['city'], 'latitude':data['latitude'], 'longitude':data['longitude'], 'zip_code':data['zip'] } except requests.exceptions.ConnectionError: raise ExternalApiException('Connection error occured during the fetch process') except requests.exceptions.Timeout: raise ExternalApiException("Connection timeout. Please check your internet connection and try again later") except requests.exceptions.TooManyRedirects: raise ExternalApiException("Too many redirects") except requests.exceptions.RequestException: raise SystemExit(e) tests.py #I am lost in this part @patch('geolocation.services.get_location') def test_create_basic_geolocation(self, mock_request): """Test creating geolocation data""" payload = { 'ip': '', } res = self.client.post(LOCATIONS_URL, payload) self.assertTrue(res.data['ip']) Thanks for any help. -
X-Accel_Redirect returns an empty file when using application port
Dears, When I use X-Accel_Redirect, nginx returns an empty file (when using application port), but when I use the port which nginx listens to, it returns it. I need to return the file on the port the application is running on. I really appreciate your help! -
Use non model django fields in django filter
I have a variable 'cptCodeTBX' which is not present as fields in django models. I need to apply filter on 'cptCodeTBX' variable. Something roughly equivalent to select * from cpt where cpt.code like cptCodeTBX or cptCodeTBX is != '' In dot net entity framework we could do it by b = cptContext.CPTs.AsNoTracking().Where( a => (String.IsNullOrEmpty(cptCodeTBX) || a.Code.StartsWith(cptCodeTBX)) -
django's sql for terminal functions
I know that in order to see the generated SQL statement for queries I could use the .query function (e.g. str(Model.objects.all().query), or same with filter, etc.) I want to see the generated SQL statements for terminal functions used on query sets (e.g. Model.objects.count(), Model.objects.update(...), etc.). As the function is called it's executed without giving out an object like QuerySet to have the query on. So is there a way to see the generated SQL statement for these kind of operations without executing them and looking back at logs, etc.? -
how to create custom scheduler in celery without the help of django celery beats
First to create an app second to create a custom scheduler to work with celery third to integrate to celery -
Internal Server Error. Unable to get access to server's content - apache2
to be short I have encountered a problem that blocked the HTTP/TCP access to port 80 error.jpg below are my errors logs and other related conf errors_logs: [Mon Feb 15 01:56:43.361342 2021] [wsgi:error] [pid 73449:tid 139984461121088] [remote 203.145.94.145:41526] RuntimeError: populate() isn't reentrant [Mon Feb 15 01:56:43.844935 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] mod_wsgi (pid=73449): Failed to exec Python script file '/home/user/project/project/wsgi.py'. [Mon Feb 15 01:56:43.844969 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] mod_wsgi (pid=73449): Exception occurred processing WSGI script '/home/user/project/project/wsgi.py'. [Mon Feb 15 01:56:43.845066 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] Traceback (most recent call last): [Mon Feb 15 01:56:43.845093 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] File "/home/user/project/project/wsgi.py", line 16, in <module> [Mon Feb 15 01:56:43.845097 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] application = get_wsgi_application() [Mon Feb 15 01:56:43.845103 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] File "/home/user/project/venv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Feb 15 01:56:43.845106 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] django.setup(set_prefix=False) [Mon Feb 15 01:56:43.845111 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] File "/home/user/project/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup [Mon Feb 15 01:56:43.845114 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] apps.populate(settings.INSTALLED_APPS) [Mon Feb 15 01:56:43.845119 2021] [wsgi:error] [pid 73449:tid 139984486299200] [remote 203.145.94.145:47921] File "/home/user/project/venv/lib/python3.8/site-packages/django/apps/registry.py", line … -
Add and Update Post from custom html forms in Django
I've created a custom HTML form for my model, just like I want to add a post from the front-end. I already created a page with the name add-post.html add-post.html <form method="POST" action=""> {% csrf_token %} <input name="title" type="text"> <textarea spellcheck="false" name="description"></textarea> <input type="file" name="image" @change="fileName" multiple /> <select required name="priority"> <option value="Low" selected>Low</option> <option value="Medium">Medium</option> <option value="High">High</option> </select> <input type="checkbox" name="on_hold"> <button type="submit">Add ToDo</button> </form> model.py class Todo(models.Model): title = models.CharField(max_length=100) image = models.ImageField(null=True, blank=True, upload_to='todo/images/') description = RichTextField() Low, Medium, High = 'Low', 'Medium', 'High' priorities = [ (Low, 'Low'), (Medium, 'Medium'), (High, 'High'), ] priority = models.CharField( max_length=50, choices=priorities, default=Low, ) on_hold = models.BooleanField(default=False) forms.py class TodoCreationForm(forms.ModelForm): class Meta: model = Todo fields = ('title','image','description','priorities','priority','on_hold') No, I want to use the above custom HTML form to post data and save it to this model database. instead of using {% form.as_p %} And I also created a particular page to update this post from the front-end but don't know how to make it work. Can you please guide me on how can I save data from the custom form and also update it from the custom form? Appreciate your response :) -
Getting JSONDecodeError from django
I'm getting trouble with requests on local developed server using Django Here are my codes veiws.py from django from django.shortcuts import render from django.views import View import json # Create your views here. class RequestView(View): template_name='request.html' def get(self, request): body_unicode = request.body.decode('utf-8') data = json.loads(body_unicode) data_value =data['key'] return render(request, self.template_name, {'content':data_value}) def post(self, request): body_unicode = request.body.decode('utf-8') data = json.loads(body_unicode) data_value = data['key'] return render(request, self.template_name, {'content': data_value}) request.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ conetent }} </body> </html> request on local import requests >>> data = {'key':'value'} >>> url = 'serverip/request' >>> res = requests.get(url, data) I want to get HttpResponse filled with data['key'] on url!! and this is an error message Internal Server Error: /request Traceback (most recent call last): File "/home/django/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 7, in inner response = get_response(request) File "/home/django/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, n _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 70, i view return self.dispatch(request, *args, **kwargs) File "/home/django/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 98, i dispatch return handler(request, *args, **kwargs) File "/home/django/saferoute/request/views.py", line 9, in get data = json.loads(body_unicode) File "/usr/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.7/json/decoder.py", line 355, … -
DRF PUT on Viewset/Serializer does not fire post_save signal on model instance
I have the following DRF viewset: class MyViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet, CreateModelMixin, DestroyModelMixin): serializer_class = MySerializer queryset = My.objects.all() lookup_field = "uuid" The following Serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = My fields = [ 'uuid', 'name' ] I have a signal stored in signal.py in the app @receiver(post_save, sender=My) def my_updated(sender, instance, created, **kwargs): if not created: print('MySignal Fired') The signal is imported in apps.py. The signal is working when I open a terminal and run the .save() method on a instance. The app is also declared in the django config. Any ideas? BTW. when executing the .PUT on the API it saves everything nicely in the DB. So the api is doing it's work. Not sure why the signal is not firing though. -
Add date and time manully in django
I want to add date and time manually for required task but when i add date & time and submit it show error of null field. Model.py from django.contrib.auth.models import User from django.db import models class TaskList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=100, null=False, blank=False) complete = models.BooleanField(default=False) datetimepicker1 = models.DateTimeField(auto_now_add=False) View.py def post(self, request): if SESSION_KEY in self.request.session: try: data = self.request.POST.get task_list = TaskList( user_id=request.session[SESSION_KEY], task=data('task'), datetimepicker1=data('datetimepicker1') ) task_list.save() return redirect('todolist') except Exception as e: return HttpResponse('failed {}'.format(e), 500) Template <form method="post"> {% csrf_token %} <label for="task"> <input name="task" placeholder="add today's task" id="task" required> </label> <div class="input-group date" id="datetimepicker1" data-target-input="nearest"> <label for="datetimepicker1"> <input class="form-control datetimepicker-input" data-target="#datetimepicker1" type="text" id="datetimepicker1" required> </label> <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <button type="submit">add</button> </form> -
Django Column Data Gets Encoded
I'm using raw query to get data from server and data that I receive from one specific column gets converted to bytes, like so: "date": "b'2021-02-09'" Column itself: CASE WHEN some.column IS NULL THEN DATE(some.other_column) ELSE DATE(some.column) END AS "date", I believe that DATE() is getting messed up by Python somehow, cause I have exact same CASE column below, but with TIME() and that column outputs data as str, not bytes My question is: How do I bypass that behavior and receive data from that column as str, or, if possible - how do I decode column data in serializer? -
Django - Saving data without using input fields/forms
I am a novice, apologies if this question seems silly. I need to save some data into MySQL database. There are no input fields. The user should click a button, and a table is updated. The data to be saved is two foreign keys and a PK. Here is my model class Bids(models.Model): id=models.AutoField(primary_key=True) userid = models.ForeignKey(Writer, on_delete=models.DO_NOTHING, related_name='userid ') orderid = models.ForeignKey(Orders, on_delete=models.DO_NOTHING, related_name='orderids') biddatetime=models.DateTimeField(auto_now_add=True) I have tried writing several functions to save these fields into table bids but no joy so far. Hers's a sample. def saveBid(request): if request.method!= "POST": return HttpResponse("Action Not Allowed") else: biddatetime=request.POST.get('biddatetime') bids= Bids(biddatetime=biddatetime) order=Orders(id=id) user= CustomUser() user.save() bids.save() Pls assist -
Django, Djoser social auth : State could not be found in server-side session data. status_code 400
i'm implementing an auth system with django and react. The two app run respectively on port 8000, 3000. I have implemented the authentication system using the Djoser package. This package use some dependencies social_core and social_django. Everything seems to be configured ok. I click on login google button...I'm redirected to the google login page and then back to my front-end react app at port 3000 with the state and code parameters on the url. At this point I'm posting those parameters to the backend. The backend trying to validate the state checking if the state key is present in the session storage using the code below from (social_core/backends/oauth.py) def validate_state(self): """Validate state value. Raises exception on error, returns state value if valid.""" if not self.STATE_PARAMETER and not self.REDIRECT_STATE: return None state = self.get_session_state() request_state = self.get_request_state() if not request_state: raise AuthMissingParameter(self, 'state') elif not state: raise AuthStateMissing(self, 'state') elif not constant_time_compare(request_state, state): raise AuthStateForbidden(self) else: return state At this point for some reasons the state session key is not there..and I receive an error saying that state cannot be found in session data ( error below ) {"error":["State could not be found in server-side session data."],"status_code":400} I recap all the … -
400 Bad Request The plain HTTP request was sent to HTTPS port, while Deploying Django to AWS with Docker and Let's Encrypt
I am following the "Django on Docker Series" series by testdrivenio for deploying a project into a new domain. I am using Django as backend but when I try to access the backend url via the port it showing via docker ps command i.e., http://0.0.0.0:443/ I get the following error, This is the docker-compose file I am using version: '3.7' services: web: build: context: ./myprojectname dockerfile: Dockerfile.staging image: 789497322711.dkr.ecr.us-east-3.amazonaws.com/myprojectname-staging:web command: gunicorn myprojectname.wsgi:application --bind 0.0.0.0:8005 volumes: - static_volume:/home/myprojectname_staging/web/static - media_volume:/home/myprojectname_staging/web/media expose: - 8000 env_file: - ./.env.staging frontendimage: container_name: frontendimage image: 789497322711.dkr.ecr.us-east-3.amazonaws.com/myprojectname-staging:frontendimage stdin_open: true build: context: . dockerfile: frontend/Dockerfile.staging # volumes: # - type: bind # source: ./frontend # target: /usr/src/frontend # - '.:/usr/src/frontend' # - '/usr/src/frontend/node_modules' ports: - '1337:30' environment: - CHOKIDAR_USEPOLLING=true depends_on: - web nginx-proxy: container_name: nginx-proxy build: ./myprojectname/nginx image: 789497322711.dkr.ecr.us-east-3.amazonaws.com/myprojectname-staging:nginx-proxy restart: always ports: - 443:443 - 80:80 volumes: - static_volume:/home/myprojectname_staging/web/staticfiles - media_volume:/home/myprojectname_staging/web/mediafiles - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro depends_on: - web nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy volumes: static_volume: media_volume: certs: html: vhost: My Nginx directory └── nginx ├── Dockerfile ├── custom.conf └── vhost.d └── default Dockerfile FROM jwilder/nginx-proxy COPY vhost.d/default /etc/nginx/vhost.d/default COPY custom.conf /etc/nginx/conf.d/custom.conf … -
Why I get error-404 while I try to add new position in admin-panel Django?
All's working for a local version. But on production-server I get 404-error (Page not found) when I try to add new position in admin-panel. I suppose that I have problems with image-fields. And I think that I maked errors for BASE_DIR and MEDIA_ROOT. urlpatterns = [ path('admin/', admin.site.urls), path('', include('pharmacy.urls')), path('articles/', include('articles.urls', namespace='articles')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In a app: urlpatterns = [ path('', views.index, name='main'), path('about', views.about, name='about'), path('contact', views.contact, name='contact'), ] My Model: class Product(models.Model): title = models.CharField(max_length=200, verbose_name='Название') description = models.TextField(max_length=2000, verbose_name='Описание', blank=True, null=True) pic = models.ImageField(verbose_name='Картинка', upload_to='pharmacy/products') is_published = models.BooleanField(verbose_name='Опубликовано', default=True) def __str__(self): return self.title class Meta: verbose_name = 'Продукт' verbose_name_plural = 'Продукты' serrings.py: BASE_DIR = Path(__file__).resolve(strict=True).parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ BASE_DIR / "pharmacy/static", os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I'm attaching screenshot with my file structure. -
Python: How to call all objects of a class with their attributes in Django?
For some context, the class is meant to hold the metadata of the products, which are objects. Now, I would like to pass the objects to my template, in order to call its attributes. Here's my code in views.py: def prices(request): @attr.s class ProductMetadata: """ Metadata for a Stripe product. """ stripe_id = attr.ib() name = attr.ib() features: list = attr.ib() monthly_price = attr.ib() yearly_price = attr.ib() standard = ProductMetadata( stripe_id='example', name='Standard', features=[(True ,"Up to 1000 DMs"), (False, "Ludicrous mode"), (False, "Premium Support")], monthly_price = "month1", yearly_price = "year1" ) premium = ProductMetadata( stripe_id='example2', name='Premium', features=[(True ,"Up to 1000 DMs"), (True, "Ludicrous mode"), (False, "Premium Support")], monthly_price = "month2", yearly_price = "year2" ) business = ProductMetadata( stripe_id = "example3", name = 'Business', features=[(True ,"Up to 1000 DMs"), (True, "Ludicrous mode"), (True, "Premium Support")], monthly_price = 'month3', yearly_price = 'year3' ) return render(request, 'instagram_prices.html', {'products': ProductMetadata.all()}) How can I achieve this? Thanks!