Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React/Django: how to get label of models.TextChoices in React
I have the following Model in Django: class Expense(models.Model): class ExpenseTypes(models.TextChoices): FOOD = 'FOOD', 'Food' HOUSE = 'HOUS', 'Home' SPORT = 'SPRT', 'Sport and exercices' TRANSPORT = 'MOVE', 'Transportation' EVERYDAY = 'EVER', 'Everyday Expenses' ENTERTAINMENT = 'ENTE', 'Entertainment' CLOTHING = 'CLOT', 'Clothes' INVESTMENTS = 'INVE', 'Investments' EDUCATION = 'EDUC', 'Education' SAVING = 'SAVE', 'Saving' HOLIDAYS = 'HOLI', 'Holidays' DEBT = 'DEBT', 'Debt' TAXES = 'TAXS', 'Taxes' user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=32) amount = models.DecimalField(max_digits=10, decimal_places=2) expense_type = models.CharField( max_length=4, choices=ExpenseTypes.choices, default=ExpenseTypes.FOOD, ) time = models.DateTimeField(default=timezone.now) with a simple serializer and view: class ExpenseSerializer(serializers.ModelSerializer): class Meta: model = Expense fields = ('id', 'user', 'title', 'amount', 'expense_type', 'time') class ExpenseViewSet(viewsets.ModelViewSet): queryset = Expense.objects.all() serializer_class = ExpenseSerializer authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated,) In React when I fetch the Data: const [expenses, setExpenses] = useState<Expense[]>([]); useEffect(() => { function formatExpense(expense: any): Expense { return { id: expense.id, title: expense.title, amount: expense.amount, user: expense.user, type: expense.expense_type, time: new Date(expense.time), }; } async function loadExpenses() { try { const response = await fetch("http://127.0.0.1:8000/api/Expenses/", { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'xxx' } }) const Expenses = await response.json() setExpenses(Expenses.map((expense: any) => formatExpense(expense))); } catch (err) { console.log(err); }; } loadExpenses(); }, … -
Invalid block tag on line 11: 'endblock'. Did you forget to register or load this tag?
Invalid block tag on line 11: 'endblock'. Did you forget to register or load this tag? 1 {% extends 'base.html'%} {%block title%}{{post.title}}{%endblock%}{%block 2 content%} 3 <h1>{{post.title}}</h1> 4 5 <small>Written by: {{post.author}}</small> 6 <br /> 7 <hr /> 8 {{post.body}} 9 <br /> 10 <a href="{% url 'home'%}" class="btn btn-success">Back</a> 11 {%endblock%} 12 -
Get related field names in serializer when ForeignKey is pointed to 'self'
I have a category model which has a field parent. This field can be null, and point to other categories from the same model. I'm having trouble serializing the category, and getting a list of its children using django rest framework. models.py class Category(models.Model): ... name = models.CharField( _('category name'), max_length=255, unique=True ) slug = models.SlugField( _('slug'), max_length=50, help_text=_( 'A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs.' ), ) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, related_name='category', blank=True, null=True ) ... serializers.py class CategoryChildrenSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Category fields = ['children'] def get_children(self, instance): if instance.parent is not None: queryset = Category.objects.filter(parent=instance.parent.id) return queryset class CategoriesNavigationSerializer(serializers.ModelSerializer): children = CategoryChildrenSerializer(many=True, read_only=True) class Meta: model = Category fields = ('name', 'children') Ideally i want the response to look something like: { name: Category 1, children: [ { name: Category 2, slug: ... }, { name: Category 3, slug: ... }, ] } It also important to note that i want to stop on the second child level, even if the parent has grandchildren. I have tried children = serializers.StringRelatedField(source='parent', read_only=True) and also doing the get_children method inside the … -
Can you put a context list inside a context in Django and cycle through it?
Currently, my project is taking grouped, query-sorted posts and displaying a for loop of each one. It is a hassle to put down every single for loop. I want to cycle through all the context without copy-and-pasting them in Jinja2. Can I do something like this? parent_context = { 'context': child_context } child_context = { 'object1': object1, 'object2': object2, ... } -
React Native API request
I'm using Django Rest Framework in my React Native App, so I'm fetching some data, but one field of that data is a foreign key. How can I retrieve that foreign keys data? item.owner displays http://127.0.0.1:8000/api/users/90/ but I want it to be the owners name which I guess needs to be fetched again. const renderItem = ({item}) => ( <> <Text>{item.owner}</Text> <Text>{item.title} : {item.category}</Text> <Image source={{uri:item.book_pic_src}} /> </> -
How to Navigate from other pages to index page specific tag?
I have multiple Options on navbar i.e home team contact store etc. So I have question that if I visited the store page and I want to come back to index.html on a specific tag like team how will I do that? I tried the following code but it didn't work for me base.html <li class="nav-item"> <a class="nav-link" href="{% url 'home:index'%}#team">Team</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'home:index'%}">Testimonial</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'home:index'%}#contact">Contact</a> </li> -
How do I make another variable available in views?
I am trying to add another section to a webpage. the first half works but I cant get the second half to render. The first half runs of a function called pageFour, it has a variable for blog. I created another function called pageFourBlogs that defines a variable for blogs. However it is still not showing up, what am I doing wrong? Thanks in advance for your efforts. urls.py from django.shortcuts import render, get_object_or_404 from .models import Blog def all_blogs(request): blogs = Blog.objects.order_by('?') return render(request, 'blog/all_blogs.html', {'blogs': blogs}) def Entertainment(request): blogs = Blog.objects.filter(category='Entertainment') return render(request, 'blog/Entertainment.html', {'blogs': blogs}) def Technology(request): blogs = Blog.objects.filter(category='Technology') return render(request, 'blog/Technology.html', {'blogs': blogs}) def Culture(request): blogs = Blog.objects.filter(category='Culture') return render(request, 'blog/Culture.html', {'blogs': blogs}) def pageOne(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/pageOne.html', {'blog': blog}) def pageTwo(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/pageTwo.html', {'blog': blog}) def pageThree(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/pageThree.html', {'blog': blog}) def pageFour(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/pageFour.html', {'blog': blog}) def pageFourBlogs(request): blogs = Blog.objects.order_by('?') return render(request, 'blog/pageFour.html', {'blogs': blogs}) pageFour.html {% extends 'blog/navBarFooter.html' %} {% block content %} <h1 class="text-center mt-3" id="blogdetailtitle">{{ blog.title }}</h1> <h5 class="text-center mt-3" id="blogdetailtitle">By: {{ blog.by }} | {{ … -
Django Plotly Dash
I have learned plotly and Dash, which are data visualisations library in python. Though i have got their core concepts and also i am well versed in django python as well, i dont know to integrate dash and plotly in django rest framework. I have searched everywhere but it seems there is a lack of resources on this topic. I want to create a dashboard using the same , just like we create dashboards using front end languages. Please help, i have been searching but not able to get any resources for help. -
DRF - api that lists nested objects but accepts foreign keys during creation
I'm fresh in drf and django overall but i'm working on application that uses drf as backend and react as fronted And currently i'm struggling with crated model serializer for transactions that will allow me to serialize nested objects on GET requests (as i need to refere to is eg. names to show in table) and create transaction with provided foreign keys(creating vie form with dropdowns), as reference to related child objects. Im wondering what would be best approach to achieve it, so for i consider: creating separate fields for getting and saving objects customising create method on view /and serilizer creating separate serializers for listing and creating transaction object I've done some research in drf documentation and here, but so far couldn't find any solutions that would meets\ my needs or be simple enough. Could you give me any advice? Now I'm getting the following error { "category": [ "This field is required." ], "tag": [ "This field is required." ], "transaction_type": [ "This field is required." ], "payment_target": [ "This field is required." ], "payment_source": [ "This field is required." ] } views.py class BaseViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): """ A simple base viewset for creating and editing """ authentication_classes … -
Unable to set up SSL for Django in Docker
I have a django app which will be run using waitress and nginx is used for reverse proxy. Now i need to enable ssl for the site (localhost as of now). The certificates are self signed and i'm unable to enable ssl for the site. Docker doesn't start nginx with error : nginx: [emerg] "ssl_certificate" directive is not allowed here in /etc/nginx/conf.d/django.conf:22 Tried with most of the solutions available and failed.I'm novice to docker. Any sort of help is really appreciated. folder structure : docker-compose.yml file : version: '3' services: nginx: image: nginx:alpine container_name: ng01 ports: - "443:443" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - ./webapp/static:/static - ./certs:/etc/ssl depends_on: - web networks: - nginx_network web: build: . command: python ./webapp/server.py volumes: - .:/code - ./webapp/static:/static networks: - nginx_network networks: nginx_network: driver: bridge django.conf file : upstream web { ip_hash; server web:443; } client_max_body_size 100M; server { listen 80; server_name localhost; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name localhost; location /static { alias /static; } location / { proxy_pass https://web/; ssl_certificate /etc/ssl/localhost.crt; ssl_certificate_key /etc/ssl/localhost.key; add_header Strict-Transport-Security "max-age=31536000" always; 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 $scheme; proxy_connect_timeout 900; proxy_send_timeout 900; proxy_read_timeout 900; } } Dockerfile : FROM … -
Can't communicate between django and selenium docker containers
I'm trying to setup a CI environment where I can test my Django application with selenium where both are running in docker. My test is setup with the following: from time import sleep from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.webdriver.remote.webdriver import WebDriver class MySeleniumTests(StaticLiveServerTestCase): port = 8000 @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver("http://selenium:4444", desired_capabilities={'browserName': 'chrome'}) cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def test_login(self): self.selenium.get('%s:%s%s' % ('http://web', self.port, '/')) greeting = self.selenium.find_element_by_id("greeting") self.assertEqual(greeting.text, 'hello world') I then try to run this on gitlab with this CI setup in my .gitlab-ci.yml: image: name: docker/compose:1.26.2 entrypoint: ['/bin/sh', '-c'] services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 stages: - test before_script: - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY build: stage: test script: - docker build --tag django . - docker network create selenium-net - docker run -d --network selenium-net --name selenium selenium/standalone-chrome:4.0.0-alpha-6-20200730 - docker run --network selenium-net --name web --expose 8000 django dindselenium/manage.py test myapp On my local machine the connection WebDriver setup succeeds but then Selenium fails to connect to the web app. On the CI environment I can't even connect to Selenium from the web app. I've setup an example repo here: https://gitlab.com/oskarpersson/dind-selenium/, and an example of a failing job: https://gitlab.com/oskarpersson/dind-selenium/-/jobs/705523165 -
Djanogo CoinMarketCap API is not updating prices(django.db.utils.OperationalError: database is locked)
I have a website that displays cryptocurrency prices with an SQLite db but unfortunately the prices have stopped updating for some reason. I get an django.db.utils.OperationalError: database is locked error when I run coin_update.py I tried adding 'OPTIONS': { 'timeout': 20, } to my settings.py but the error presists This is what my coin_update.py file looks like: import os, django, sys os.environ['DJANGO_SETTINGS_MODULE']='website.settings' django.setup() import datetime print("Cron Script for coinmarketcap API initialized") from requests import Session from requests.exceptions import ConnectionError, Timeout, TooManyRedirects import json from cryptocracy.models import Coin, CoinHistory url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' parameters = { 'start': '1', 'limit': '5000', 'convert': 'USD', } headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': 'aa817498-b4b3-48da-9774-eb54c26d846b', } session = Session() session.headers.update(headers) try: response = session.get(url, params=parameters) data = json.loads(response.text) coin_data=data except (ConnectionError, Timeout, TooManyRedirects) as e: print(e) coin_data=e integrity_error_count=0 api_length=len(coin_data['data']) for coin in coin_data['data']: update_coin=Coin.objects.filter(ticker=coin['symbol']) if update_coin: is_coin=True if coin['quote']['USD']['percent_change_24h']: change24h=coin['quote']['USD']['percent_change_24h'] else: change24h=0 if coin['quote']['USD']['volume_24h']: volume=coin['quote']['USD']['volume_24h'] else: volume=0 if coin['quote']['USD']['price']: price=coin['quote']['USD']['price'] else: price=0 if coin['circulating_supply']: supply=coin['circulating_supply'] else: supply=0 if coin['max_supply']: max_supply=coin['max_supply'] else: max_supply=0 if coin['total_supply']: total_supply=coin['total_supply'] else: total_supply=0 if coin['quote']['USD']['market_cap']: market_cap=coin['quote']['USD']['market_cap'] else: market_cap=0 if coin['platform']: is_coin=False save_history=update_coin[0] CoinHistory.objects.create(coin=save_history, price=save_history.price, supply=save_history.supply, volume=save_history.volume, total_supply=save_history.total_supply, max_supply=save_history.max_supply, market_cap=save_history.market_cap, change24h=save_history.change24h) update_coin.update(price=price, supply=supply, volume=volume,total_supply=total_supply, max_supply=max_supply, market_cap=market_cap, change24h=change24h) else: integrity_error_count=integrity_error_count+1 continue print("There are " + … -
How to get single object from django
I am creating a website where i am using django database.The database will have one def called categories and one called gifi.So a gif will belong to a category and when one category will be clicked it will send the user to a page where all gifs that belong to that category will show up. This is the models: These are templates i am using: These are the Urls These are the Views Here you can find a video of how website should work -
Django, JWT token refreshing: Paradox? or am I missing something?
Using this: https://github.com/Styria-Digital/django-rest-framework-jwt My app uses HttpOnly tokens for security. Let's say the token has 30 seconds of life with 90 minutes to renew -- using JWT_EXPIRATION_DELTA': timedelta(seconds=30) and JWT_REFRESH_EXPIRATION_DELTA': timedelta(minutes=90) So I send my /token-auth request with a user and password. I receive a token back good for 30 seconds. This is from the response header: Set-Cookie: my-token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InJvbmVubWFnaWQrZmlsbXNpbnRsQGdtYWlsLmNvbSIsImlhdCI6MTU5ODQ3MzIyMiwiZXhwIjoxNTk4NDczMjUyLCJqdGkiOiI3YzEwZTJhMi0wZjQ0LTQ3NjAtOTg3MS0yMmNmNmM4MTI4ZTYiLCJ1c2VyX2lkIjoiNjEyODRjNDItYTdjOS00YWM1LWExZjYtMDY0YzNjOTI1OTVkIiwib3JpZ19pYXQiOjE1OTg0NzMyMjJ9.Y9DIw6ldGog-fsnMFph9ObmVQog1KWhTBjYxnM3u8N4; expires=Wed, 26 Aug 2020 20:20:52 GMT; HttpOnly; Max-Age=30; Path=/; SameSite=None; Secure So I keep sending subsequent requests during the 30 seconds of life, and getting good responses, , all is good. The request header reads: Cookie: my-token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InJvbmVubWFnaWQrZmlsbXNpbnRsQGdtYWlsLmNvbSIsImlhdCI6MTU5ODQ3MzIyMiwiZXhwIjoxNTk4NDczMjUyLCJqdGkiOiI3YzEwZTJhMi0wZjQ0LTQ3NjAtOTg3MS0yMmNmNmM4MTI4ZTYiLCJ1c2VyX2lkIjoiNjEyODRjNDItYTdjOS00YWM1LWExZjYtMDY0YzNjOTI1OTVkIiwib3JpZ19pYXQiOjE1OTg0NzMyMjJ9.Y9DIw6ldGog-fsnMFph9ObmVQog1KWhTBjYxnM3u8N4 Now the 30 seconds expire.... the next request gets an understandable 401 but when I look at it's request header: The Token is gone, it's not used. It's been erased from Chrome. Given that --- how can I use /token-refresh when it requires the old token which has been erased? It's almost as if you are forced to renew it before it expires. But if this is the case, what's the point of having a longer JWT_REFRESH_EXPIRATION_DELTA if it cannot ever be used? -
Show Django Admin DateTimeField accordingly to User's timezone
In Django I have two models - User and Kiosk class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True) email = models.EmailField(_('email'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) role = models.CharField( 'User Role', choices=ROLES, default='agent', max_length=15) updated_on = models.DateTimeField('Updated on', auto_now=True) timezone = TimeZoneField(default='America/Los_Angeles') locations = models.ManyToManyField(Location, blank=True) class Kiosk(models.Model): '''Kiosk unit''' name = models.CharField('Name', max_length=60) enabled = models.BooleanField('Enabled', default=True) created_on = models.DateTimeField('Created on', auto_now_add=True) updated_on = models.DateTimeField('Updated on', auto_now=True) last_check_in = models.DateTimeField('Last Time Checked In', null=True) I need to represent timestamps created_on, updated_on, last_check_in in Django Admin accordingly to timezone field in User (request.user.timezone). I thought of creating custom Widget but in this case I would need to manually add it to each timestamp field, which doesn't sound right, especially, taking into considerations that I wanted to scale in future adding more models with timestamps. Is there any more pythonic solutions? Thanks! -
How to use logging in Django with django-background-tasks library?
I have a Django application which it's deployed to Elastic Beanstalk (Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I'm using django-background-tasks library for my long running processes. I need to save the print outputs in a file as log but I couldn't find any logs about that in bundle logs. So I have imported the logging library such as below. settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR + "/logfile", 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'myapp': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, } } the tasks.py file that in myapp: import logging log = logging.getLogger(__name__) @background(schedule=1) def model_create(csv_file, features): log.info("Preprocessing is starting") model_data = Preprocessing(csv_file, features) log.info("Model is training") model_data.train() The log messages in the model_create function are printed into the logfile, but the log messages in the Preprocessing class are not printed. How can I fix this issue or are there any ways to see the … -
The above exception (int() argument must be a string
The above exception (int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute') was the direct cause of the following exception: i get this error when trying to reload my details.py page. apparently i'm trying to display similar posts by tags. following the docs here's what ive tried: views.py def postdetailview(request, pk,tag_slug=None): Post = get_object_or_404(post, pk=pk) post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = post.objects.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] return render(request, 'blog/post_detail.html',{'post': Post}) i'd add anymore code needed to help thanks in advance -
How to query in multi-level one-to-many relationship in django
I have a multi-level/hierarchical tables. It goes like this template<1-n>category<1-n>subcategory<1-n>brands<1-n>products. presently using Django ORM I can get the hierarchical data using template-id(pk). Now I have a store property in my products model, I want to get the same hierarchical but for a specific store. -
how to access date_joined column from each new account from management commands?
I am writing a custom management commands in Django for unverified users where each new account where it's longer than 24 hours without verifying the email confirmation, then flagged as is_deleted=true, my code looks like this , but however how can I access to date_joined of each new account? User = get_user_model() def handle(self, *args, **kwargs): now = datetime.datetime.utcnow().replace(tzinfo=utc) timediff = now - self.date_joined if User.objects.filter(is_superuser=True): pass else: if timediff.seconds / 3600 - 24 > 0: for user in User.objects.filter(date_joined__gt=timediff, signup_confirmation=0): user.is_deleted = True user.save() return True return False -
How to create a folder in Django to store user inputs
Goal of Code: User uploads a video to our django site. Use opencv to split it up into individual frames (this works well). We store the frames in a unique folder on our backend (this is where the problem lies). What we need help with: Creation of a unique folder based on user inputted video with django with correct path. Save the frames of the video into that folder. The code thus far: from django.db import models from django.urls import reverse import uuid import cv2 import os from django.db import models from PIL import Image, ImageFilter from django.urls import reverse from PIL import Image class Video(models.Model): vid = models.FileField(upload_to=image_upload_location(filename='jpg')) img = models.ImageField(upload_to=image_upload_location(filename='jpg')) date_added = models.DateTimeField(auto_now_add=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def mp4_to_image(self, *args, **kwargs): super().save(*args, **kwargs) This is part we struggling with, creating a unique folder for each video input. This code works on my local computer path however we need to integrate it with django framework try: if not os.exists('exit_folder_path'): os.makedirs('exit_folder_path') except OSError: print ('Error: Creating directory') Here we use opencv to split the video into individual frames and then save them. The imwrite() function saves the frame as a jpeg in path defined by name parameter. We would … -
Django - Error while sending data to highcharts.js
I'm overriding the admin dashboard, and creating a new one with charts. I've created a template tag: @register.simple_tag def expediente_pie(): departamentos = ExpAsociado.objects.values('departamento__nombre').annotate(count=Count('id')) data = [] for d in departamentos: s = "{name: '" + str(d['departamento__nombre']) + "', y: '" + str(d['count']) + "'}" data.append(s) return data In my template I want to show a Pie Chart, with the values that return the tag: {% expediente_pie as exp %} <script src="{% static 'js/highcharts.js' %}"></script> <script> Highcharts.chart('expediente-pie-chart', { chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, type: 'pie' }, title: { text: 'Expedientes por Departamentos' }, tooltip: { pointFormat: '{series.name}: <b>{point.y}</b>' }, accessibility: { point: { valueSuffix: '%' } }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {point.percentage:.1f} %' } } }, series: [{ name: 'Expedientes', colorByPoint: true, data: [ {% for e in exp %}{{ e }},{% endfor %}] // this is where it crashes }] }); </script> With this the Pie Chart doenst plot, and send me the warning Uncaught SyntaxError: Unexpected token '&'. How can I send data to this template correctly and render the chart? -
Exception Value: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
taking a specific quantity from the input box gives an error bookdetails.py <form class="single-product-cart" action="" method="POST"> <input type="number" name="qty" value="1"> <a href="{{book.get_add_to_cart_url}}" type="submit" name="add-to-cart" class="single_add_to_cart_button btn alt" style="margin-bottom:10px;">Add to cart</a> </form> views.py class BookDetailView(generic.DetailView): template_name = 'book_detail.html' model = book def get_context_data(self, **kwargs): context = super(BookDetailView, self).get_context_data(**kwargs) context['book_list'] = book.objects.all().order_by('-id')[:6] context['related'] = book.objects.all() return context def add_to_cart(request, slug): Book = get_object_or_404(book, slug=slug) order_book, created = orderbook.objects.get_or_create( Book=Book, user=request.user, ordered=False) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.books.filter(Book__slug=Book.slug).exists(): quant = request.POST.get('qty') order_book.quantity += int(quant) order_book.save() else: order.books.add(order_book) else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.books.add(order_book) return redirect(request.META['HTTP_REFERER']) I am facing problem in 'order_book.quantity += int(quant)' its showing "Exception Value: int() argument must be a string, a bytes-like object or a number, not 'NoneType'". and its not fetching the quantity value at 'quant = request.POST.get('qty')' print(quant) prints 'none' . -
Is it possible to send div as email template in Django
I'm Django newbie. I wonder if anybody tried to do that. I have UpdateView that renders update form as div and some other content as another div. I wonder if you could send that another div as an e-mail message. I would be like ordering shipping with pickup and delivery address. Does it make sense anyway? views.py class VCIUpdateView(UpdateView): model = VCI context_object_name = 'VCIUpdate' form_class = VCIModelForm template_name = 'VCIupdate.html' success_url = "/VCI" def get_context_data(self, **kwargs): context = super(VCIUpdateView, self).get_context_data(**kwargs) context['subsidiary_address'] = Subsidiary.objects.all() return context def form_valid(self, form, **kwargs ): context = super(VCIUpdateView, self).get_context_data() send_mail("hello", context, 'email', ['email@gmail.com'], fail_silently=False) return super(VCIUpdateView, self).form_valid(form) VCIUpdate.html {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row py-4"> <div class="col"> <form method="post" id="subsidiaryForm" name="text" data-subsidiaries-url="{% url 'ajax_load_subsiriaies' %}" data-salesPersonsDistributor-url="{% url 'ajax_load_salesPersonsDistributor' %}" data-salesPersonsDistributorContact-url="{% url 'ajax_load_salesPersonsDistributorContact' %}" novalidate> <table class="table table-borderless table-condensed"> {% csrf_token %} {{ form.as_table }} </table> <input type="submit" value="Save" /> </form> </div> <div class="col"> <div class="row" id="text"> <table class="table table-borderless"> <thead> <th>Adres odbioru:</th> <th></th> </thead> <tr> <th>Filia:</th> <td>{{ VCIUpdate }} <td>{{ VCIUpdate.salesPersonDistributor.subsidiary }}</td> </tr> <tr> <th>Kontakt:</th> <td>{{ VCIUpdate.salesPersonDistributor.name }} {{ VCIUpdate.salesPersonDistributor.surname }}</td> </tr> <tr> <th>Telefon:</th> <td>{{ VCIUpdate.salesPersonDistributor.phone }}</td> </tr> <tr> <th>Kontakt:</th> <td>{{ VCIUpdate.salesPersonDistributor.email }}</td> </tr> <tr> <th>Ulica:</th> <td>{{ VCIUpdate.salesPersonDistributor.subsidiary.street … -
Django honeypot conflicting with browser autofill
I am attempting to use django-honeypot (https://github.com/jamesturk/django-honeypot) to prevent spam from hitting my website built in django. However the django honeypot field is conflicting with the browser autofill. How can I prevent this? For reference honeypot renders and html field that looks like this: -
Tags on sidebar not showing, how to show tags
I need a way to display all tags from my post on the sidebar so people can choose what posts to show. I tried a loop, but it's not displaying the tags neither the links. Here i let my code, lmk if you need any other file to show. list.html: {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block sidebar %} <p class="tags"> Tags: {% for tag in post.tags.all %} <a href="{% url 'blog:post_list_by_tag' tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> <h4> <a href="{% url 'blog:new_post' %}">Add a new Post</a> </h4> {% endblock sidebar %} {% block content %} {% if tag %} <h2>Posts tagged with "{{ tag.name }}"</h2> {% endif %} {% for post in posts %} <div class="card mb-3"> <h2 class="card-header pl-3"> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <div class="card pl-3"> <p> {{ post.body|truncatewords:30|linebreaks }} </p> </div> <div class="card-footer text-muted pb-1"> Published {{ post.publish }} by {{ post.author }} <p class="tags"> Tags: {% for tag in post.tags.all %} <a href="{% url 'blog:post_list_by_tag' tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> …