Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Website Embedded Video Transcript Based On Closed Caption Files YouTube & Vimeo
For SEO purposes, I want to recreate something like what Lynda.com and YouTube uses for their video transcripts where it shows the entire video speaker's dialogue as highlighted text moving along throughout the video based on the timestamp as well as what the video's speaker is saying. I want to be able to do this with both embedded Vimeo and YouTube videos. How would I recreate this showing the entire transcript text on the webpage for SEO purposes with this functionality or use the Vimeo and YouTube APIs to do it? Or maybe there is another way? I assume you would need to store these caption file types on the server and then visualize them with them via HTML/JavaScript somehow (I would prefer using my main server language Django besides JavaScript). Maybe store the entire transcript in the database? Or maybe uploading these file types to Vimeo or YouTube and then extracting them with the API would work? How can this be accomplished? Examples: Click the transcript tab and play the video - https://www.lynda.com/Raspberry-Pi-tutorials/Why-Raspberry-Pi/5007872/2810621-4.html On any YouTube video, click ... and then click "Open Transcript" http://www.erlendthune.com/yt/ytexample.html -
Find out how dynamic text is placed in a website
Specifically referencing a page on a site like this: lolnames.gg. All of the information affiliated to the available name is, I'm assuming, pulled from an API - however I would like to know how it is specifically placed in that div on the page. I could not find any event listeners related to pushing that text there. -
django not logging DB connection issues with 502 Bad Gateway
In trying to diagnose a 502 Bad Gateway error, I quickly determined it was a database connection issue (since I had just updated the host entry in settings.py) however none of the log files indicated anything that would point towards a DB connection issue... tail /var/log/nginx/error.log 2019/12/25 03:53:13 [error] 818#818: *11 upstream prematurely closed connection while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: example.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "example.com" 2019/12/25 03:56:54 [error] 818#818: *14 upstream prematurely closed connection while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: example.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "example.com" 2019/12/25 03:58:08 [error] 818#818: *16 upstream prematurely closed connection while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: example.com, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "example.com" tail /var/www/example.com/example/gunicorn.error.log (where the gunicorn error-logfile writes to) [2019-12-25 03:56:56 +0000] [2447] [INFO] Starting gunicorn 20.0.4 [2019-12-25 03:56:56 +0000] [2447] [INFO] Listening at: unix:/run/gunicorn.sock (2447) [2019-12-25 03:56:56 +0000] [2447] [INFO] Using worker: sync [2019-12-25 03:56:56 +0000] [2474] [INFO] Booting worker with pid: 2474 [2019-12-25 03:56:56 +0000] [2475] [INFO] Booting worker with pid: 2475 [2019-12-25 03:56:56 +0000] [2477] [INFO] Booting worker with pid: 2477 [2019-12-25 03:56:56 +0000] [2478] [INFO] Booting worker with pid: 2478 … -
AttributeError: 'tuple' object has no attribute 'status_code'
I'm a beginner in python. I'm not able to understand what the problem is? the runtime process for the instance running on port 43421 has unexpectedly quit ERROR 2019-12-24 17:29:10,258 base.py:209] Internal Server Error: /input/ Traceback (most recent call last): File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/core/handlers/base.py", line 178, in get_response response = middleware_method(request, response) File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/middleware/common.py", line 94, in process_response if response.status_code == 404: AttributeError: 'tuple' object has no attribute 'status_code' -
django Many to Many with three table relationships together
I want to create a seralizer with 3 models and many to many relationship: -MODEL---------------------------------------------------------------------------- class Permission(models.Model): permission_name = models.CharField(max_length=20) class Feature(models.Model): feature_name = models.CharField(max_length=40) class Role(models.Model): name = models.CharField(max_length=40) permissions = models.ManyToManyField(Permission, through='RolePermission') features = models.ManyToManyField(Feature, through='RolePermission') class RolePermission(models.Model): role = models.ForeignKey(Role, on_delete=models.CASCADE) permission = models.ForeignKey(Permission, on_delete=models.CASCADE) feature = models.ForeignKey(Feature, on_delete=models.CASCADE) -DATA---------------------------------------------------------------------------- PERMISSION: 1 - add 2 - edit 3 - remove 4 - view FEATURE: 1 - user 2 - device ROLE: 1 - ROLE1 2 - ROLE2 -data i want to response from view ------------------------------------------------------- [ { "id": 1, "name": "ROLE1", "features": [ { "id": 1, "name": "user", "permissions": [ { "id": 1, "name": "add" }, { "id": 2, "name": "edit" }, { "id": 3, "name": "remove" }, { "id": 4, "name": "view" } ] }, { "id": 2, "name": "device", "permissions": [ { "id": 4, "name": "view" } ] } ] }, { "id": 2, "name": "ROLE2", "features": [ { "id": 1, "name": "user", "permissions": [ { "id": 4, "name": "view" } ] }, { "id": 2, "name": "device", "permissions": [ { "id": 4, "name": "view" } ] } ] } ] -but i cant write the serializer correct, can you help me? --------------------------------- -
Virtual env is not activating
u0_a233@localhost ~/django> . env/bin/activate env/bin/activate (line 82): Missing end to balance this if statement if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ] ; then ^ from sourcing file env/bin/activate called on line 359 of file /data/data/com.termux/files/usr/share/fish/config.fish in function '.' called on standard input source: Error while reading file 'env/bin/activate' u0_a233@localhost ~/django> -
Saving data to Mongo Database - too large cpu
I'm trying to save a really big .csv file from upload form in Django into MongoDB, it works, but it takes too much time to process, so I decided to use Multiprocessing, this approach shorted the time a little bit, but CPU cores came to 100%, so I would like to make my code a little bit lower-computation expensive. Here is my code views.py def save_to_db(line): # I think this part cost the most time column = line.split(",") kokyaku.objects.create(顧客CD = int(column[0]), 顧客補助CD = int(column[1]), 顧客名称s=str(column[2]), 顧客名称=str(column[3]), 顧客名称カナ=str(column[4]), 法人名称=str(column[5]), 代表者名称=str(column[6]),住所=str(column[7]), 電話番号=str(int(column[8])),地区名称=str(column[9]), データマッチ用電話番号=int(column[10]),契約状態=str(column[11]) ) def upload(request): data = {} if "GET" == request.method: return render(request, "main/upload.html", data) # if not GET, then proceed csv_file = request.FILES["csv_file"] file_type = request.POST.get("type", "") if not csv_file.name.endswith('.csv'): messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("upload")) file_data = csv_file.read().decode("utf-8") lines = file_data.split("\n") if file_type == "val3": with concurrent.futures.ProcessPoolExecutor() as executor: executor.map(save_to_db, lines) return HttpResponseRedirect(reverse("upload")) btw. here is my functions from models.py If it helps too class kokyaku(models.Model): 顧客CD = models.IntegerField(blank=True) 顧客補助CD = models.IntegerField(blank=True) 顧客名称s = models.TextField(blank=True) 顧客名称 = models.TextField(blank=True) 顧客名称カナ = models.TextField(blank=True) 法人名称 = models.CharField(max_length=15, blank=True) 代表者名称 = models.CharField(max_length=15, blank=True) 住所 = models.TextField(blank=True) 地区名称 = models.TextField(blank=True) 電話番号 = models.IntegerField(blank=True) データマッチ用電話番号 = models.IntegerField(blank=True) 契約状態 = models.CharField(max_length=2, blank=True) def __str__(self): … -
AngularJS: ng-repeat not show items
I tried the code of AngularJS as follows: var app = angular.module('MyApp', []); app.controller('new_controller', function($scope) { $scope.people= [{ name: "GeekAgashi", Age: 12, attended: 1 }, { name: "GeekSatoshi", Age: 16, attended: 0 }, { name: "GeekNakumato", Age: 14, attended: 1 }]; }); In HTML file the code: <div class="sidebar-pane" ng-app="MyApp" id="flight_info" ng-controller="new_controller"> <table> <tr> <td>Name</td> <td>Age</td> </tr> <tr ng-repeat="p in people"> <td>{{p.name}}</td> <td>{{p.Age}}</td> </tr> </table> </div> On the webpage, I can only get the table frame which I think means that the data is successfully passed. But I cannot get the table items: <table> <tbody> <tr> <td>Name</td> <td>Age</td> </tr> <!-- ngRepeat: p in people --> <tr ng-repeat="p in people" class="ng-scope"> <td></td> <td></td> </tr> <!-- end ngRepeat: p in people --> <tr ng-repeat="p in people" class="ng-scope"> <td></td> <td></td> </tr> <!-- end ngRepeat: p in people --> <tr ng-repeat="p in people" class="ng-scope"> <td></td> <td></td> </tr> <!-- end ngRepeat: p in people --> </tbody> </table> I am just wondering if it is a bug or there is something wrong with my code, or the browser (chrome v79) does not support it. Appendix: I write the backend in Django and I found that if I directly run the plain HTML, the table is visible. … -
How can I send userid from form request to pre_ or post_delete signal?
Another question form novice. I have some form: class SomeForm(forms.ModelForm): ... def save(self, commit=False): instance = SomeModel(field='value1') instance.userid = self.request.user.id instance.delete() instance = SomeModel(field='value2') instance.userid = self.request.user.id instance.save() In post_save signal: @receiver(post_save,sender=SomeModel) def pre_save_model(sender,instance,**kwargs): print(instance.userid) it works fine. But in post_delete: @receiver(post_delete,sender=SomeModel) def post_delete_model(sender,instance,**kwargs): print(instance.userid) it says: AttributeError: 'SomeModel' object has no attribute 'userid' I guess, than I can't understand something important. But what? -
A problem handling Django stripe payment exceptions
I have an exception handling problem for Django stripe payment, when I do input stripe, an exception error occurs, so it cannot be saved to the database settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # django crispy 'crispy_forms', # django countries 'django_countries', # init core 'core', # stripe 'stripe', ] views.py from django.conf import settings import stripe stripe.api_key = settings.STRIPE_SECRET_KEYS class PaymentView(View): def get(self, *args, **kwargs): return render(self.request, "payment.html") def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: # Use Stripe's library to make requests... charge = stripe.Charge.create( amount=amount, # sen currency="usd", source=token ) payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() order.ordered = True order.payment = payment order.save() message.success("Your order successfully") return redirect("/") except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught body = json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") return redirect("/") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.error(self.request, "Rate limit error") return redirect("/") except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.error(self.request, "Invalid parameter") return redirect("/") except stripe.error.AuthenticationError as e: # Authentication with Stripe's API … -
Admin Page in Django won't load
I'm new with Django Framework, I've been following few tutorials and trying to create a website using Django 3.0.1 and Pythong 3.8 when I crate my super user using: python manage.py createsuperuser I'm able to setup it up, but when I try to access: 'http://127.0.0.1:8000/admin/' Server can't be accessed(image) This only happens when attempting to access after entering my username and passwords, as soon as I enter my credentials, the server stops. This is what my urls.py under the project looks like: from django.contrib import admin from django.urls import path, include admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), path('tokens/', include('tokens.urls')) ] Does someone have an Idea of what the problem is? Thank you in Advance. -
Django's ArrayField; how to set a non-empty default?
#models.py from django.db import models from django.contrib.postgres.fields import ArrayField class Group(models.Model): members = ArrayField(models.IntegerField(), blank=True, default=[0]) Is this safe? Documentation warns against using default=[] for an empty default. It suggests default=list instead. https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#arrayfield -
Turning a Django project into a cloud SaaS project
I have a Django 2.2 project. I am installing this project to several companies. But for every company i create a server install mysql, django, uwsgi, nginx... So all belongs to that company. I want to serve this django project system as a cloud service. So every company will be member. When they get member and pay, they will start to use their system on cloud. But companies will be isolated from each other. I am not sure how to do that. Should i write whole project again ? Or should i automize all installation prosesses with scripts and when they register and pay, scripts will make installations and will start to serv its project on nginx. Should i use different databases for every project... Lots of questions and couldn't figure out right design. -
Django - how to mailmerge docx document and download it without saving on the disk?
I am building a Django app, which store docx templates with merging fields. I've got a view that choose a template and provide fields' document with values. Then it adds the document to the django's response. I didn't find any solution to not save the document on the disk and delete it almoste immediatly. If you have a better way to do all this, i would be very interested ! publipostage/models.py: from django.db import models from django.core.files.storage import FileSystemStorage from django.conf import settings from mailmerge import MailMerge from datetime import datetime fs = FileSystemStorage(location=settings.PUBLIPOSTAGE_ROOT) class DocTemplate(models.Model): document = models.FileField(storage=fs) name = models.CharField(max_length=50) description = models.TextField() uploaded_date = models.DateTimeField(auto_now_add=True) @property def abs_path(self): return os.path.join(settings.PUBLIPOSTAGE_ROOT, self.document.name) def mailmerge(self, data): # build temporary file name timestamp = datetime.now().strftime("%Y%m%d_%h%i%s") temp_filename = f'temp_{self.name}_{timestamp}.docx' temp_filename = os.path.join(settings.PUBLIPOSTAGE_ROOT, temp_filename) # open template with merging fields with MailMerge(self.abs_path) as document: fields = document.get_merge_fields() # check if all merge fields have been provided in data param missing = [_ for _ in fields if _ not in data] if len(missing) > 0: msg = ', '.join(missing_fields) raise ValueError(f'Missing {len(missing)} merge fields: {msg}') # on transfrome toutes les valeurs en str for key in data: data[key] = str(data[key]) document.merge(**data) # … -
How can i send files who have spaces in their name in my django app
I will like to be able to send files in email in this django project. But files with spacies in their names seem not to go through, also when selecting the files to be sent i am able to select multiple files but only one file will go through the others are not recieved in mail. Views.py import os from django.shortcuts import render, redirect from django.core.files.storage import FileSystemStorage from .forms import EmailForm from django.core.mail import send_mail from django.conf import settings from datetime import datetime from django.core.mail import EmailMessage def email1(request): if request.method == "POST": form = EmailForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.published_date = datetime.now() post.save() email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') document = request.FILES.get('document') email_from = settings.EMAIL_HOST_USER recipient_list = [email] email = EmailMessage(subject,message,email_from,recipient_list) base_dir = 'media/documents/' try: for i in document: email.attach_file('media/documents/'+str(document)) os.rename(document(document.replace(' ', '_'))) email.send() return render(request, 'sendmail/sendmail.html') except: pass else: form = EmailForm() return render(request, 'sendmail/sendmail.html', {'form': form}) forms.py from django import forms from django.forms import ClearableFileInput from .models import Mails class EmailForm(forms.ModelForm): email = forms.EmailField(max_length=200, widget=forms.TextInput(attrs={'class': "form-control", 'id': "clientemail"})) message = forms.CharField(widget=forms.Textarea(attrs={'class': "form-control"})) document = forms.FileField(widget = forms.ClearableFileInput(attrs={'multiple':True})) subject = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control"})) class Meta: model = Mails fields = ('email', 'subject', 'message', … -
is there a way to run my django project server as always reflect the changes?
I always run my local server with; python manage.py runserver 127.0.0.1:8000 But there is a problem, I have to refresh my browser every time that I made a change in my code. I want the server do the job of refreshing my browser automatically. Note: I am using Pycharm. -
Django URL in template with slug in it
I'm trying to link to a blog post but it has a slug in it, and i'm not sure how to pass it in. I've looked online but I didn't apparently understand the answers since I haven't found a solution yet. I'm trying to do like the following in my template href="{% url 'blog_detail' post.categories.5 slug=blender-task-name post.14 %}", but it gives me the following exception: Could not parse the remainder: '-task-name' from 'blender-task-name' This is how the object i'm trying to link to looks like URLS.py: urlpatterns = [ path("", views.blog_index, name="blog_index"), path("<category>/<slug>/<int:pk>/", views.blog_detail, name="blog_detail"), path('<category>/', views.blog_category, name='blog_category'), ] Models.py: class Category(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Post(models.Model): slug = models.SlugField(max_length = 250, null = True, blank = True) title = models.CharField(max_length = 250, default="Blog Post") body = models.TextField() created_on = models.DateTimeField(null=True) last_modified = models.DateTimeField(null=True) categories = models.ForeignKey('Category', related_name='posts', default="2", unique=False, on_delete=models.CASCADE) class Comment(models.Model): author = models.CharField(max_length=60) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE) -
Django App Failing while pushing to Pivotal Cloud Foundry
Brand new to Python and Django . Created first ever app in here. My Django Rest API is working good in local. I tried deploying to PCF. my manage.py looks like below #!/usr/bin/env python import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() and requirement.txt is Django django-toolbelt djangorestframework gunicorn and runtime.txt is python-x.x.x I created Manifest.yml too like applications: - name: MyPythonApp memory: 128MB disk_quota: 256MB random-route: true However i am getting error like below 2019-12-24T15:53:35.64-0500 [STG/0] ERR WARNING: You are using pip version 19.2.3, however version 19.3.1 is available. 2019-12-24T15:53:35.64-0500 [STG/0] ERR You should consider upgrading via the 'pip install --upgrade pip' command. 2019-12-24T15:53:36.46-0500 [STG/0] OUT Running python /tmp/app/manage.py collectstatic --noinput --traceback 2019-12-24T15:53:36.96-0500 [STG/0] ERR Traceback (most recent call last): 2019-12-24T15:53:36.97-0500 [STG/0] ERR File "/tmp/app/manage.py", line 21, in <module> 2019-12-24T15:53:36.97-0500 [STG/0] ERR main() 2019-12-24T15:53:36.97-0500 [STG/0] ERR File "/tmp/app/manage.py", line 17, in main -
Erro NoReverseMatch
Olá, Pessoal, não estou conseguindo entender o erro abaixo aonde está ocorrendo. O erro ocorre quando tento acessar a lista de informativos, se comentar a linha contex_object_name, ele renderiza o template sem a lista de informativos, quando coloco ocorre o erro. Reverse for 'info' with arguments '('',)' not found. 1 pattern(s) tried: ['informativo/(?P[-a-zA-Z0-9_]+)/$'] Seguem os arquivos Views: #encoding: utf-8 #Django Imports from django.shortcuts import render from django.views.generic import ListView, View, DetailView #Model Import's from .models import * def get(self, request, slug, *args, **kwargs): informativo = Informativo.objects.get(slug = slug) lista_info = Informativo.objects.filter(status = True) relacionados = post.tags.similar_objects() contexto = { 'informativo':informativo, 'lista_info':lista_info, 'relacionados':relacionados, } return render (request, 'informativo.html', contexto) class ListaInformativo(ListView): model = Informativo template_name = 'lista_informativo.html' context_object_name = 'lista_info' ordering = ['-data_criacao'] paginate_by = 5 class DetalheInformativo(DetailView): model = Informativo template_name = 'informativo.html' context_object_name = 'informativo' Urls: #encoding: utf-8 #Django Imports from django.urls import path #Views Import from .views import * urlpatterns = [ path('lista/', ListaInformativo.as_view(), name = 'lista'), path('<slug:slug>/',DetalheInformativo.as_view(), name = 'info'), path('tag/<tag>/', DetalheInformativo.as_view(), name = 'tag'), ] Agradeço desde já a ajuda. Abraço -
I've read the documentation but my STATIC folder is still not being served
My settings.py file has the static URL set: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' The staticfiles app is installed: INSTALLED_APPS = [ 'Journal', 'adminsortable2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] I've created a folder inside my app called static/journal: https://i.stack.imgur.com/T1eGw.png My template loads static and uses the URL as per documentation: {% load static %} <link rel='icon' href='{% static "journal/favicon.ico" %}' type='image/x-icon'> And yet when I browse to http://localhost/static/journal/favicon.ico I get an error 404!!! The rest of my app is accessible at http://localhost (runserver is on port 80 and localhost resolves to 127.0.0.1 via hosts file_ -
What is the way to build a backend
I want to build a backend that will return a feed from my database of content (each 'post' has title, image, content, likes, etc..). Also I need an CMS panel to give my writers a place to create the content that will get into the database. The backend should return a customize feed for each user based on the content he did not see yet (and not based on published time). I know there are many option to build backend for mobile apps like Parse, Firebase, Django etc.. (I also consider WordPress)... But I need very complex algorithm (return random posts that hasn't been read) so I did not find that Firebase and Parse are the solution (fix me if I wrong). I have knowledge of development in python, and I found the GetStream.io company that seems to do great thing and something I would need, but I did not find how to use its platform to access my database and not thier activity (I don't need it to be social). Basically my question is, how do you think I should build my backend? using what frameworks? how do I connect a CMS system and so on.. Step by Step … -
How do I dynamically load data from my django views to my django template with jquery without refreshing the page?
I'm trying to load data from my django views into my django templates without refreshing the page with jquery. I have a cart function in my views that's returning all the items in a users cart. I would like to display all the items on the click of a button in a django template with jQuery. I can't seem to figure out what I'm doing wrong. Here is my views: def cart(request): template = loader.get_template("main/cart.html") if request.user.is_authenticated: email = request.user.email usercartitems = request.user.cart_item_set.all() cartitems = [] store = "" totalprice = 0 numberofitemsincart = len(cartitems) for item in usercartitems: quantity = item.product_quantity store_id = item.store_id product_id = item.product_id storedetail = Store_detail.objects.get(pk = store_id) product = Product.objects.get(pk = product_id) item = {"quantity":quantity, "product":product} cartitems.extend([item]) store = storedetail numberofitemsincart = len(cartitems) product = Product.objects.get(pk = product_id) totalproductprice = product.price * int(quantity) totalprice += totalproductprice context={ 'store':store, 'email':email, 'cartitems':cartitems, 'numberofitemsincart':numberofitemsincart, 'totalprice':totalprice, } return HttpResponse(template.render(context,request)) elif request.user.is_authenticated is False: if request.session.get('cart'): allitems = request.session['cart'] cartitems = [] totalprice = 0 for item in allitems.values(): store_id = item['store_id'] quantity = item['quantity'] product_id = item['product_id'] product = Product.objects.get(pk = product_id) store = Store_detail.objects.get(pk = store_id) totalproductprice = product.price * int(quantity) totalprice += totalproductprice cartdict = {'store':store,'product':product,'quantity':quantity,} … -
python for statement with if inside it
Need help please. I'm trying to get this if statement within a for statement correct, but failing miserably at it. If an image isn't available, I badly need a fallback image to replace it. Thank you {% for post in posts|slice:":1" %} <div class="container"> {% if post.image.url %} <div class="flex-item"> <a href="{{ post.get_absolute_url }}"><img style="width:100%;" src="{{ post.image.url }}"</a> </div> {% else %} <div class="image-container1"> <img src="{% static 'images/fallback.png' %}" alt="" style="width: 100%;text-align: center;display: block;"> </div> {% endif %} {% endfor %} -
Django Forms UpdateView: How to alert user after successful update?
I'm using a django UpdateView and cripsy forms to handle my form processing. I'd like to show an alert or popup on the page after the model has successfully updated, i.e. after validation and save. If I use the onSubmit parameter to show an alert, this will just show after the submit button is pressed, but I only want it to show after the valid model has been updated. Is there an easy way to do this without re-writing a lot of the class methods? Thank you. -
Annotating a FilteredRelation on a ManyToManyField returns nothing
Models class User(AbstractUser): pass class Report(Model): user = ForeignKey ( "User", related_name="reports" ) shared_doctors = ManyToManyField ( "User", symmetrical = False, related_name="shared_reports" ) I have more fields on the models, but I have omitted them in the interest of shortening the problem. Query User.objects.annotate( shared_reports_user = FilteredRelation( 'shared_reports', condition = Q(shared_reports__user=user) ) ).annotate( shared_reports_user_count = Count('shared_reports_user') ) I have brought down the query to the base level which is giving unexpected results. user in the first annotate is an instance of User. The Query runs successfully, but the resulting QuerySet has no shared_reports_user key, though it has a shared_reports_user_count key, which has a value of 0. As far as I understood from the documentation, FilteredRelation takes a field present on the Model that it will filter on, and a named argument, condition, that takes a Q object as a condition to be applied to the existing field value. This leads me to believe that the first annotation should return a QuerySet annotated with a subset of shared_reports satisfying the condition specified in the Q object. I'm sure my database contains values satisfying the Q object (I have manually inspected the data), and even in case there is no output, I …