Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ValueError The view HomeFeed.views.AddCommentView didn't return an HttpResponse object. It returned None instead
I received this error from the code: ValueError at /HomeFeed/comments/testuser1-2 The view HomeFeed.views.AddCommentView didn't return an HttpResponse object. It returned None instead. Any idea why this is happening? Like which part is causing this problem too, is it the function or my reverse lazy line? models.py class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE) body = models.TextField() date_added = models.DateField(auto_now_add=True) class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] widgets = { 'body' : forms.Textarea(attrs={'class': 'form-control'}), } views.py class AddCommentView(DetailView, FormView): model = BlogPost # change model to post because your are commenting on POSTS not COMMENTS form_class = CommentForm template_name = 'HomeFeed/add_comment.html' success_url =reverse_lazy('HomeFeed:main') def form_valid(self, form): comment = form.save(commit=False) #comment.user = self.request.user comment.name = self.request.user comment.post = self.get_object() comment.save() -
How to create a template in django that can be use any other page and that rander same / editable if needed
i created a base template home.html, there is footer and i pass categories on footer and it work fine in home.html but there is extended pages view.html when i go to this page the footer categories is not showing likewise footer is not showing in other pages how can i solve this problems . to incluse view.html in home.html home.html {% block body %} {%endblock%} <--footer--> <div class="col-xs-6 col-md-3"> <h6>Categories</h6> <ul class="footer-links"> {% for category in procategory %} <li><a href="foodgrains?category={{category.id}}">{{category.name}}</a></li> {% endfor %} </ul> </div> view.html {% extends 'home.html' %} {% load static %} {% block body %} <--my code --> {% endblock body %} problems is when i go to view,html the footer categories value is not showing can any one have any suggestion to solve ,how the footer categories show in different page i sloe use {% include 'footer.html' %} it also doesn't work -
Why are the contents of my static css and js files being replaced by html code?
I have a pure js application from which I have generated the build files using yarn build I have the following files I now need to serve these files using Django. Here is what I have tried I have added a frontend folder in the Django app as follows I have also added the following URL re_path("wazimap/", TemplateView.as_view(template_name="index1.html")) and updated the settings file with the following TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ["frontend/build/dist"], ....More code STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "frontend/build/dist"), ] now when I access the /wazimap/ URL, the HTML is served but the css/js that is being loaded contains the wrong code. I can see from the console that the files are being requested but index1.html is what is being placed inside all the css/js files i.e The contents of the css/js files are the content of the index1.html file. So a js file has something like <!DOCTYPE HTML>... which isn't a valid js thus causing errors. Any ideas why this is happening? -
How to add email in Django amin Add user Page
I have created a CustomUser(AbstractUser) Model and in this model I want to add email id field in admin Add User Page.Currently By default first we can enter username and Password and after creating username and password we are redirected to another page where email field is available I want this email field on add User page is this possible.? -
Jupyter Installation
i am quite new into the Jupyter community and want to experience what jupyter has to offer. My knowledge about Jupyter is still quite limited While I was downloading jupyter and trying to open the jupyter notebook. Errors below were shown to me instead. Traceback (most recent call last): File "C:\Users\Tan Caken\anaconda\Scripts\jupyter-notebook-script.py", line 6, in from notebook.notebookapp import main File "C:\Users\Tan Caken\anaconda\lib\site-packages\notebook\notebookapp.py", line 51, in from zmq.eventloop import ioloop File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq_init_.py", line 50, in from zmq import backend File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend_init_.py", line 40, in reraise(*exc_info) File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise raise value File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend_init_.py", line 27, in ns = select_backend(first) File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend\select.py", line 28, in select_backend mod = import(name, fromlist=public_api) File "C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend\cython_init.py", line 6, in from . import (constants, error, message, context, ImportError: cannot import name 'constants' from partially initialized module 'zmq.backend.cython' (most likely due to a circular import) (C:\Users\Tan Caken\AppData\Roaming\Python\Python38\site-packages\zmq\backend\cython_init_.py) And I don't know how to solve this problem. I kinda notice the import error that says there is a python thing install beforehand, but other than that. I have no clue on resolve on this. T -
Operational Error: no such table: background_task - clean way to deploy?
I have an issue with background_tasks and deploying. When running makemigrations I get: no such table: background_task here are my INSTALLED_APPS: INSTALLED_APPS = [ 'appname.apps.AppnameConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'background_task', ] I also tried python manage.py makemigrations background_task before python manage.py makemigrations but this also failed. My workaround for now is to rename the tasks.py to tasks and to comment the part in the urls.py where I call the tasks from the tasks.py and deleting background_task from settings.py. Then I do all the migrating and then undo my renaming/commenting/deleting. This works, but there must be a better way? I already tried the tips from here (but my workaround is based a little bit on OPs own answer) and here. -
In Django, after login I'm able to redirect to the previous page, but if the login page is directly accessed then unable to redirect
I want to secure each webpage of my django app, and what I want is that after login the user should be redirected to the previous page he was trying to access. So in accounts/views.py this is the login function I am using for that: def login(request): if request.method == 'POST': #some code if user is not None: auth.login(request, user) return redirect(request.POST.get('next','dashboard')) else: #some code else: #some code Now, I have used @login_required condition for each view of my webapp in this way: @login_required(login_url='login') def profile(request): return render(request, 'profile.html') my login.html: <form method="POST" action="/accounts/auth"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.GET.next }}" /> {{ login_form }} <input type="submit"> </form> Now if the user visits accounts/profile without login, then he is redirected to accounts/login?next=/accounts/profile, so after login he is successfully redirected to accounts/profile as the value of 'next' is set to /accounts/profile and in login function if the user is authenticated then i have used return redirect(request.POST.get('next','dashboard')) which means redirect to the value of next if it is entered, otherwise /accounts/dashboard. Now coming to my issue, if I try to access the login page directly (i.e. /accounts/login) then as there is no next variable in the URL, so according to … -
Django Field Error (Unknown Fileds) even though field is already included in models.py
I keep getting the error, FieldError at /admin/products/variant/add/ Unknown field(s) (default) specified for Variant. Check fields/fieldsets/exclude attributes of class VariantAdmin. Even though the field default is included in my Variant Model models.py file class Variant(models.Model): COLOR_CHOICES = [ ('black', 'Black'), ('grey', 'Grey'), ('white', 'White'), ('blue', 'Blue'), ('green', 'Green'), ('yellow', 'Yellow'), ('orange', 'Orange'), ('red', 'Red'), ('purple', 'Purple'), ('gold', 'Gold'), ('silver', 'Silver'), ('brown', 'Brown'), ('pink', 'Pink'), ('colorless', 'Colorless'), ] CLOTH_SIZE_CHOICES = [ ('xxs', 'XXS'), ('xs', 'XS'), ('s', 'S'), ('m', 'M'), ('l', 'L'), ('xl', 'XL'), ('xxl', 'XXL'), ('xxxl', 'XXXL')] product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='variants') default = models.BooleanField(default=False), price = models.FloatField() old_price = models.FloatField(blank=True, null=True) quantity = models.IntegerField() # Dimensions in cm height = models.FloatField(blank=True, null=True) width = models.FloatField(blank=True, null=True) length = models.FloatField(blank=True, null=True) # in kg weight = models.FloatField(blank=True, null=True) # Colors color_family = models.CharField(max_length=20, choices=COLOR_CHOICES) specific_color = models.CharField(max_length=50, blank=True, null=True) # Clothing and Shoes cloth_size = models.CharField( max_length=20, choices=CLOTH_SIZE_CHOICES, blank=True, null=True) shoe_size = models.IntegerField(blank=True, null=True) # Computing ram = models.IntegerField(blank=True, null=True) rom = models.IntegerField(blank=True, null=True) # in cm screen_size = models.FloatField(blank=True, null=True) def __str__(self): return f"{self.product} Variant" def in_stock(self): return self.quantity > 0 def discount(self): if (self.old_price == self.price) or (self.old_price < self.price): return 0 return (100 - ((self.price / self.old_price) … -
Error 500 deploying a DJANGO app on heroku, in everything except the index
The view with the index works perfect even with statics, but the other views show the error 500 The code of my urls.py is next: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include("home.urls",namespace="home")), path('api/',include("api.urls",namespace = "api")), ] +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and that one in my urls home folder (app folder) from django.urls import path from django.contrib.auth import views as auth_views from home import views from django.conf import settings from django.conf.urls.static import static app_name="home" urlpatterns=[ path('VerItems/',views.VerItems, name="VerItems"), path('VerAutores/',views.VerAutores, name="VerAutores"), path('AgregarAutor/',views.AgregarAutor, name="AgregarAutor"), path('AgregarItem/',views.AgregarItem, name="AgregarItem"), path('',views.Index.as_view(), name="index"), ] And finally. settings file, I know that BASEDIR is not what every web shows it should be, but if I change it, the index does not work anymore from pathlib import Path import os.path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ke-7l!7r!e$f#8+e=bv9(&wu_1@purto!^#ut948t8)od+@te(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Django: How to make it such that I can submit interest to any blogpost, not just 1 blog post?
Django: How to make it such that I can submit interest to any blogpost, not just 1 blog post? Currently, now after I submit interest to a blogpost, I can no longer submit interest to any other blog post. I will receive this message saying that 'You have already submitted your interest to this post.' Even though i haven't. Judging by the nature of my model. Is there a way for me to filter the 'user' field in my interest model such that I am only checking through to see if the particular user in that particular blog post has already submitted the interest? Cause i understand that right now, they are filtering it based on all the blogpost, and as long as I have already submitted 1, it definitely exists. Please let me know if you need my forms.py , urls.py too if it helps. views.py def submit_interest_view(request, slug): form = SubmitInterestForm() user = request.user blog_post = get_object_or_404(BlogPost, slug=slug) num_blogpost = BlogPost.objects.filter(author=user).count() if blog_post.author.email == user.email: return HttpResponse('You cannot submit interest to your own post.') if Interest.objects.filter(user=request.user).exists() and request.method=="POST": return HttpResponse('You have already submitted your interest to this post.') if request.method == 'POST': form = SubmitInterestForm(request.POST, request.FILES) if form.is_valid(): … -
How Mediafire (file Hosting) works or how to develope a Medifire like clone?
Actually, I was learning Django So I want to make a project for my own curiosity and also want to learn more about scalability and load. -
Django: Can't access static files in python script
i have deployed a django project with mod wsgi on an apache server. Everything works so far. In one python script I'd like to open a file in static files. Therefore I have tried something like this: mycode.py import cv2 class Foo(): def __init__(self): ... def openImg(self): self.myimg = cv2.imread('static/myapp/img/picture.jpg',0) return self.myimg .. just for testing However it can't find this file. Whether in path ('static/myapp/img/picture.jpg'), nor path ('myapp/static/myapp/img/picture.jpg') nor in path ('../static/myapp/img/picture.jpg') and some other which I have already forgot. It always returns "None". If I try the same on my "undeployed" local project it works without any problem. I have already collected all staticfiles to /myproject/static and given enough rights to access them. By the way, the access to the static files in the html works in production. What's the problem? Can you give me any advice? Thank you. Some additional information: views.py from django.shortcuts import render from .mycode import Foo def index(request): # New Instance for class Foo bar = Foo() # Return img array to put it in html for whatever imagearray = bar.openImg() context = {'imgarray': imgarray} return render(request, 'electreeksspy/index.html', context) Thats an example of my directory /home/myuser/MyProject /static/myapp/img/picture.jpg (collected) / /myapp /static/myapp/img/picture.jpg /mycode.py /views.py … -
Django: simple_tag not rendering simple string
I am trying to create dynamic menus list under one mega menu.The menus will be fetched from database.I am using Django simeple_tag feature to achieve this but some how does not render the simple test string which I am giving although I want to render HTML tags at the end.Here is my code, my_app/home/templatetags/menus.py from django import template register = template.Library() @register.simple_tag(name='downloadable_menus') def downloadable_menus(a): """ Generate the downloadable menus under the free resources mega menu """ return 'Hello' This is how I am using in template. {% load menus %} <div class="content"> <ul class="menu-col"> {{ downloadable_menus }} </ul> </div> So the above code should display the "Hello" string in the menu but it is not.Any help would be appreciated. -
How to import a value inside another class model in Django?
shope/models.py from django.db import models class Product(models.Model): PN = models.CharField(max_length=100, default = "AAAA") Ship/models.py from shop.models import Product class OrderItem(models.Model): product = models.ForeignKey(Product, related_name='ship_items', on_delete=models.CASCADE) PN = models.ForeignKey(Product.PN, related_name='ship_items', on_delete=models.CASCADE) print(PN) All I want to do is to get PN from shope/models.py into Ship/models.py then print it. -
PLEASE HELP: assert not cls._meta.auto_field, ( AssertionError: Model shop.Product can't have more than one auto-generated field
I GOT MORE THAN ONE AUTO-GENERATED FIELD ERROR product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to="shop/images", default="") def __str__(self): return self.product_name``` -
How to store file in django session and get that file in another view and store in database
I created form where user upload their photo and other details before they submit the form i want to redirect somewhere because of payment gateway so how can i handle it. this is in my views #this is for order creation def form_submit(request): white_bg_photo = request.FILES['white_bg_photo'] front_page = request.FILES['front_page'] request.session['file1'] = white_bg_photo request.session['file2'] = front_page if order_status == 'created': context['data'] = data #all other stuff i am sending to order confirmation return render(request, 'order_confirmation.html',context) else: return(request,'error.html') #this is for order confirmation def payment_status(request): response = request.POST data = request.POST.get('data') params_dict = { 'razorpay_payment_id' : response['razorpay_payment_id'], 'razorpay_order_id' : response['razorpay_order_id'], 'razorpay_signature' : response['razorpay_signature'] } # VERIFYING SIGNATURE try: status = client.utility.verify_payment_signature(params_dict) booking = Booking() booking.white_bg_photo = request.session['file1'] booking.front_page = request.session['file2'] booking.data = data booking.save() return render(request, 'order_summary.html', {'status': 'Payment Successful'}) except: return render(request, 'order_summary.html', {'status': 'Payment Faliure!!!'}) -
Adding Button in Django Admin Panel
In my main Django Project, I have an app called "Argentina" where I have registered model "PowerPlantMix". The model will have list of PowerPlants in Argentina with their respective capacities. Goal: What I am trying to do is to have an extra button by name of "Button" (as given in image) in which a URL would be embedded that would take me to respective URL(already registered in url.py). Is there a way I can add a button in models. As I have multiple apps I cannnot use the view site button. Thanks -
Django, Next.JS: CORS header ‘Access-Control-Allow-Origin’ missing, CORS request did not succeed even though django-cors-headers is defined
I am stuck with the old and confusing issue of CORS with Django and Next.JS. My setup: OS: Windows 10, Browser: Mozilla: 84.0.2 (64-bit), Django: 3.1, Next.JS: 10. My Django settings: INSTALLED_APPS = [ ... 'corsheaders', 'rest_framework', 'my_app', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True urls.py: from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('my_app.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] My Next.js page: import { useState } from 'react'; import axios from 'axios'; export default function loginForm() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = () => { const headers = { "Content-Type": "application/json", "Accept": "application/json" } return axios({ method: "POST", url: "http://127.0.0.1:8000/api/token/", data: { username: username, password: password }, headers: headers }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); }; return ( <div className="loginBox"> <div className="lblBox"> <label className="label" htmlFor="loginbox"> Enter Username and Password <div className="unameInput"> <input type="text" name="username" placeholder='Enter username' onChange={e => setUsername(e.target.value)} /> </div> <div className="passwordInput"> <input type='password' name='password' placeholder='Enter password' onChange={e => … -
Making nested queries using the Django ORM
Assuming I have a model like below: class Region(models.Model): info = JSONField() number = models.IntegerField() I want to write a ORM query which translates into a nested SQL query similar to the below one: SELECT result, COUNT(number) FROM (SELECT jsonb_object_keys("region_table"."info") as result, number from region_table) pp group by number; Is there any way to perform the above nested SQL query? -
Using python-decouple, how do I pass a variable with a carriage return (rsa key)?
I have a rsa key in my .env file like this: MY_KEY=-----BEGIN PRIVATE KEY-----\n********my key**********\n-----END PRIVATE KEY-----\n When using from decoule import config and "private_key": config("MY_KEY"), the following is the result I get. MY_KEY=-----BEGIN PRIVATE KEY-----\\n********my key**********\\n-----END PRIVATE KEY-----\\n The extra slash in \\n is causing a problem in that my google.oauth2 can't recognize the key. Is there a way to import the key so that only one slash is returned and not two? -
check if exist on postgres array django
i have this zone like east west north south and i have added states in all 4 zone.every states stored in array type like this ids: {cd26ddeb-04cb-4d9a-8c7f-51d5d389f475,bc44618d-3a21-475b-8d74-c0542abb173b,18695611-256e-4506-a087-596f8914551d} what i'm trying to do is whenever i have any new state it should check on all zone if it exist then do nothing otherwise add this. Issue is i'm passing new states that need to add with previous added states. then i'm checking with all zone states if not exist then add this to new_state list and pass to data but this part not working: if state not in all_state: #its not filtering states returning all new_state.append(state) @api_view(['POST']) @login_required_message def zoneEdit(request): data = decode_data(request.data.copy()) new_state = [] try: try: zone_queryset = Zone.objects.get(uid=data['uid']) all_state = Zone.objects.values_list('state',flat=True) print(all_state, "all_state") data["created_by"] = request.user.uid for state in data['state']: if state not in all_state: #its not filtering states returning all new_state.append(state) print(new_state, "to be added") zone_serializer_obj = ZoneSerializer(zone_queryset, data=new_state) if zone_serializer_obj.is_valid(): try: city_save = zone_serializer_obj.save() return CustomeResponse(request=request, comment=ZONE_NAME_UPDATE, data=json.dumps(zone_serializer_obj.data, cls=UUIDEncoder), status=status.HTTP_200_OK, message=ZONE_NAME_UPDATE) except Exception as e: return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), message=SOMETHING_WENT_WRONG+" mv54 "+str(e), data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, data=json.dumps(zone_serializer_obj.errors, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) except City.DoesNotExist: return CustomeResponse(request=request, … -
Django template progress bar upload to AWS s3
I have a form where the user can upload multiple files and I am using jquery ajax to submit the files and other fields in the form. when uploading large files.. the site looks unresponsive so I wanted to add a progress bar. so inside the xhr parameter, I wrote... xhr: function () { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function (e){ if (e.lengthComputable) { console.log('Bytes Loaded: '+e.loaded) console.log('Total Size: '+e.total) console.log('Percentage Uploaded: '+(e.loaded/e.total)) } }); return xhr; } but this does not work properly because almost instantly the percentage uploaded shows 1 i.e. 100% while the actual file takes its own time to upload and after that, the success message is shown. What am I doing wrong? -
AWS Lightsail 'Exception occurred processing WSGI script'
I followed the amazon tutorial EXACTLY for deploying a Django app on lightsail: Deploy Django-based application onto Amazon Lightsail. But when I visit my IP address (http://52.41.70.195/) I get Internal server error. When I check the apache error logs I see these errors: Failed to parse Python script file '/opt/bitnami/projects/Django-E -Commerce/perfectcushion/wsgi.py'. Exception occurred processing WSGI script '/opt/bitnami/projects/Django-E-Commerce/perfectcushion/wsgi.py'. My wsgi.py file looks like the one amazon provides: import os import sys sys.path.append('/opt/bitnami/projects/Django-E-Commerce’) os.environ.setdefault("PYTHON_EGG_CACHE", "/opt/bitnami/projects/Django-E-Commerce/egg_cache") os.environ.setdefault("DJANGO_SETTINGS_MODULE", “Django-E-Commerce.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Any suggestions? -
Cannot publish Django Rest API on heroku
I'm trying to publish my Django rest framework application to Heroku. I'm following all the procedures accordingly to publish from Github repository but don't know where is my mistake. In Heroku deploy tab it says deployed successfully but while i go to visit the page it show the following error. My folder structure is as follows where my API is in api folder and the project is in config folder: I've specified the file name in Heroku procfile as follows (adding asgi file since my project is using asgi instade of wsgi for Django channels): web: gunicorn config.asgi --log-file - When I check the error from the terminal it cannot find module config but also show build success. The error is as follows: 2021-01-14T07:10:10.612461+00:00 heroku[web.1]: State changed from crashed to starting 2021-01-14T07:10:25.885018+00:00 heroku[web.1]: Starting process with command `gunicorn config.asgi --log-file -` 2021-01-14T07:10:30.278347+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-01-14T07:10:30.279496+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [4] [INFO] Listening at: http://0.0.0.0:36267 (4) 2021-01-14T07:10:30.279664+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [4] [INFO] Using worker: sync 2021-01-14T07:10:30.296521+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [9] [INFO] Booting worker with pid: 9 2021-01-14T07:10:30.305338+00:00 heroku[web.1]: State changed from starting to up 2021-01-14T07:10:30.310836+00:00 app[web.1]: [2021-01-14 07:10:30 +0000] [9] [ERROR] Exception … -
How do I add Pagination to a table (Django)
I am trying to add pagination to one of the tables for my project, but I can't find any good resources to refer to, all of the docs use some kind of URL query, but I don't want to do that, since it is on the user page. Background --- I am making a mock website for trading for a project and I need the user to be able to see their trade history, and as you can imagine, after any more than 10, the page starts to look very long, so I am trying to find a way to make the table have pages, but I just can't figure it out. Aim -- To add pages to a bootstrap table. The table should be able to go back and forth using buttons. My "solution" - after going through stuff for about an hour, I found this but I don't know if it is good/safe. Code : VIEW - def userPage(request): user = request.user user_info = user.info trades = user_info.trade_set.all().order_by('-time_bought_at') ###I want this queryset to be paginated total_trades = trades.count() balance = round(user_info.balance) context = { "user" : user, "user_info" : user_info, "trades" : trades, "total_trades" : total_trades, "balance" : …