Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. on heroku
ERROR: PyAudio-0.2.11-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. while deploying to heroku.I also install this error file in my system. -
How to insert images from render( , , context) in Django?
guys! New in Django so maybe it's a silly question. I have a .json file that keeps information about shop's clothes including "img". The goal is to otput all the information about products in a single "for loop". So I've written such lines {% for product in products %} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"> <img class="card-img-top" src="{% static '{{ product.img }}' %}" !!! problem is here alt=""> </a> <div class="card-body"> <h4 class="card-title"> <a href="#"> {{ product.name }} </a> </h4> <h5>{{ product.price }}</h5> <p class="card-text"> {{ product.description }}</p> </div> <div class="card-footer text-center"> <button type="button" class="btn btn-outline-success">Отправить в корзину</button> </div> </div> </div> {% endfor %} Everything works fine except the line concerns an image. In devtools I get the next path "/static/%7B%7B%20product.img%20%7D%7D". But in the .json file it looks like "img": "vendor/img/products/Brown-sports-oversized-top-ASOS-DESIGN.png". I am totally confused about that situation and definitely in a bind. I appreciate any help -
Upload an image from html template file to a django python class without using model
I am a beginner in coding. I am building an application in Django which requires an image captured through the html and then it should be used in a python class where i want to pass the image to opencv. i am using the following code: store.html:- {% csrf_token %} Image: <input type="file" name="camCapture" accept="image/*" id="image" required> <input type="submit" name="submit" value="submit" required> filter.py: class Pic2Filter(django_filters.FilterSet): img = cv2.imread('CV/static/images/IMG_1159.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) hImg,wImg,_ = img.shape boxes = pytesseract.image_to_data(img) lst = [] for x,b in enumerate(boxes.splitlines()): if x!=0: b = b.split() if len(b)==12: x,y,w,h = int(b[6]),int(b[7]),int(b[8]),int(b[9]) detected_text = b[11] lst.append(detected_text) #Product identification products = Product.objects.values_list('name', flat=True) d = [x.lower() for x in lst] # make dict of list with less elements search_result = [] for m in products: if m.lower() in d: searched_name = Product.objects.filter(name__iexact=m) search_result += searched_name i want to use the captured image instead of CV/static/images/IMG_1159.jpg. Is there a way to do it without using a model or saving? -
The field 'email' clashes with the field 'email' from model 'account.account'. Django3.2
Newbie in django here. I've been trying to create a simple site with django and i just finished creating the models. However, when I try to makemigrations, i get this: SystemCheckError: System check identified some issues: ERRORS: account.Account.email: (models.E006) The field 'email' clashes with the field 'email' from model 'account.account'. I checked my code, but i couldn't find anything bad. Maybe my eyes are broken. Here's my models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class AccountManager(BaseUserManager): def create_user(self, first_name, last_name, name, email, password=None): if not email: raise ValueError("User must have an email address") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, name = name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, name, email, password=None): user = self.create_user( email = self.normalize_email(email), password = password, first_name = first_name, last_name = last_name, name = name, ) user.is_admin = True user.is_staff = True user.is_active = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) name = models.CharField(max_length=50) reputation = models.BigIntegerField(default=1) downvote_count = models.IntegerField(default=0) # mandatory fields created_date = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superadmin … -
Django event stream deployment with daphne
I'm trying to redeploy my Django project on my local ubuntu server to document all the steps, I managed to get it up and running but the problem is my real time notifications are not working, I'm using Django event stream for the notifications. I have setup the Daphne and Nginx accordingly and the event stream connection is opened too but I'm not receiving the real time notifications. There is no code related issue as the same code is on production server and notifications are working there. The problem is I'm not getting any error message so I don't know where to look to debug the issue. I'm sharing the configurations which I did I think I'm missing something in the setup. I have followed Django channels official deployment here. My Nginx and Daphne configurations are in the below images. . Channels=2.3.1 Daphne=2.5.0 Django Event Stream==2.6.0 I'm using http server sent events -
jinja2.exceptions.TemplateNotFound: login.html :FastAPI
I'm a newbie to fastapi , I'm trying to render a html page using a router app/routers/login.py: from fastapi.templating import Jinja2Templates import os # some of codes here.... # BASE_PATH = Path(__file__).parent.resolve() # # lets say your template directory is under the root directory # templates = Jinja2Templates(directory=f'{BASE_PATH}/templates') router = APIRouter( tags=['login'], prefix="/login", ) operating_directory = os.path.dirname(os.path.abspath(__file__)) #templates = Jinja2Templates(directory="templates") templates = Jinja2Templates(directory=os.path.join(operating_directory, 'templates')) @router.get("/", response_class=HTMLResponse) async def login(request: Request): return templates.TemplateResponse("login.html",{"request": request}) my html file is in this location: app/templates/login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link rel="stylesheet" href="css/main.css"> <!-- <link href="{{ url_for('static', path='css/main.css') }}" rel="stylesheet"> --> </head> <body> <div class="container"> <form action=""> <div class="form-group"> <label for="email">Email</label> <input type="text" class="form-control" required> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" required> </div> <input type="submit" class="btn" value="login"> </form> </div> </body> </html> when i try http://localhost:8000/login/ render the template , its shows not able to fin template -
Docker SQL - SQL connection timeout
I have been trying to resolve this issue for many days still I couldn't able to resolve it.I have created the docker image for mssql and django app.when I tried to docker-compose up I can see it still resulting in the same error but when i run in the local its working fine. my system config: microsoft.com/fwlink/?linkid=2099216. sql-server-db | 2021-10-09 13:44:28.18 Server The licensing PID was successfully processed. The new edition is [Express Edition]. 2021-10-09 13:44:28.89 Server Microsoft SQL Server 2017 (RTM-CU26) (KB5005226) - 14.0.3411.3 (X64) Aug 24 2021 09:59:15 Copyright (C) 2017 Microsoft Corporation Express Edition (64-bit) on Linux (Ubuntu 16.04.7 LTS) errorlogs: Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 197, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 312, in get_new_connection web_1 | conn = Database.connect(connstr, web_1 | pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') these are my requirements.txt is anything that i left out to install requirements.txt asgiref==3.4.1 click==8.0.1 colorama==0.4.4 Django==2.1.15 django-mssql-backend==2.8.1 # django-pyodbc-azure==2.1.0.0 … -
Why we use action attribute in html form? What is the difference between action and redirect?
Yes! you must be thinking it is a basic question or stupid etc, but i didn't get the answer of this question on the entire google.. I got the answer of this question is that the action always sends data to the url which was given to the action attribute and just redirect the on that url.. My questions are: Why we use action whenever we can use redirect in django or other backends?: if we send data to the url why we send? Where we use this data? -
Django SECRET_KEY protection VS ability to run project locally
I have read many topics here about django SECRET_KEY, but most of them are about how to store it in environment variable instead of settings.py, at this stage everything is clear. Currently i keep it in .env locally and in config var on heroku. Im confused about 2 conflicting points that i can't combine together. On the one hand, it considers as a good practice to keep SECRET_KEY in secret. From the docs: Instead of hardcoding the secret key in your settings module, consider loading it from an environment variable Besides that github warms in email if you have SECRET_KEY explicit in your code: GitGuardian has detected the following Django Secret Key exposed within your GitHub account. On the other hand, i want to allow anyone to run my project locally. I have it on github and deployed version on heroku, but it's still a demo project which is used as part of portfolio, not a serious one. What is the solution here? To break the protection convention and put it explicitly in settings.py? -
Turn django rest framework url completely off
Hey i was wondering if it is possible to completely turn off the drf own rendering url. I know that u can switch from the browsable api renderer to the JSON renderer. As i have it on my own settings shown below REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ] } When I go to my localhost:8000/products I want to see simply a 404 page and not the JSON rendered products. I am currently using a simple router. -
make djangoAdmin a reall dashboard?
for my project i needed to add some features to the DjangoAdmin using ModelAdmin,used DA's builtins like https://docs.djangoproject.com/en/3.2/ref/contrib/admin and so on ,further i got more things like customizig DJ template link above. at the time, i just wondered that it would be really good for me if i could do more with templates, here is what i need ,almost like full customization . think about a User model that has img, username, and other things almost like a User , including all of these we reach inTime dashboards , can i customize my DjangoAdmin template using my User model and it's objects (img, ...)?? searched a lot and got some builted like django-admin-plus https://github.com/jsocol/django-adminplus any reference, snippet, or any related will help. thanks for your time,ErfanVahedi -
How to Create New User from User_Profile in DRF?
I am creating a cross-platform application in which the users are - Admin, Instructor, and Student. And for registering a new user privilege is only for admin users, so an admin user can add another admin, instructor, and student. I am trying to make nested serializers by which a UserProfile (AdminProfile, InstructorProfile, or StudentProfile) when created also creates User. I am new to django and drf. How can this be done ? serializers.py from rest_framework import serializers from .models import User, ProfileAdmin # # This will have GET method for seeing the users according to the userType. class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'user_type'] extra_kwargs = {'password': {'write_only': True}} class UserProfileSerializer(serializers.ModelSerializer): user_account = UserSerializer(many=False) class Meta: model = ProfileAdmin fields = ['email', 'first_name', 'last_name', 'address', 'telNum', 'aliasMailID', 'MSteamsID', 'user_account'] def create(self, validated_data): account_data = validated_data.pop('user_account') user = ProfileAdmin.objects.create(**validated_data) User.objects.create(**account_data) return user def update(self, instance, validated_data): account_data = validated_data.pop('user_account') user_account = instance.user_account instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.address = validated_data.get('address', instance.address) instance.telNum = validated_data.get('telNum', instance.telNum) instance.aliasMailID = validated_data.get('aliasMailID', instance.aliasMailID) instance.MSteamsID = validated_data.get('MSteamsID', instance.MSteamsID) instance.save() user_account.username = account_data.get('username', user_account.username) user_account.user_type = account_data.get('user_type', user_account.user_type) return instance models.py from django.db import models … -
Python Django function got multiple values for argument
I am trying to call a function to print a receipt using Django in an html file. The function has 1 variable print_order_receipt(number) where the number is the order number fetched from Shopify API. This is the HTML code I did: path('print/<int:number>/', views.print_order_receipt, name="print") And this is the function: def print_order_receipt(number): order = Order.objects.get(number=number) printer = Network("192.168.1.100") printer.text('**********************************************\n') printer.text('LNKO vous remercie!\n') printer.text('**********************************************\n') printer.text('\n') printer.text('\n') printer.text('Commande Numero: ') printer.text(order.number) printer.text('\n') printer.text('\n') printer.text('Montant total a payer: ') printer.text(order.totalprice + " MAD") printer.text('\n') printer.text('Dont taxes: ') printer.text(order.tax + " MAD") printer.text('\n') printer.text('Client: ') printer.text(order.clientfname + ' ' + order.clientlname) printer.text('\n') printer.text('Une facture detaillee a ete envoyee a:\n') printer.text(order.clientemail) printer.barcode(order, 'EAN13', 64, 2, '', '') printer.qr("You can readme from your smartphone") printer.cut() And these are the 2 HTML versions I tried, both are not working: <td><a href="/print/{{ number }}">Imprimer</a></td> <td><a href="{% url 'print' {{ number }} %}">Imprimer</a></td> I don't know what I'm doing wrong here! Here is the Traceback error: Environment: Request Method: GET Request URL: http://localhost:8000/print/12500/ Django Version: 2.2.5 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "D:\Dropbox\Dropbox\My Laptop\lnko\printer_receipt\venv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Dropbox\Dropbox\My Laptop\lnko\printer_receipt\venv\lib\site-packages\django\core\handlers\base.py" … -
How can I store the value of one IntegerField model in another model?
** Hi beginner in Django here, I want to have a model that'll allow the user to modify the balance model, a model for deposit and withdrawal, in a way that the value for the user's balance model can be updated. The user can modify it using the class based view "updateview" ** from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): # DEPOSITOR user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True, max_length=30) # ACCTNO title = models.CharField(max_length=7) # To check number of accounts accountComplete = models.BooleanField(default=False) # BALANCE balance = models.IntegerField(null=True, blank=True) #WITHDRAWAL model #DEPOSIT model def __str__(self): return self.title class Meta: order_with_respect_to = 'user' -
What is wrong with this inkscape extension?
I am not a programmer. I used to use an inkscape extension that was designed to change the path in inkscape to Gcode. Recently this extension stopped working giving the following error massage. The extension has 5 python files (unicorn.py, init.py, context.py, entities.py, svg_parser.py). The error massage I keep getting is: Traceback (most recent call last): File "unicorn.py", line 23, in from unicorn.svg_parser import SvgParser File "C:\Program Files\Inkscape\share\inkscape\extensions\unicorn\svg_parser.py", line 4, in import entities ModuleNotFoundError: No module named 'entities' **Based on the error massage I think the problem is with python.py or svg_parder.py I post the unicorn.py and svg_parser.py here. Can anybody help me with this? unicorn.py text #!/usr/bin/env python ''' '' import sys,os import inkex from math import * import getopt from unicorn.context import GCodeContext from unicorn.svg_parser import SvgParser class MyEffect(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option("--extrude_multiple", action="store", type="float", dest="extrude_multiple", default="1.0", help="Extrude_multiple") self.OptionParser.add_option("--e_r_pattern", action="store", type="float", dest="e_r_pattern", default="1.0", help="E_r_pattern") self.OptionParser.add_option("--e_r_speed", action="store", type="float", dest="e_r_speed", default="900.0", help="E_r_speed") self.OptionParser.add_option("--z_hop_enabled", action="store", type="inkbool", dest="z_hop_enabled", default="true", help="Z_hop_enabled") self.OptionParser.add_option("--z_hop_height", action="store", type="float", dest="z_hop_height", default="10.0", help="Z_hop_height") self.OptionParser.add_option("--z_hop_speed", action="store", type="float", dest="z_hop_speed", default="900.0", help="Z_hop_speed") self.OptionParser.add_option("--x_move", action="store", type="float", dest="x_move", default="0.1", help="X move") self.OptionParser.add_option("--y_move", action="store", type="float", dest="y_move", default="0.1", help="Y move") self.OptionParser.add_option("--layer_delay", action="store", type="int", dest="layer_delay", default="10000", help="Layer_delay") self.OptionParser.add_option("--retraction", action="store", type="float", dest="retraction", default="0.1", help="Retraction") self.OptionParser.add_option("--z_up", action="store", type="float", dest="z_up", … -
Fetch API Django
I'm attempting to implement API from rapidapi.com def home(request): headers = { 'x-rapidapi-host': "...", 'x-rapidapi-key': "..." } url = "..." response = requests.request("GET", url, headers=headers).json() my print statement shows the following: {'data': [{'iso': 'CHN', 'name': 'China'}, {'iso': 'TWN', 'name': 'Taipei and environs'}, {'iso': 'USA', 'name': 'US'}, {'iso': 'JPN', 'name': 'Japan'}, {'iso': 'THA', 'name': 'Thailand'}, {'iso': 'KOR', 'name': 'Korea, South'}, {'iso': 'SGP', 'name': 'Singapore'}, {'iso': 'PHL', 'name': 'Philippines'}, {'iso': 'MYS', 'name': 'Malaysia'}, {'iso': 'VNM', 'name': 'Vietnam'}, {'iso': 'AUS', 'name': 'Australia'}, {'iso': 'MEX', 'name': 'Mexico'}, {'iso': 'BRA', 'name': 'Brazil'}, {'iso': 'COL', 'name': 'Colombia'}, {'iso': 'FRA', 'name': 'France'} How do I insert the data in my template ??? I do understand it's a list ... I did attempted in my views.py : d ={ "iso":response ['data']['iso'], "name":response ['data']['name'] } my template looks like so: <h1> {{data.iso}}</h1> <h2>{{data.name}}</h2> It does not work ... -
Django // Daphne 500 error on all requests after version update "TypeError: object HttpResponse can't be used in 'await' expression"
I have a problem where I'm getting 500 responses after updating Django from version 3.1.13 to 3.2.8. The issue wasn't occurring on the previous version of Django, and it only occurs if both the Django Channels app and OpenCensus middleware are enabled in settings.py. I would really appreciate if someone can help verify that my asgi.py and settings.py are configured correctly, or identify the dependency causing the issue so that I can follow through and raise a bug. Repo that reproduces the issue https://github.com/oscarhermoso/bug-opentelemetry-django-asgi Daphne error as it appears in the browser 500 Internal Server Error Exception inside application. Daphne ASGI entrypoint # testproject/asgi.py import os from django.core.asgi import get_asgi_application # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testproject.settings') from channels.auth import AuthMiddlewareStack # noqa from channels.routing import ProtocolTypeRouter, URLRouter # noqa import testproject.routing # noqa application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": get_asgi_application(), # WebSocket chat handler "websocket": AuthMiddlewareStack( URLRouter( testproject.routing.websocket_urlpatterns ) ), }) Installed apps and middleware # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'opencensus.ext.django.middleware.OpencensusMiddleware' ] Error Dump System check identified no issues (0 silenced). October 09, 2021 - 10:59:03 Django version … -
I get some undefiend behavior in django settings
I changed a drf settings to REST_FRAMEWORK = {'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',)} It's disabled BrowsableAPI. And if I import BrowsableAPI in settings of my proj then this enabled again. Why is it work so? -
Is there any way to send mails regulary using Sendgrid?
I want to send monthly notifications to users that log on to my website. I've thought of using Sendgrid's Marketing campaigns to send monthly mails but it doesn't fit perfectly to my needs. I'll have to keep adding emails to the automation at a month's duration and that doesn't seem the right way to do it. -
Django UpdateView: How to display the original values?
I'm using Django UpdateView to update a Model class class TestCase(models.Model): name = models.CharField(max_length=200) executable = models.CharField(max_length=1023) parameter_value_list = models.TextField() test_type = models.CharField(max_length=200) created_by = models.CharField(max_length=200, default = "user") create_datetime = models.DateTimeField("testcase created on", auto_now = True) My view is as: class MyEditCaseView(UpdateView): model = TestCase fields = ['name', 'executable', 'parameter_value_list', 'test_type'] template_name_suffix = '_update_form' def get_success_url(self): return reverse("myApp:testCase") My template is as: <form action="{% url 'myApp:editCase' case.id %}" method="post"> {% csrf_token %} <input type="submit" value="Edit"> </form> urls: path('editCase/<int:pk>/', views.MyEditCaseView.as_view(), name='editCase') It works OK, but I have 2 questions: The update view page pop out is blank for all fields even they have old values. I won't like to change all fields. How to show the old values, if I don't want update all fields? The default lay out of the update view page seems not elegant. Can I change the style? -
Is there a way to encrypt the password when creating a non-admin user in Django Admin Panel?
I'm new with django and I making an app just for practice so I wanted to try to create different users, so I have the admin user and other 2. I'm not making a sing up page as I wanted to only be able to create the users in the admin panel so I have: #models.py from django.db import models # Create your models here. class UserType1(models.Model): Username = models.CharField(max_length=50, null=False) Password = models.CharField(max_length=50, null=False) class Meta: ordering = ('Username',) def __str__(self): return self.Username class NormalUser(models.Model): Username = models.CharField(max_length=50, null=False) Password = models.CharField(max_length=50, null=False) class Meta: ordering = ('Username',) def __str__(self): return self.Username And to show it in the Admin panel: #admin.py from django.contrib import admin from . import models # Register your models here. @admin.register(models.UserType1) class UserType1Admin(admin.ModelAdmin): list_display = ('Username','Password') search_fields = ("Username", ) @admin.register(models.NormalUser) class NormalUserAdmin(admin.ModelAdmin): list_display = ('Username','Password') search_fields = ("Username", ) For example, creating a NormalUser, as you can see, that's how it's saved, the password it's just simple text: Normal User Creation Showing Normal User In the future, they will hace different fields but, for now, the thing I want to know if there is a way to save the password encrypted in the data … -
ImportError: cannot import name 'Maca' from partially initialized module 'maca.models' (most likely due to a circular import)
I have this error ImportError: cannot import name 'Maca' from partially initialized module 'maca.models' (most likely due to a circular import). I have code like this from maca.models import Maca class Maca2(models.Model) maca = models.ForeignKey( Maca, on_delete=models.CASCADE ) Now to model "Maca" I'm trying to access every single "Maca2" objects like this from maca2.models import Maca2 class Maca(models.Model) ... @property maca_has_maca2(self) maca2 = Maca2.objects.all() Can you help me to handle this? -
NoReverseMatch at "/"
Hello I get an error "NoReverseMatch at "/" Everything works when I use pk as user.username in "cart-page" but I can not set it as cart.id or orderitems.id. It is not fault of Urls because I have changed "str" to "int" code: HTML: <div class="navbar__rightside"> <a class="navbar__link" href="{% url 'cart-page' cart.id %}">Cart</a> <a class= "navbar__link" href="{% url 'profile-page' user.username %}">Profile</a> <a class="navbar__link" href="{% url 'logout-page' %}">Logout</a> </div> views.py: class ShopListView(ListView): model = Item template_name = 'shop/home.html' context_object_name = 'items' def post(self, request, *args, **kwargs): return reverse('detail-page') class CartView(TemplateView): template_name = "shop/cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cart'] = Cart.objects.annotate( price=Sum(F('orderitem__item__price') * F('orderitem__quantity')) ).get(order_user= self.request.user) cart = context['cart'] cart.total = cart.price cart.save() context['order_items'] = OrderItem.objects.filter(cart=cart) return context def post(self, request, pk): if 'minus' in request.POST: cart = Cart.objects.get(order_user=self.request.user) OrderItem.objects.filter(id=pk, cart=cart).update( quantity=F('quantity')-1) return HttpResponse("cart uptaded") urls.py path('', ShopListView.as_view(), name='home-page'), path('cart/<int:pk>/', CartView.as_view(), name='cart-page'), -
Not able to download file from django server
I want to download an image from server using httpresponse mediaobj = Media.objects.filter(id=fileid)[0] response = HttpResponse(content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % mediaobj.filename() response['X-Sendfile'] = mediaobj.mediafile.path Above code is from my view. But i am getting 0 byte file in return Why? Actually its a 142KB file. -
Can i upload files in one django filefield as a list of files?
I have created a webpage where a candidate can apply for jobs. There, they can list different previous experiences. I am handling all experience details by concatenating them in my models and splitting them while fetching. how should I handle files in such a case? My Applicant model has the FileField called company_doc. Can it also somehow take multiple files so that I can retrieve them via some indexing? is that possible?