Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect www to no-www URL - Nginx
I am using DigitalOcean to host my Django app and I am trying to forward all the www.example.com URLs to example.com. I am also using Let's Encrypt to enable HTTPS, so if anyone can help me please let me know. /etc/nginx/sites-enabled/default server { server_name www.example.com; return 301 $scheme://example.com$request_uri; } /etc/nginx/sites-enabled/example.com server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 301 https://example.com$request_uri; } server { listen [::]:443 ssl ipv6only=on; listen 443 ssl; server_name example.com www.example.com; # Let's Encrypt parameters ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; } } -
How to pass more than one parameter to url in django
HTML page has 2 button to process payment, I need to pass 2 parameters to url for a reason. Below is the method I tried but it's not working. Can someone help me here..?? <a href="{% url 'process-payment' order.id button.id %}" id = "CashOnDelivery" class="btn btn-warning"> Cash on Delivery</a> <a href="{% url 'process-payment' order.id button.id %}" id = "Card" class="btn btn-warning">Pay through Card</a> views.py def process_payment(request, order_id, button_id): if id == CashOnDelivery # directly take order return redirect (reverse('update-records', kwargs={'order_id': order_id})) else # process the card payment then update transaction return redirect (reverse('update-records', kwargs={'order_id': order_id})) urls.py urlpatterns=[ path('payment/<order_id>/<button_id>',views.process_payment, name='process-payment'), ] -
Stream video to web browser using Django in Python
Peace and blessing to everyone There is a guide to streaming video with flask. Has anyone written anything similar with django? I have this code that reads and displays the video but it opens in a separate window, how do I submit it to the html page in the django project? import cv2 import numpy as np cap = cv2.VideoCapture('D:\\trais\mitan_choreg_img\\movie\\investigate_1.mp4') currentFrame = 0 while(True): ret, frame = cap.read() frame = cv2.flip(frame, 1) cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break currentFrame += 1 cap.release() cv2.destroyAllWindows() I'm new to django and would love to receive any piece of code that will help. Thanks in advance! -
(Django) 'CommentView' object has no attribute 'body'
I have been trying to emulate comment functionality with a decorator. import json import jwt from django.views import View from django.http import JsonResponse from functools import wraps from django.db.models import Q from .models import Comment from account.models import Account class CommentView(View): def login_required(func): @wraps(func) def wrapper(request, *args, **kwargs): # import pdb; pdb.set_trace() given_token = json.loads(request.body)['access_token'] decoded_token = jwt.decode(given_token,None,None) try: if Account.objects.filter(username=decoded_token).exists(): return func(request, *args, **kwargs) return JsonResponse({"message": "username does not exist"}) except KeyError: return JsonResponse({"message": "INVALID_KEYS"}, status=403) return wrapper @login_required def post(self, request): print("request ", json.loads(request.body)) data = json.loads(request.body) Comment.objects.create( username = jwt.decode(json.loads(request.body)['access_token']), content = data['content'], ) return JsonResponse({"message":"Comment Created!"}, status=200) def get(self, request): return JsonResponse({'comment':list(Comment.objects.values())}, status=200) And I used the program called Httpie to give JSON POST request like so: http -v http://127.0.0.1:8000/comment access_token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImJlY2sifQ.2unop67pLHOshcGs385GwOvaZZW_J--TRNXyHI3gKNU" content="hello" There is no problem with the token since this is the exact copy of the token give during the SignInView(which is in another app). Below is the models.py file in the 'comment' app. from django.db import models from account.models import Account class Comment(models.Model): username = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() created_time= models.DateTimeField(auto_now_add = True) updated_time= models.DateTimeField(auto_now = True) class Meta: db_table = 'comments' def __str__(self): return self.username + ": " + self.content However, when … -
logout in Django using Auth-token
I am trying to logout using Auth-token My view: def logout(request): try: auth_token = request.META['HTTP_AUTH_TOKEN'] invalidate_token = User_Detail.objects.filter(auth_token=auth_token) invalidate_token.delete() return JsonResponse({'detail': "Logged out"}, status=status.HTTP_202_ACCEPTED) except Exception as e: return JsonResponse({"error": ["Token does not exist!"]}, status=status.HTTP_400_BAD_REQUEST) I am getting {'detail': "Logged out"} but I can still see auth_token in my database. I want my auth_token to be null once logged out. -
Django: Change object result in deleting foreign object? [closed]
Currently, I have this problem where when I changed an object in a table (primary table), the foreign object gets deleted. For example: # primary table (User) #foreign table (Subject) ====================== ================================ id | name | age id | name | user_id ====================== ================================ U0 | James | 20 C1 | maths | U0 U1 | Alex | 30 C2 | science | U1 C3 | english | U0 C4 | history | U1 # AFTER CHANGE An OBJECT/ROW IN PRIMARY TABLE # primary table (User) #foreign table (Subject) : object associated with user U1 get deleted ====================== ================================ id | name | age id | name | user_id ====================== ================================ U0 | James | 20 C1 | maths | U0 U1 | Alex | 35 <-- change C3 | english | U0 Code (models.py): from django.db import models class User(models.Model): id = models.CharField(max_length = 100, unique = True) name = models.CharField(max_length = 100) age = models.IntegerField() class Subject(models.Model): id = models.CharField(max_length = 100, unique = True) name = models.CharField(max_length = 100) user = models.ForeignKey(User, on_delete = models.CASCADE) #on_delete = cascade here Is this associated with the on_delete = cascade which explained here the referenced object is deleted, also delete … -
Can i get mysql sum() over in django queryset?
[my django query] queryset = Sale.objects.all().select_related( ).values( ).annotate( dept_nm=F('Department__dept_nm'), dept_cd=F('Department__dept_cd'), sal_year=ExtractYear('sal_dt'), sal_month=ExtractMonth('sal_dt'), sal_famt=F('sal_famt'), ).values( 'sal_year', 'dept_cd', 'dept_nm' ).annotate( Jan=Coalesce(Sum(Case(When(sal_month=1, then='sal_famt'),)), 0), Feb=Coalesce(Sum(Case(When(sal_month=2, then='sal_famt'),)), 0), Mar=Coalesce(Sum(Case(When(sal_month=3, then='sal_famt'),)), 0), Apl=Coalesce(Sum(Case(When(sal_month=4, then='sal_famt'),)), 0), May=Coalesce(Sum(Case(When(sal_month=5, then='sal_famt'),)), 0), Jun=Coalesce(Sum(Case(When(sal_month=6, then='sal_famt'),)), 0), Jul=Coalesce(Sum(Case(When(sal_month=7, then='sal_famt'),)), 0), Aug=Coalesce(Sum(Case(When(sal_month=8, then='sal_famt'),)), 0), Sep=Coalesce(Sum(Case(When(sal_month=9, then='sal_famt'),)), 0), Oct=Coalesce(Sum(Case(When(sal_month=10, then='sal_famt'),)), 0), Nov=Coalesce(Sum(Case(When(sal_month=11, then='sal_famt'),)), 0), Dec=Coalesce(Sum(Case(When(sal_month=12, then='sal_famt'),)), 0), Tot=Coalesce(Sum('sal_famt'), 0), ).filter(sal_year=year).order_by('dept_cd') [ this queryset result ] SELECT DEPT.dept_cd, DEPT.dept_nm, YEAR(sal_dt) as sal_year, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '1' THEN SALE.sal_famt END), 0) JAN, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '2' THEN SALE.sal_famt END), 0) FEB, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '3' THEN SALE.sal_famt END), 0) MAR, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '4' THEN SALE.sal_famt END), 0) APL, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '5' THEN SALE.sal_famt END), 0) MAY, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '6' THEN SALE.sal_famt END), 0) JUN, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '7' THEN SALE.sal_famt END), 0) JUL, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '8' THEN SALE.sal_famt END), 0) AUG, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '9' THEN SALE.sal_famt END), 0) SEP, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '10' THEN SALE.sal_famt END), 0) OCT, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '11' THEN SALE.sal_famt END), 0) NOV, ROUND(SUM(CASE WHEN MONTH(SALE.SAL_DT) = '12' THEN SALE.sal_famt END), 0) DEM, ROUND(SUM(SALE.sal_famt), 0) TOT, SUM(SALE.sal_famt) * 100 / SUM(SUM(SALE.sal_famt)) OVER() as PER FROM … -
Grouping Data using ORM
I have a table like this A B C 1 2 a 4 5 b 1 2 c 4 5 d With only the help of Django ORM, how to get the data in the following format: [1, 2, a, c], [4, 5, b, d] -
Getting the except django.core.exceptions.ImproperlyConfigured while querying DB
I am trying to fetch a few rows from the DB using the following code in my views.py: from django.http import HttpResponse from django.shortcuts import render from fusioncharts.models import QRC_DB def display_data(request,component): query_results = QRC_DB.objects.get(component_name__contains=component) return HttpResponse("You're looking at the component %s." % component) For the above, I am getting the following exception: django.core.exceptions.ImproperlyConfigured: The included URLconf 'Piechart_Excel.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. However whenever I am removing/commenting out the below line, the above exception disappears: query_results = QRC_DB.objects.get(component_name__contains=component) The 2 urls files are as follows: urls.py under the app directory from django.urls import path from fusioncharts import views urlpatterns = [ path('push-data/', views.push_data, name='push-data'), path('home/', views.home, name='home'), path('display_data/<str:component>', views.display_data, name='display_data'), ] and urls.py under the mail project directory from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('fusioncharts.urls')) ] Can anyone say what's going wrong? How come just one line of code which queries the DB is causing the above exception? -
Stream-framework requires django?
I am learning stream-framework. I followed the tutorial and built a basic feed like below from stream_framework.feeds.redis import RedisFeed class PinFeed(RedisFeed): key_format = 'feed:normal:%(user_id)s' class UserPinFeed(PinFeed): key_format = 'feed:user:%(user_id)s' feed = UserPinFeed(13) I got the below Error `Traceback (most recent call last): File "D:\CommonFiles\Python37\lib\site-packages\stream_framework\settings.py", line 26, in import_global_module objects = getattr(module, '__all__', dir(module)) File "D:\CommonFiles\Python37\lib\site-packages\django\utils\functional.py", line 224, in inner self._setup() File "D:\CommonFiles\Python37\lib\site-packages\django\conf\__init__.py", line 61, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\X\Desktop\sd.py", line 1, in <module> from stream_framework.feeds.redis import RedisFeed File "D:\CommonFiles\Python37\lib\site-packages\stream_framework\feeds\redis.py", line 1, in <module> from stream_framework.feeds.base import BaseFeed File "D:\CommonFiles\Python37\lib\site-packages\stream_framework\feeds\base.py", line 7, in <module> from stream_framework.storage.base import BaseActivityStorage, BaseTimelineStorage File "D:\CommonFiles\Python37\lib\site-packages\stream_framework\storage\base.py", line 10, in <module> class BaseStorage(object): File "D:\CommonFiles\Python37\lib\site-packages\stream_framework\storage\base.py", line 36, in BaseStorage metrics = get_metrics_instance() File "D:\CommonFiles\Python37\lib\site-packages\stream_framework\utils\__init__.py", line 146, in get_metrics_instance from stream_framework import settings File "D:\CommonFiles\Python37\lib\site-packages\stream_framework\settings.py", line 45, in <module> import_global_module(settings, locals(), globals()) File "D:\CommonFiles\Python37\lib\site-packages\stream_framework\settings.py", line 31, in import_global_module except exceptions as e: TypeError: catching classes that do not inherit from BaseException is not allowed` How do I resolve this error? … -
Django filtering with list and specific data
I'm sorry for the weird title. I don't know how to explain my problem in a short sentence. I'm trying to filter my model with a list but sometimes query returns multiple rows. For example: all_pos [1,2,3] query = MyModel.objects.filter(pos__in=all_pos) The query above returns a list of rows from the database but second item in the list returns two rows with B and C in the second column. 1, A, word 2, B, word 2, C, word 3, A, word But I only want the row with B. How can I filter this further so I can achieve the result below. 1, A, word 2, B, word 3, A, word -
Django PayPal subscription cancel and Webhooks
I'm using PayPal in my Django app, and I was wondering is there a way to cancel users subscription without going to PayPal dashboard? I couldn't find any docs regarding this section(cancelation), and Webhooks. -
Django-Filter Package: How To Filter Objects To Create Stats And Not Lists
I'm using Django-Filter package which is working well for the one example they have in their documentation. However, I am not trying to generate a list of objects rather filter the calculations I have done on the object fields. Example template: https://django-filter.readthedocs.io/en/stable/guide/usage.html#the-template {% for obj in filter.qs %} {{ obj.name }} - ${{ obj.price }}<br /> {% endfor %} The problem here is that a list is created.. I'm looking for my trade "stats" to be updated based on the new filter selections. I believe I need to set up my views differently and possibly call the template objects in another way as well but not totally sure. filters.py class StatsFilter(django_filters.FilterSet): class Meta: model = Trade fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] views.py class StatsView(LoginRequiredMixin, FilterView): model = Trade template_name = 'dashboard/stats.html' filterset_class = StatsFilter def get_form(self, *args, **kwargs): form = StatsFilter() user = self.request.user form.fields['associated_portfolios'].queryset = Portfolio.objects.filter(user=user) return form def get_context_data(self, *args, **kwargs): trade = Trade.objects.filter(user=self.request.user, status='cl').order_by('created') all_trades = Trade.objects.filter(user=self.request.user, status='cl').count() context = super(StatsView, self).get_context_data(*args, **kwargs) data = [t.profit_loss_value_fees for t in trade] context['all_trades'] = all_trades context['gross_profit'] = sum([t.profit_loss_value for t in trade]) context['net_profit'] = sum([t.profit_loss_value_fees for t in trade]) ... return context stats.html <form method="get" class="row"> … -
django using remote application database
I am a newbie to django. I have a remote database that is migrated and used by Laravel application. I am trying to connect to this database and insert some records into one of the tables from django application. def get_connection(self): """ Connect to aurora and return connection object """ import mysql.connector from sqlalchemy import create_engine engine_str = 'mysql+mysqlconnector://{user}:{passwd}@{host}:{port}/{schema}'.format( user=self.user_name, passwd=self.password, host=self.host, port=self.port, schema=self.db_name ) engine = create_engine(engine_str, echo=False) return engine And then perform db transactions such as insert_query below: def insert_query(self, query, *args, **kwargs): """ Insert and return id """ result = self.execute_query(query, *args, **kwargs) if result: return result.lastrowid else: return None So my question being: do we need to create models and migrate for this separate database tables too? Is it a bad practice to execute raw queries? I also checked for multiple database support for django and there are other Database Routers and stuffs. Multiple databases. Any help is appreciated. -
SPLIT a sting in the following manner: (in PYTHON)
How can I split the string 07:05:45PM into this manner ['07:05:45','PM'] in python -
how to add additional model to the function and filter DB based on new value
Therese are my django models (taken from DB that is static): class Profile(models.Model): player_name = models.CharField(max_length=150) player_surname=models.CharField(max_length=200) class Meta: db_table='profiles' class Results_2019(models.Model): player_name = models.CharField(max_length=150) first_score=models.DecimalField(decimal_places=2,max_digits=1000) second_score=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='results_2019' class Results_2018(models.Model): player_name = models.CharField(max_length=150) first_score=models.DecimalField(decimal_places=2,max_digits=1000) second_score=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='results_2018' class Additional(models.Model): player_name = models.CharField(max_length=150) weight=models.DecimalField(decimal_places=2,max_digits=1000) height=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='results_2018' I want to filter from DB players based on math calculations and meeting certain criteria as i shown below: def abc_func() ABC = [] for abcrest in [Results_2019,Results_2018]: abc_list = abcrest.objects.all() for result in abc_list: score1 = result.first_score score2 = result.second_score growth = (score2 - score1) / score1 if growth > 0.2 : ABC.append(result.ticker) DoubleNames = list(set([x for x in ABC if ABC.count(x) == 2])) ABCNames = [] for name in DoubleNames: finalnames = Profile.objects.filter(player_name=name)[0] ABCNames.append([finalnames.player_name, finalnames.player_surname]) return ABCNames The limitation in this function is that i can't embed class Additional it states that Results_2019 has no column weight. I wanted to filter based on mass= score1/weight but it does not work. Is there any way to embed it in function? P.S : Foreignkey does not work in my models. -
Django Rest Framework AttributeError: 'str' object has no attribute 'get_default_basename'
This is my first time using viewsets and routers. When I run the server, it shows the that error. Here is the view (inside a file called api.py): class LeadViewset(viewsets.ModelViewSet): queryset = Lead.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = LeadSerializer serializer: class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__' urls: from rest_framework import routers from .api import LeadViewset router = routers.DefaultRouter router.register('api/leads', LeadViewset, 'leads') What am I doing wrong? urlpatterns = router.urls -
Qunit Tests Always Failing
Ive recently began trying to do qunit testing but am having a lot of difficulty. I have written a test that should first check that <div id='optional_fields'>'s class is set to none on page load (as it should be by the first javascript code), then that its set to block on the pressing of the checkbox button (the second piece of javascript code). My problem is that the first test always fails, and the 2nd test passes not because $('#id_taken_test_before').click(); changes the div to block, but because its always displayed as block and the button press does nothing. Also, if I move the closing <div id="qunit-fixture"> div so its not surrounding the test code (<div id="qunit-fixture"></div>), the $('#id_taken_test_before').click(); works correctly. I dont know why it doesnt work if the entire code is surrounded by the <div id="qunit-fixture"> tag. tests.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>QUnit Example</title> <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.10.0.css"> <script src="https://code.jquery.com/jquery-3.5.0.js" integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous"></script> </head> <body> <div id="qunit"></div> <div id="qunit-fixture"> <!-- page content --> <div id="div_id_taken_test_before" class="custom-control custom-checkbox"> <input type="checkbox" name="taken_test_before" class="checkboxinput custom-control-input" id="id_taken_test_before" checked=""> <label for="id_taken_test_before" class="custom-control-label"> Have you taken the test before </label> </div> <!-- div_id_taken_test_before --> <div id='optional_fields'></div> <!-- /page content --> </div><!-- /qunit-fixture … -
Unable to get current user data between two dates in Django
current_user = request.user if LeadTarget.objects.filter(user_id__username=current_user): start_date = LeadTarget.objects.filter(user_id__username=current_user).values('start_date','deadline') startdate = [] deadline = [] for i in start_date: startdate.append(i['start_date']) deadline.append(i['deadline']) print("-------") print(startdate) start = (startdate[0]) print("start",start) print(type(start)) print(deadline) user_data = LeadTarget.objects.filter(created_at__range=(startdate, deadline)) print("data =======: ", user_data) if user_data: for i in user_data: print("data : ", i) else: print("empty") -
What does cl do in Django admin template
Am trying to use custom view in ModelAdmin and redirect to custom change_list html The problem am getting reverse for app_list with argument app_label not found when I removed cl.opts work for current model I have passed opts and app_label to context Any help please -
Reverse for 'display_data' not found. 'display_data' is not a valid view function or pattern name
I am getting the below error when I am trying to load the home page: Reverse for 'display_data' not found. 'display_data' is not a valid view function or pattern name My views.py file is as follows: def home(request): #query_results = QRC_DB.objects.all() return render(request, 'display_data.html') def display_data(request,component): #query_results = QRC_DB.objects.all() return HttpResponse("You're looking at the component %s." % component) My urls.py file under the app is as follows: from django.urls import path from fusioncharts import views urlpatterns = [ path('home/', views.home, name=''), ] The urls.py file under the project is as follows: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('fusioncharts.urls')) ] And my html file (display_data) code is as follows : {% block content %} <h3>Display the test results</h3> <div id="container" style="width: 75%;"> <canvas id="display-data"></canvas> <li><a href="{% url 'display_data' 'SQL' %}">SQL</a></li> </div> {% endblock %} Can anyone please help me to find out the mistake ? Thanks. -
How to filter in django when two models is join on the views.py and want to filter, sort_by and order_by only on the table?
Models.py Views.py Please note I have written "query" to join two tables, cross-check once again models.py query.html Here in this HTML, I have a form which is the GET method, If I search for something related to table data so my result should display on the same page Please provide a solution -
Django Update view function deletes one image from formset when updating texts
I have this post with a form for title and tags and a modelformset for images with postimages model which has a foreign key relation to Post Model. I am able to update images and edit posts, but the problem is whenever I try to edit the title, one of the images gets deleted and it creates a duplicate of another image in the formset. Please have a look the views. I am not able to figure it out. views def update_post(request, slug): context = {} post = get_object_or_404(Post, slug=slug) ImageFormSet = modelformset_factory(PostImage, fields=('image',), extra=5, max_num=5) tags = Tag.objects.filter(post=post) if post.user != request.user: return redirect('posts:myhome') if request.POST: form = UpdatePostForm(request.POST or None, instance=post) formset = ImageFormSet(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): obj = form.save(commit=False) obj.save() post = obj data = PostImage.objects.filter(post=post) for index, f in enumerate(formset): if f.cleaned_data: if f.cleaned_data['id'] is None: photo = PostImage(post=post, image=f.cleaned_data.get('image')) photo.save() else: photo = PostImage(post=post, image=f.cleaned_data.get('image')) d = PostImage.objects.get(id=data[index].id) d.image = photo.image d.save() context['success_message'] = "Updated" return redirect('posts:myhome') form = UpdatePostForm( initial = { 'title': post.title, 'tags':post.tags, 'visibility':post.visibility, } ) formset = ImageFormSet(queryset=PostImage.objects.filter(post=post)) context['form'] = form context['formset'] = formset return render(request, 'posts/update_post.html', context) Thanks in advance! -
i am able to build my django web app on heroku but while launching its showing these error(error log shown below)
2020-05-20T05:56:19.466995+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-05-20T05:56:19.466995+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-05-20T05:56:19.466996+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-05-20T05:56:19.466996+00:00 app[web.1]: self.callable = self.load() 2020-05-20T05:56:19.466997+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-05-20T05:56:19.466997+00:00 app[web.1]: return self.load_wsgiapp() 2020-05-20T05:56:19.466997+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-05-20T05:56:19.466998+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-05-20T05:56:19.466998+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2020-05-20T05:56:19.466999+00:00 app[web.1]: mod = importlib.import_module(module) 2020-05-20T05:56:19.466999+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module 2020-05-20T05:56:19.467000+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-05-20T05:56:19.467000+00:00 app[web.1]: File "", line 994, in _gcd_import 2020-05-20T05:56:19.467000+00:00 app[web.1]: File "", line 971, in _find_and_load 2020-05-20T05:56:19.467000+00:00 app[web.1]: File "", line 941, in _find_and_load_unlocked 2020-05-20T05:56:19.467001+00:00 app[web.1]: File "", line 219, in _call_with_frames_removed 2020-05-20T05:56:19.467001+00:00 app[web.1]: File "", line 994, in _gcd_import 2020-05-20T05:56:19.467001+00:00 app[web.1]: File "", line 971, in _find_and_load 2020-05-20T05:56:19.467001+00:00 app[web.1]: File "", line 953, in _find_and_load_unlocked 2020-05-20T05:56:19.467006+00:00 app[web.1]: ModuleNotFoundError: No module named 'mywebsite' 2020-05-20T05:56:19.467089+00:00 app[web.1]: [2020-05-20 05:56:19 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-05-20T05:56:19.475859+00:00 app[web.1]: [2020-05-20 05:56:19 +0000] [11] [INFO] Booting worker with pid: 11 2020-05-20T05:56:19.480935+00:00 app[web.1]: [2020-05-20 05:56:19 +0000] [11] [ERROR] Exception in worker process 2020-05-20T05:56:19.480936+00:00 app[web.1]: Traceback (most recent call last): 2020-05-20T05:56:19.480937+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-05-20T05:56:19.480937+00:00 app[web.1]: worker.init_process() 2020-05-20T05:56:19.480937+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process … -
How can I correctly run my for loop in html?
So, I have a for loop that loops through my users profiles and randomly displays a number of them. I am attempting to create 12 of these profiles to be listed and to be listed in this sort of pattern I have with my html. However, I am running into a problem where it's running my html pattern 6 different times... which is not what I want. I want 6 different profiles to be used and ran only once. I understand why it's doing it, because it's a for loop. My question is how can I make this work through html? If this were python, I'd add a counter. Also, if I only have 1 of these cards, the profiles don't display how I want them too, they display in 12 different rows. {% for profile in random_profiles %} <div class="row"> <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img src="{{ profile.photo.url }}" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">Thumbnail</text></svg> <div class="card-body"> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn …