Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Excel File Upload
Note: Please read the whole question before marking it as duplicate. Django has changed ALOT Since a couple of years. I have already tried all the solutions and read Django Rest Framework Documentation on: FileUploadPasrer https://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser MultiPartParser https://www.django-rest-framework.org/api-guide/parsers/#multipartparser. None of the ways work. I also tried uploading using simple Django but that didnt seem to work Either. The Error I am getting is that request.FILES['file'] is always an empty {}. Write now my code looks like this parser_classes = [MultiPartParser] def put(self, request, format=None): file_obj1 = request.data['file'] data = json.loads(request.POST['form']) print(file_obj1) return Response(status=status.HTTP_201_CREATED) Like i said I always tried Using FileUploadParser. Same code just replaced MultiPartParser with FileUploadParser. I am using Postman to send an excel file and then reading it. Anyone who has recently upload an excel file in Django Rest Framework can guide me but make sure your code works becuase I have already spent a day and still can't find the solution so far. Edit: Curl Request from Postman would be: curl --location 'http://localhost:8000/amm-api/upload/upload_workbook/' \ --form '=@"/Users/razan/Projects/HTS/ags-carmax/Robbie_Lisa-Branch.xlsx"' This is how it looks in Postman -
i'm having django bug
in my project i need to build a function that send email to the trip owner depending on the button clicked accept or refuse: here is my views code : from django.shortcuts import render from .models import Guide,Trip from django.core.mail import EmailMessage from django.conf import settings def accept(request): trips = Trip.objects.all() z = {'aw': trips} if request.method == 'POST': for i, trip in enumerate(trips): trip_id = request.POST.get('trip_id_{}'.format(i)) #send email to the trip_id owner print("trip_id =", trip_id) if 'accept_{}'.format(i+1) in request.POST: email_msg = EmailMessage( 'Trip accepted', 'Hi there! Your trip has been accepted.', settings.EMAIL_HOST_USER, [trip.owner_email], ) email_msg.fail_silently = True email_msg.send() elif 'refuse_{}'.format(i+1) in request.POST: email_msg = EmailMessage( 'Trip refused', 'Hi there! Your trip has been refused.', settings.EMAIL_HOST_USER, [trip.owner_email], ) email_msg.fail_silently = True email_msg.send() return render(request, 'system/accept.html', z) here is my template code : {% block content %} {% for x in aw %} {{x.owner}} {{x.owner_email}} <form method="post" action="{% url 'accept' %}"> {% csrf_token %} <input type="hidden" name="trip_id_{{ forloop.counter }}" value="{{ x.id }}"> <br> <input type="submit" name="accept_{{ forloop.counter }}" value="accept"> <input type="submit" name="refuse_{{ forloop.counter }}" value="refuse"> </form> {% endfor %} {% endblock content %} my web page looks like this enter image description here but when i press accept button to send … -
Multi-database in django: Tables not dumped
I'm trying to demonstrate the use of multi-database in Django using db routers but facing issues dumping data into respective databases. The django models are visible in both databases, but not my own created ones. Here is my models.py file: from django.db import models from django.db import models from django.contrib.auth.models import User from peewee import * import psycopg2 # Create your models here. class temp(models.Model): id= models.IntegerField(primary_key=True) class Meta: app_label='client_db' db_table='temp' class temp2(models.Model): id= models.IntegerField(primary_key=True) class Meta: app_label='default' db_table='temp2' settings.py DATABASE_ROUTERS = ('app_celery.dbrouter.client_router', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } , 'client_db': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'amm', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': '127.0.0.1', 'PORT': 5432, }, } dbrouter.py class client_router: """ A router to control all database operations on models in the user application. """ def db_for_read(self, model, **hints): """ Attempts to read user models go to users_db. """ if model._meta.app_label == 'client_db': return 'client_db' return 'default' def db_for_write(self, model, **hints): """ Attempts to write user models go to users_db. """ if model._meta.app_label == 'client_db': return 'client_db' return 'default' def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the user app is involved. """ if obj1._meta.app_label == 'client_db' or \ obj2._meta.app_label … -
Javascript not loading in my Django + React Project with Vite.js
So I had created a project with React as frontend and Django as it backend. For the backend and frontend two separate folders were created : backend and frontends (ignore the spelling mistake it was intentional). I created a react project using vite.js and also created a build production by using the npm run build command. I then linked the dist folder which was generated to django through settings.py along with all other configurations needed for linking static files and stuff, editing views.py as well as urls.py. Below is the syntax for my STATICFILES_DIRS STATIC_URL = '/assets/' STATICFILES_DIRS = (os.path.join(REAL_BASE_DIR,'frontends', 'dist', 'assets'),) Also the directory tree of my project : screenshot So when I start the django server the static files successfully load (like the javascript and the .css) and its show 200 Success CODE and no 404 but in the console of my browser the following error shows up particularly for the Javascript file (not the css). error image The CSS file loads successfully with no errors but the Javascript file shows the above error and I can't find any possible solution on how to fix it. Expecting the JavaScript file to load since there were no 404 Not … -
Websocket connection to failed on production host but it is fine in localhost django
I implemented websocket connection for live ubdation in by django application . The problem is it works in localhost but when i host the same application in public host server it not connecting .i used to host Daphne server droping my code down below myjavascript.js let urls=`ws://${window.location.host}/ws/socket-server/` const Wsocket=new WebSocket(urls) Wsocket.onmessage=function (e) { let data=JSON.parse(e.data) console.log(data) } consumer.py # consumer.py class SocketConsumer(WebsocketConsumer): def connect(self): self.accept() self.room_group_name='test' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.send(text_data=json.dumps({ 'type':'connection_established', 'message':'you are noew connected' })) #routnig.py websocket_urlpatterns=[ re_path(r'ws/socket-server',consumers.SocketConsumer.as_asgi()) ] #asgi.py application = ProtocolTypeRouter( { "http": get_asgi_application(), 'websocket':AuthMiddlewareStack( URLRouter( App.routing.websocket_urlpatterns ) ) # Just HTTP for now. (We can add other protocols later.) } ) I used channels settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': "channels.layers.InMemoryChannelLayer" } } and i run my application command daphne myproject.asgi:application help me legends -
What is the expected way to set `filterset_fields` in Django-Filter and Django REST Framework?
When I set the fiterset_fields like below, class SubCategoryViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = [DjangoFilterBackend] filterset_fields = ["category_id"] # single underscore I get this response when a category with the specified ID doesn't exist { "category_id": [ "Select a valid choice. That choice is not one of the available choices." ] } But when I set it like class SubCategoryViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = [DjangoFilterBackend] filterset_fields = ["category__id"] # notice the double underscore I get a [] when a category with the specified ID doesn't exist. Why does this happen? What is the right way to do this? -
Heroku Django app with AWS OpenSearch (anonymous user is not authorized issue)
I used to have an ElasticSearch Service instance (t2.micro.search) set up to enable a search functionality for an app hosted on Heroku. That old setup was working fine. I now tried to set up a new instance (t3.small.search) using the same settings as the previous one. However, when I tried to build the index from Heroku, I got this error: TransportError(403, '{"Message":"User: anonymous is not authorized to perform: es:ESHttpPost with an explicit deny in a resource-based policy"}' I realized my access policy has "Deny" instead of "Allow" I had before: { "Version": "2012-10-17", "Statement": [ { "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": "es:*", "Resource": "arn:aws:es:us-east-1:000000000000:domain/my-domain/*" } ] } I tried to change it to "Allow" but the console would not allow me to save the settings ("Apply a restrictive access policy to your domain"). Does somebody know how to set up the access policy so I can continue to use AWS OpenSearch for a Heroku app? -
wagtail on-publish custom sucess message
I have a question regarding the success message wagtail is displaying when an editor is publishing a page in the admin interface. It's usually "Page {Page.title} has been published". I’am trying to figure out how to add one’s own success or error message on-publishing resp. an error occuring. For a Page in my project I have implemented the below receiver that gets activated if the editor uploads in a certain field a file and publishes the site. This file is then processed by a script, though the file itself is not saved. For the editors, I would like to have a custom success message displayed below the default on-publish success message if they uploaded the file successfully, tough only if the pages is published after uplaoding a file. I found the question linked below, I could figure out how to show a custom message but it is not a very satisfying solution. The wagtail version, I'am using is 4.22 customize-post-publish-flash-message-in-wagtail-cms @receiver(page_published, sender=Model) def process_uploaded_file(sender, instance, **kwargs): if instance.uploaded_file: process_data(instance.uploaded_file.path) instance.uploaded_file.delete(save=False) instance.uploaded_file = None instance.date = (date.today()) instance.save() I took the hook from the answer in the question linked above and changed it a bit. If one of the pages of … -
Django: AttributeError - ‘bytes’ object has no attribute ‘amount’
I got back this response from an api call b'response=1&responseMessage=APPROVED&noticeMessage=New+Card+Stored+-+New+Customer+Created+-+New+Order+Created+-+Order+Marked+as+Paid&date=2023-04-14&time=09%3A00%3A57&type=purchase&amount=100.00&cardHolderName=Sammy&cardNumber=5413+++9130&cardExpiry=0125&cardToken=0eaf06f7a255b5f0f7703f&cardType=Mastercard&transactionId=36341061&avsResponse=X&cvvResponse=M&approvalCode=T4E6ST&orderNumber=INV001007&customerCode=CST1007&currency=USD&xmlHash=10d7b700eb6d291b19368a437dd19709fcadb6da36879f078a9ad4548986101a&xml=%3Cmessage%3E%3Cresponse%3E1%3C%2Fresponse%3E%3CresponseMessage%3EAPPROVED%3C%2FresponseMessage%3E%3CnoticeMessage%3ENew+Card+Stored+-+New+Customer+Created+-+New+Order+Created+-+Order+Marked+as+Paid%3C%2FnoticeMessage%3E%3Cdate%3E2023-04-14%3C%2Fdate%3E%3Ctime%3E09%3A00%3A57%3C%2Ftime%3E%3Ctype%3Epurchase%3C%2Ftype%3E%3Camount%3E100.00%3C%2Famount%3E%3Ccurrency%3EUSD%3C%2Fcurrency%3E%3CcardHolderName%3ESammy%3C%2FcardHolderName%3E%3CcardNumber%3E5413+++9130%3C%2FcardNumber%3E%3CcardExpiry%3E0125%3C%2FcardExpiry%3E%3CcardToken%3E0eaf06f7a255b5f0f7703f%3C%2FcardToken%3E%3CcardType%3EMastercard%3C%2FcardType%3E%3CtransactionId%3E36341061%3C%2FtransactionId%3E%3CavsResponse%3EX%3C%2FavsResponse%3E%3CcvvResponse%3EM%3C%2FcvvResponse%3E%3CapprovalCode%3ET4E6ST%3C%2FapprovalCode%3E%3CorderNumber%3EINV001007%3C%2ForderNumber%3E%3CcustomerCode%3ECST1007%3C%2FcustomerCode%3E%3CincludeXML%3E1%3C%2FincludeXML%3E%3C%2Fmessage%3E' I am trying to get some attribute/value from the response, i don't know if that would be possible since this is not a json response, this is how i am trying to get the reponse def process_endpoint(request): data = request.body.amount print(data) context = { 'response':data } return render(request, "payments/response.html", context) but i keep getting this error that says AttributeError: 'bytes' object has no attribute 'amount' whenever i include json_data = request.body.amount. Firstly, can i convert this response that i got to a json response? I tried doing that but got an error that says JSONDecodeError at /process_endpoint/ Expecting value: line 1 column 1 (char 0) this is the code i used import json json_data = json.loads(request.body.decode(encoding='UTF-8')) Secondly, can i get some specific attributes/value from the response?, e.g amount, date, payment_type etc -
How to create Django model for data with multiple images
I basically want to create a multivalued attribute called images. I created a model called CseDepartment with attributes: title, description, updated and created. Then i created another model called NewsImage with attributes: cseDepartment (foreign key), images, created and updated. But while running the code i get error saying CseDepartment has no attribut called newsImage_set. how to fix this issue? each news or data in CseDepartment can have multiple images how can i make this work? Error shown when accessing template This is what I tried: views.py: def cse_dept(request): dept = CseDepartment.objects.all() context = { 'dept' : dept} return render(request, 'website/cse_dept.html', context) def cse_news(request, pk): cseDepartment = CseDepartment.objects.get(id=pk) images = cseDepartment.newsImage_set.all().order_by('-created') context = {'news' : cseDepartment, 'newsImages' : images} return render(request, 'website/cse_news.html', context) models.py: class CseDepartment(models.Model): title = models.CharField(max_length=200) image = models.CharField(max_length=300) description = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.title class NewsImage(models.Model): cseDepartment = models.ForeignKey(CseDepartment, on_delete=models.CASCADE) image = models.CharField(max_length=300) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.image[0:50] urls.py path('cse_dept/', views.cse_dept, name="d-cse"), path('cse_news/<str:pk>/', views.cse_news, name="news"), template <h3>{{news.title}}</h3> {% for pic in newsImages %} <img src="{{pic.image}}" alt=""> {% endfor %} I want this template to display all the images relating … -
can not update adminprofile model using restapi with dj rest auth even if change permission_classes = [AllowAny] despite it work with userprofile
i have adminprofile and userprofile models, i made restapi to update fields inside them when i use it with the userprofile it works , but with admin profile it give me this erorr error : **Code Details 401 Undocumented Error: Unauthorized Response body Download { "detail" : "The user is invalid" } ** #inside model.py class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, password, **other_fields) def create_user(self, email, username, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username,password=None,**other_fields) other_fields.setdefault('is_normal', False) other_fields.setdefault('is_patient', False) other_fields.setdefault('is_farmer', False) other_fields.setdefault('is_suffer_heart', False) other_fields.setdefault('is_suffer_kidney', False) user.set_password(password) user.save(using=self._db) return user def upload_to(instance,filename): return 'users_api/{filename}'.format(filename=filename) def validate_phone_number(value): if not re.match(r"^01[0125]{1}", value): raise ValidationError("Phone number must start with 010 or 011 or 012 or 015") if not re.match(r"^\d{11}$", value): raise ValidationError("Phone number must be 11 numbers") class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150) password= models.CharField(max_length=20) created_at = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_normal = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) is_farmer … -
How to test DB connection Using Google Cloud SQL, Secrets Manager with Django 4.1 gcloud setup. Windows 10
I am following this tutorial and when I get to "python manage.py make mirations" I get the error - Models aren't loaded yet cloud-sql-proxy.exe is running on another cmd. I am trying to troubleshoot this but I am very new to Google Cloud SQL and Secrets Manager. Is there a way to determine if the issue is the secrets manager, the code or the DB? Traceback (most recent call last): File "D:\Programming\Django\Polls\manage.py", line 36, in <module> main() File "D:\Programming\Django\Polls\manage.py", line 32, in main execute_from_command_line(sys.argv) File "D:\Programming\Django\Polls\pollenv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Programming\Django\Polls\pollenv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Programming\Django\Polls\pollenv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "D:\Programming\Django\Polls\pollenv\lib\site-packages\django\core\management\base.py", line 455, in execute self.check() File "D:\Programming\Django\Polls\pollenv\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "D:\Programming\Django\Polls\pollenv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "D:\Programming\Django\Polls\pollenv\lib\site-packages\django\core\checks\model_checks.py", line 18, in check_all_models models = apps.get_models() File "D:\Programming\Django\Polls\pollenv\lib\site-packages\django\apps\registry.py", line 181, in get_models self.check_models_ready() File "D:\Programming\Django\Polls\pollenv\lib\site-packages\django\apps\registry.py", line 143, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
X-Accel-Redirect to a soft-linked directory gives 403 permission denied
We have a django view that returns a response with the X-Accel-Redirect header: @login_required def get_secure_file(request): response = HttpResponse() # Content-type will be detected by nginx del response['Content-Type'] response['X-Accel-Redirect'] = '/securemedia/signicat/foo.pdf' return response and the nginx config is set up with: location /securemedia/ { internal; alias /srv/data/smedia/mysite/filer_private/; } in /srv/data/smedia/mysite/filer_private/ there is a (soft) link to /srv/data/appdata/signicat/ with the following permissions/owners/groups: /srv$ ls -ld /srv/data/appdata/sig* drwxrwsr-x 3 erlend gunicorn 86016 Apr 14 16:00 /srv/data/appdata/signicat /srv$ ls -ld /srv/data/smedia/mysite/filer_private/sig* lrwxrwxrwx 1 sak www-data 26 Apr 3 15:26 /srv/data/smedia/mysite/filer_private/signicat -> /srv/data/appdata/signicat and the file we're looking for is inside the signicat directory: /srv$ ls -l /srv/data/appdata/signicat/foo* -rw-rw-r-- 2 sak gunicorn 281376 Apr 14 15:19 /srv/data/appdata/signicat/foo.pdf i.e. everything should at least be world-readable. Still we get a 403 error from nginx, access.log: 88.88.88.88 - - [14/Apr/2023:15:31:30 +0200] "GET /get-secure-file/ HTTP/1.1" 403 196 0.066 "https : //www.mysite.com/dashboard/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36" "http-host=www.mysite.com" "elapsed=0.066s" "scheme=https" error.log: 2023/04/14 15:31:20 [error] 1460872#1460872: *785119 open() "/srv/data/smedia/mysite/filer_private/signicat/foo.pdf" failed (13: Permission denied), client: 99.99.99.99, server: www.mysite.com, request: "GET /get-secure-file/ HTTP/1.1", upstream: "http://unix:/tmp/gunicorn@mysite.sock/get-secure-file/", host: "www.mysite.com", referrer: "https : //www.mysite.com/dashboard/" (space added around colons since url's, even fictitious ones, can't exist in question text..) … -
Cant find function index from templates in my django project when calling from core.baurl where baurl is the url folder of the app core
enter image description hereyour text enter image description hereyour text enter image description hereyour text Can anyone help me out with this problem ? https://github.com/DebankanSarkar989/Testrepo/tree/main I tried solving it changing it from the from core views but it didn't help . -
Which should i learn now, Flask or Django [closed]
I just learnt core python for software development and now i am trying to pick up a framework, which of the framework would you advise me to pick up?? Flask or Django -
Nginx 403 fobidden for static files in django
I deployed my webiste on a linux server but the problem is that css is not loading. NGINX server { listen 80; server_name ip; location = /favicon.ico { access_log off; log_not_found off; } # Serve static files location /static/ { root /home/paul/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Inside of myproject I have below directories and file myproject(dir-here are settings.py, etc) env(dir) manage.py main(dir) requirements.txt static(dir) static admin(dir) css(dir) media(dir) settings.py STATIC_URL = '/static/' import os STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I do not know what I am doing wrong, on my local computer everything looks ok -
How could we change the app name in Wagtail after creation?
Because of some mistakes in naming the apps during their creation with Wagtail and working on their content for some days, It's important to know how we could change their name after creation with Wagtail. I'm trying to do it with Django's methods for creating and changing the app name. But they didn't work perfectly. -
Django: how can i show user data based on model object
I have a model called Category, and I want to show some icons based on what is created from a Category model, if user created an object from a Category model called Food, I want to show the food icon in the template, for example: {% if category is food %} <a href=""> show Food Icon </a> {% else %} show others category icons using this method below: a user can click an object and get everything that is created from a Product model with a category of food or any object of Category model, but I do not know how to write a query to get an object of Category model and show icon based on that object. how can I do this? def home(request): category = request.GET.get('category') if category == None: products = Product.objects.all() else: products = Product.objects.filter(category__name=category) categories = Category.objects.all() context = { 'products': products, 'categories': categories } return render(request, 'home.html', context) template: <div class="container"> <div class="row justify-content-center"> {% for category in categories %} <div class="col-md-4"> <a href="{% url 'home' %}?category={{category.name}}">{{category.name}}</a> </div> {% endfor %} </div> </div> models: class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return str(self.name) -
Django. Field for selecting values (ManyToMany) as in the admin panel
How to achieve the display of the field for the form (when it is filled) as in the admin panel (screenshot)? I tried using forms.CheckboxSelectMultiple widget but it doesn't quite fit. It provides the entire list from the request as a whole, this is not very convenient, since my list will be very large. We need a slider and search fields, as it is actually implemented in the admin panel. -
django restfrawwork not working on cpanel [closed]
when i try to save to db on cpanel not working but get method is working the code is def CreateUser(request): serializer = UserSerializer(data=request.data) try: if serializer.is_valid(): serializer.save() return Response(serializer.data) except User.DoesNotExist: return JsonResponse({'status':'404','message':'invalid user data'}) -
How to scrape headlines by a keyword using django
Hi i've written a web scraper with beautiful soup and django. I'm trying to display the headlines that contain the keyword, which has been sent by the user or in other words the user searches for something and we scrape the headlines related to that search and then show them to the user. I've tried it without search and it worked. But when i search for something no headline is scraped. This is what i've written so far. What should i do? Thanks in advance. my views.py from django.shortcuts import render import requests from bs4 import BeautifulSoup news_list = [] def search(request): bbc_r = requests.get("https://www.bbc.com/news") bbc_soup = BeautifulSoup(bbc_r.content, 'lxml') if request.method == 'post': q = request.POST.get('q') query = bbc_soup.find_all('a', {"class": "gs-c-promo-heading gs-o-faux-block-link__overlay-link gel-pica-bold nw-o-link-split__anchor"}) for th in query: if q in th: news_list.append(th.text) return render(request, 'search.html', {'news_list':news_list}) this is my html <!DOCTYPE html> <html> <head> <title>News</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> </style> </head> <body> <div class="jumbotron"> <center><h1>BBC News Headlines</h1> </center> </div> <div class="container d-flex align-items-center justify-content-center"> <div class="row"> <div class="col-6"> <h3 class="text-center mb-5"> Lastest News</h3> {% for n in news_list %} <h5 class="text-center"> - <a href="https://www.bbc.com/news"> {{n}} </a></h5> <hr> {% endfor %} <br> </div> </div> </div> this is the … -
How to pass context to the django static template tag
I have an image with the name image1.png. Image name is stored in the context_image like context_image = 'image1.png'. How to pass my context_image to this code {% static "images/image1.png" %}? I try this {% static "images/{{ context_image }}" %} but this code ain't working. -
Django does not download file from query
I have a Django app where I need to allow a user to download a log file generated from a query. I have created a view for the download, and I generate the file - but once the client presses the button (called with ajax), nothing gets downloaded. My View is as follows: def download_rollback(request): serial = request.POST.get('serial') response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{}.csv"'.format(serial) writer = csv.writer(response) writer.writerow(['timestamp','serial','log']) queryset = ConfigLog.objects.filter(ser_no=serial).filter(log__contains='ROLLBACK') for obj in queryset: writer.writerow([obj.timestamp, obj.ser_no, obj.log]) return response and I have the following urls.py: urlpatterns = [ ... path('beaconing/download_rollback/', views.download_rollback,name='download_rollback'), ... ] I have followed various tutorials to try this - they all pointed to something like the above, but none works. -
Data in form is not showing in database. Only new line is appearing
I am doing project in django. It is voting system. I already designed webpage. But the problem is when I connected voting page to database it is not working properly. When i am voting and submitting the form. It is not displaying in database. Only entry is happening. Means there will be new line add in table but the data we entered in voting page is not showing. How can I solve this? I want to display voter name and the candidate name voter voted for in database. -
No data is sent when submitting the django form
I'm trying to create an Order object via ModelForm, but nothing comes out. Forms.py class OrderCreateForm(forms.ModelForm): user = forms.ModelChoiceField(queryset=get_user_model().objects.all(), widget=forms.HiddenInput()) is_payed = forms.BooleanField(required=False, widget=forms.HiddenInput()) status = forms.IntegerField(widget=forms.HiddenInput()) payed_at = forms.DateTimeField(widget=forms.HiddenInput(), required=False) price = forms.IntegerField(widget=forms.HiddenInput(), required=False) class Meta: model = m.OrderStorage fields = '__all__' Views class StartOrder(generic.CreateView): template_name = 'clientpart/order_create.html' success_url = reverse_lazy('order_list_tire') form_class = f.OrderCreateForm queryset = m.OrderStorage.objects.all() def get_form(self, form_class=None): if form_class is None: form_class = self.get_form_class() form = form_class(**self.get_form_kwargs()) if form.is_valid(): size = int(str(form.cleaned_data['size'])) period = int(str(form.cleaned_data['period'])) price = size*period form.fields['price'].queryset = int(price) return form def get_form_kwargs(self,): ret = super().get_form_kwargs() print(ret) ret['initial'] = { 'user': self.request.user.pk, 'status': OrderStatus.CREATE, } return ret According to my idea, the value is taken from the field and the price is created, then it is written to the dictionary, but for some reason it is not written to the dictionary. enter image description here How do I record an object price