Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how make in django after one time login stay login when ever user log out
after one time login it automaticely logout next runserver time, can i prevent ? it is possiable example facebook ,youtube other web page . in my case when start of my Django Project(Runserver) and when I logging with authenticate data and it is successful to login , after complete work and I close the django run server then it is automatically logout dot but I want to the previous login account is tail login if the user want to log out in that case it is logout but other case it is still again -
Django Ecommerce site Deployment can not find the static files. Gunicorn and Nginx
The project is named medE. And under the project folder i have my static folder named static. I also have other apps inside it. But my main concern is over settings.py and statics. After deploying it in a digitalocean droplet, the static files are found in port 8000 which is basically Gunicorn but my static file is no found in the IP which i set up using Nginx. Without the static files everything is working fine. Here is my directory structure in the project named medE. ├── Home/ ├── authentication/ ├── medE/ │ ├── settings.py │ └── wsgi.py ├── media/ ├── products/ ├── static/ ├── templates/ └── manage.py Here is my settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-!p!jwnxnk_nf)5psc4-bu2n(^so-zk0#-c_t=gl97a-*4(rs0@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["mede-dxyxn.ondigitalocean.app", "localhost", "167.71.202.130"] SESSION_ENGINE = 'django.contrib.sessions.backends.db' SESSION_COOKIE_AGE = 1870050 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
Django CMS Form for Anonymous User
I have Django CMS application and I want to give different permissions to user. Before giving permission, I want to authenticate User with LDAP backend. I have created LDAP backend and working fine. I have created login form using Django form and rendered in template. The form only appears on UI when the user is logged in using Django Admin. How can I render this form when the user is not logged in or when the user is anonymous. How do I solve this issue? Thank you. code for forms: from django import forms class loginForm(forms.Form): user_name = forms.TextInput() password = forms.PasswordInput() I tried to check the permission but finds permission only for plugins, I couldn't find the permission settings for form in admin interface of Django CMS. Also, I don't have any logic in template or views.py to allow forms for only authenticated user. -
Cross-origin request not setting cookies, reactJs, Django Backend, Firefox + Chrome
I have a react app, and sending requests as such: const public_key_r = await axios.get( "https://eliptum.tech/get-public-key", { withCredentials: true, // This is crucial for cookies to be sent and received in cross-origin requests }, ); const publicKey = public_key_r.data.publicKey; const csrfToken = public_key_r.data.csrf_token; console.log(csrfToken); const encryptedPassword = await encryptData(password, publicKey, false); const response = await axios.post( "https://eliptum.tech/user/create", { username, encryptedPassword, email, phone_number: phoneNumber, }, { withCredentials: true, headers: { "X-CSRFToken": csrfToken, }, }, ); My Backed view for https://eliptum.tech/get-public-key get request is: class PublicKeyView(View): def get(self, request): # Ensure a session ID is available if not request.session.session_key: request.session.save() session_id = request.session.session_key private_key, public_key = RSAKeyManager.get_keys(session_id) if not private_key or not public_key: # Keys are generated as bytes, so decode them before storing private_key, public_key = RSAKeyManager.generate_keys() RSAKeyManager.store_keys(session_id, private_key.decode('utf-8'), public_key.decode('utf-8')) if isinstance(public_key, bytes): public_key = public_key.decode('utf-8') # Retrieve CSRF token csrf_token = get_token(request) # Construct the JSON response response_data = { "session_id": session_id, "public_key": public_key, "csrf_token": csrf_token } # Create JsonResponse with the response data response = JsonResponse(response_data, status=200) # Set CSRF token as a cookie in the response # Ensure the Secure and SameSite attributes are correctly set for cross-origin compatibility response.set_cookie('csrftoken', csrf_token, secure=True, samesite='None') response['Access-Control-Allow-Credentials'] = 'true' return response … -
ModelForm in Django doesn't know attribute is already filled - NOT NULL constraint failed: teretana_pretplatnik.first_name
I am making a Django Gym app following this tutorial https://www.youtube.com/watch?v=Mag1n3MFDFk&list=PL2aJidc6QnyOe-fp1m4yKHjcInCRTF53N&index=3 I wanted to write a form page that the user (once logged in) can fill and become a subscriber. In the tutorial he used a new model Enrollment to fill the data with but I have a model Pretplatnik (Subscriber in english) that has a OneToOne relationship with django user model. Also two other models that are FK to Pretplatnik for Plan that the user can subscribe to and a model for Trainer that the user can choose. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Oznaka(models.Model): naziv = models.CharField(max_length=200) def __str__(self): return self.naziv class Plan(models.Model): naziv=models.CharField(max_length=150) cijena=models.IntegerField() max_clanova=models.IntegerField(null=True) oznake=models.ManyToManyField(Oznaka, default=None, blank=True, related_name='oznake') def __str__(self): return '%s' % self.naziv class Trener(models.Model): ime=models.CharField(max_length=150) image=models.ImageField(upload_to='static/assets/img/team', default=None) def __str__(self): return self.ime class Pretplatnik(models.Model): korisnik=models.OneToOneField(User, on_delete=models.CASCADE) trener=models.ForeignKey(Trener, on_delete=models.CASCADE, related_name='pretplatnici') plan=models.ForeignKey(Plan, on_delete=models.CASCADE, null=True) datum_r=models.DateField(blank=True,null=True) spol=models.CharField(max_length=25, default=None) adresa=models.CharField(max_length=150) def __str__(self): return str(self.korisnik) class Pretplata(models.Model): pretplatnik=models.ForeignKey(Pretplatnik, on_delete=models.CASCADE, null=True) plan=models.ForeignKey(Plan, on_delete=models.CASCADE, null=True) class CustomModelName(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) from django import forms from django.forms import ModelForm from teretana.models import * class PretplatnikForm(forms.ModelForm): plan = forms.ModelChoiceField(queryset=Plan.objects.all(), to_field_name = 'naziv', empty_label="Select Plan") trener = forms.ModelChoiceField(queryset=Trener.objects.all(), to_field_name = 'ime', empty_label="Select Trainer") class Meta: … -
Does uWSGI terminate processes when the nginx client disconnects?
My stack is Django + uWSGI + NGINX. We have certain client requests that can take a really long time to fulfill, and we're trying to optimize our timeouts for different endpoints depending on their estimated processing time. I can do this in NGINX using location blocks, but uWSGI's harakiri setting is application-wide and doesn't discriminate between endpoints. My question is, if I set the NGINX timeout for an endpoint to 30s, but uWSGI has a harakiri timeout of 60s, will the application keep working until that 60s is reached, regardless of client timeout at 30s? For some more context, here's an example from our NGINX config: location /example/path { if ($http_x_forwarded_proto != "https") { return 301 https://$server_name$request_uri; } include /sites/example/confs/server/nginx_redirects.conf; send_timeout 30; uwsgi_pass unix:///tmp/example.com.sock; uwsgi_read_timeout 30; include uwsgi_params; include /etc/nginx/proxy/nginx_proxy.conf; } -
ImportError: cannot import name 'Client' from 'plaid'
I have been struggling to find an answer. I am trying to integrate plaid with my django project, however I continue to get the same error. I am on python 3.11 and plaid 19.0.0. The plaid package in in my python site packages where it shows: ImportError: cannot import name 'Client' from 'plaid' (/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/plaid/__init__.py) And the init.py file is: """ The Plaid API The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501 The version of the OpenAPI document: 2020-09-14_1.496.2 Generated by: https://openapi-generator.tech """ __version__ = "19.0.0" # import ApiClient from plaid.api_client import ApiClient # import Configuration from plaid.configuration import Configuration # import Environments from plaid.configuration import Environment # import exceptions from plaid.exceptions import OpenApiException from plaid.exceptions import ApiAttributeError from plaid.exceptions import ApiTypeError from plaid.exceptions import ApiValueError from plaid.exceptions import ApiKeyError from plaid.exceptions import ApiException Any help would be greatly appreciated -
The Paginator is not displaying on home page
When I open the home page the paginator is not displaying. And I couldn't fix this issue. I tried these codes, and I couldn't fix this issue. Please help me to fix this issue Codes on views.py from django.core.paginator import Paginator, EmptyPage, InvalidPage def home(request, c_slug=None): c_page = None prodt = None if c_slug != None: c_page = get_object_or_404(Categ, slug=c_slug) prodt = Products.objects.filter(category=c_page, available=True) else: prodt = Products.objects.all().filter(available=True) cat = Categ.objects.all() paginator = Paginator(prodt, 4) try: page = int(request.GET.get('page', '1')) except: page = 1 try: products = paginator.page(page) except (EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request, 'index.html', {'ct': cat, 'pr': products}) Codes on Index.html <div class="row flex px-xl-5"> {% for i in pr.object_list %} <div class="col-lg-3 col-md-4 col-sm-6"> <div class="product-item bg-light mb-4"> <div class="product-img position-relative overflow-hidden"> <a href="{{i.get_url}}"><img class="img-fluid w-100" src="{{i.img.url}}" alt="" style="height:250px; width:500px;"> </a> </div> <div class="text-center py-4"> <a class="h6 text-decoration-none text-truncate" href="{{i.get_url}}">{{i.name}}</a> <p>{{i.des|truncatechars:80}}</p> <div class="d-flex align-items-center justify-content-center mt-2"> <h5>RS {{i.price}}</h5><h6 class="text-muted ml-2"><del>RS 123.00</del></h6> </div> <p>Stocks left: {{i.stock}}</p> <div class="d-flex align-items-center justify-content-center mb-1"> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small>(99)</small> </div> </div> </div> </div> {% endfor %} </div> <div class="mx-auto"> … -
A navbar cant't recognize a static file in my Django project
I want to use a CSS style in a static file for a navbar but it is not recognized and i get an error: Not Found: /favicon.ico [04/Mar/2024 17:57:46] "GET /favicon.ico HTTP/1.1" 404 3581 [04/Mar/2024 18:17:46] "GET /list?page=1 HTTP/1.1" 200 1374 views py: class ListFeedBack(ListView): template_name = 'feedback/list_feedback.html' model=Feedback paginate_by = 2 list_feedback.html: {% extends 'feedback/base.html' %} {% block content %} {% load static %} <h2>Все отзывы</h2> <table> <tr> <th>Номер</th> <th>Имя</th> <th>Фамилия</th> <th>Отзывы</th> <th>Рейтинг</th> </tr> {% for i in object_list %} <tr> <th><a href="{{i.get_url}}">{{i.id}}</a></th> <th>{{i.name}}</th> <th>{{i.surname}}</th> <th>{{i.feedback}}</th> <th>{{i.rating}}</th> </tr> {% endfor %} </table> {% endblock %} {% block navbar %} <nav class="list-pages"> <ul> {% for p in paginator.page_range %} <li class="page-num"> <a href="?page={{p}}">{{p}}</a> </li> {% endfor %} </ul> </nav> {% endblock %}` Note: i also use base.html with empty navbar block base.html: `<!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title> {% block title %} {% endblock %} </title> <link rel="stylesheet" href=" {% static 'feedback/field.css' %}"> </head> <body> {% block content %} {% endblock %} <link rel="stylesheet" href=" {% static 'feedback/table.css' %}"> {% block navbar %} {% endblock %} </body> </html> Note: it tried to use with favicon direction but i get the same error. urls.py: from … -
Django App not returning csrf token on get response.cookie consistently
Given I have this GET view: class PublicKeyView(View): def get(self, request): # Ensure a session ID is available if not request.session.session_key: request.session.save() session_id = request.session.session_key private_key, public_key = RSAKeyManager.get_keys(session_id) if not private_key or not public_key: # Keys are generated as bytes, so decode them before storing private_key, public_key = RSAKeyManager.generate_keys() RSAKeyManager.store_keys(session_id, private_key.decode('utf-8'), public_key.decode('utf-8')) if isinstance(public_key, bytes): public_key = public_key.decode('utf-8') print(public_key) # public_key = public_key.replace('\n', '') # Return the public key and session ID return JsonResponse({"session_id": session_id, "public_key": public_key}, status=200) And this settings.py Django settings for django_backend project. Generated by 'django-admin startproject' using Django 5.0.2. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path from utils.utils import get_secrets # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-&sru-aw9zw@2t*hyy7eh&ynb5buu(tw_sd7=xsgt(+6bi5&h4f" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['eliptum.tech'] CSRF_TRUSTED_ORIGINS = ['https://eliptum.tech'] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "backend_app" ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", … -
Django Nginx Unable to serve Static Files
Nginx won't serve my Django static files while gunicorn serves as expected. I have my settings as: STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') while my nginx.conf has: events {} http { server { listen 80; server_name 127.0.0.1 cloud101.dev www.cloud101.dev; # Correctly point to your static files directory # root /usr/src/app/staticfiles; location /static { root /usr/src/app/staticfiles; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } the Dockerfile has: # pull the official base image FROM python:3.12.2-bullseye ... # Install Nginx and dependencies RUN apt-get install -y nginx # copy project COPY . /usr/src/app COPY website/nginx.conf /etc/nginx/nginx.conf EXPOSE 8000 RUN python manage.py collectstatic -v 2 --noinput CMD ["gunicorn", "--bind", "0.0.0.0:8000", "website.wsgi:application"] gunicorn serves alright but the static files are not served although the default server does. What am I missing? -
Django GenericForeignKey for ManyToMany relationship
I'd like to enable the use of tags on different entities of my database, which have nothing to do with each other. For this, I used the GenericForeignKey and the ContentType django framework. For example, I have the 2 followings entities and the Tag class: class Tag(models.Model): name = models.CharField(max_length=100) content_type = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = GenericForeignKey("content_type", "object_id") class Entity1 (models.Model): ... tags = GenericRelation(Tag, related_query_name="entity1") class Entity2 (models.Model): ... tags = GenericRelation(Tag, related_query_name="entity2") However, this design only allows to use one tag to be used for one entity, I would like a ManyToMany relationship between my Tag and the different EntityX objects. What would be the best design to achieve this ? -
why does floatformat:2 adds a comma after the hundred place
I have a Django project and I have a {{account.current_balance}} tag in my HTML. I also included the type of data it is just in case it matters. I understand #1 and #2, but I don't understand why with #3, adding intcomma would add a comma after the hundred place. Tag without floatformat or intcomma {{ account.current_balance }} output: Current Balance - Type 303.6000000000000 - Decimal Tag with floatformat:2 {{ account.current_balance|floatformat:2 }} output: Current Balance - Type 303.60 - Decimal Tag with floatformat:2 with intcomma {{ account.current_balance|floatformat:2|intcomma }} output: Current Balance - Type ,303.60 - Decimal -
Prevent Cookie Sharing across sub-domains
Is there a way to prevent the cookie sharing on subdomains Following is my session cookie domain DJANGO_COOKIE_DOMAIN=.dev.fox.com and my set_cookie() method sets the cookie even for subdomains like e.g: abc.fox.dev.com. NOTE: I am getting this token via Firebase authentication. I want to create an isolation , that if a user is logged in on app.dev.fox.com , cookies must be set on app.dev , but unfortunately it is set on all domains ending on .dev.fox.com how to prevent this ? -
Using MagicMock in Production Code, rather than refactoring the whole code base?
Is it an acceptable practice to use MagicMock in deployement code in Production rather than using some other way? Basically I have created a central function which is being used in a lot of places, lets call it foo(). Then there are other functions, let's call them bar() and baz() which are calling the function foo() to set some property values. Now, what I want to do is write another function, let's call it temp(), which calls bar(), but I want to set the value returned by foo(), to return a specific value if it called from temp(), but return a proper computed value if called from any other place which call the function bar() or baz(). (Note that the number of layers defined here is kept simple for example, in reality there are a lot of functional levels). What I am trying to find is a quick hack fix, so as to not refactor a lot of codebase to get through a proper solution. -
Vercel deployment with django
I'm trying to deploy my django app on Vercel but it isn't working, this is my vercel.json code: { "version": 2, "functions": { "core/wsgi.py": { "runtime": "vercel-python@9.8.1" }, "build_files.sh": { "runtime": "@vercel/static-build" } }, "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "core/wsgi.py" } ] } It's raising this error: Error: Function Runtimes must have a valid version, for example now-php@1.0.0. Can someone help me? Please -
Make Cart Session in Django
More than one product cannot be added to the cart. After adding a product, it cannot be changed in the shopping cart. from django.shortcuts import render, redirect, get_object_or_404 from django.views import View from .cart_madule import Cart from Product.models import Product class CartDetailView(View): def get(self, request): cart = Cart(request) return render(request, 'Cart/cart.html', {'cart': cart}) class CartAddView(View): def post(self, request, pk): product = get_object_or_404(Product, id=pk) flavor, weight, quantity = request.POST.get('flavor'), request.POST.get('weight'), request.POST.get('quantity') cart = Cart(request) cart.add(product, flavor, weight, quantity) return redirect('Cart:cart_detail') Cart_Session_Id = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(Cart_Session_Id) if not cart: cart = self.session[Cart_Session_Id] = {} self.cart = cart def __iter__(self): cart = self.cart.copy() for item in cart.values(): product = Product.objects.get(id=int(item['id'])) item['product'] = product item['total'] = int(item['quantity']) * int(item['price']) yield item def unique_id_generator(self, id, flavor, weight): result = f'{id}-{flavor}-{weight}' return result def add(self, product, quantity, flavor, weight): unique = self.unique_id_generator(product.id, flavor, weight) if unique not in self.cart: self.cart[unique] = {'quantity': 0, 'price': str(product.Price), 'weight': weight, 'id': str(product.id), 'flavor': flavor} else: self.cart[unique]['quantity'] += int(quantity) self.save() def save(self): self.session.modified = True -
Django 3 url - view must be a callable or a list/tuple in the case of include()
I am beginner in Python and Django. I migrate project from 2.x to 3. I have this code: urlpatterns += [ url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ] and this code return me error: url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { File "/mnt/c/Projekty/GO/.venvs/lib/python3.9/site-packages/django/conf/urls/__init__.py", line 22, in url return re_path(regex, view, kwargs, name) File "/mnt/c/Projekty/GO/.venvs/lib/python3.9/site-packages/django/urls/conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). How can i repair it? Please help me -
Troubleshooting Dynamic Image Updating and Color-Based Filtering in Django Product.html page
I have created a hyperlink in html So, In product_detail_page.html: <div class="product-color"> <span>Color</span> {% for c in colors %} <div class="color-choose"> <a href="?colorID={{c.id}}" style="display: inline-block; width: 40px; height: 40px; background-color: {{c.code}}; border-radius: 50%; border: 2px solid #FFFFFF; cursor: pointer; float: left; margin-right: 10px; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.33);"> </a> </div> {% endfor %} </div> Now it is taking colors id (suppose if I click on red color it is taking {?colorID=1} in url) Now I created a view for this That if I Click in a color it will change the product Image So, In views.py def product_detail_view(request,pid): product=Product.objects.get(pid=pid) colors = Color.objects.all() sizes= Size.objects.all() p_image=product.p_images.all() products=Product.objects.filter(cagtegory=product.cagtegory) ColorID=request.GET.get('colorID') if ColorID: product=Product.objects.filter(color=ColorID) else: product=Product.objects.all() context={ "p":product, "p_image":p_image, 'colors': colors, 'sizes': sizes, 'products': products, } return render(request,"core/product_detail.html",context) and I created this models in models.py class Color(models.Model): name=models.CharField(max_length=20) code=ColorField(default='#FF0000') def __str__(self): return self.name class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): … -
Is there a way to run multiline python scripts on the traditional interactive shell like shell plus?
I have to run python scripts on an old server which serves a django app, eveytime I'm running the commands line by line, I want to be able to paste the script or set of commands all at once like shell plus django extension, is there a way? for example, I want to paste the code below all at once, like I do in shell plus djnago extension. fields = ['id', "name"] rows = article_list filename = "articles_with_highlighted_text_v2.csv" with open(filename, 'w', newline='') as csvfile: csvwriter = csv.writer(csvfile) csvwriter.writerow(fields) csvwriter.writerows(rows) Thanks. I've tried a google search but unfortunately haven't been able to find any tricks to be able to run the script all at once on the python shell. -
Page not found (404): The current path, calendars/event/1/details, didn’t match any of these
admin/ accounts/ calendars/ add/ [name='calendar_add'] calendars/ <int:calendar_id>/events/add/ [name='event_add'] calendars/ event/<int:event_id>/details/ [name='EventDetailsView'] calendars/ <int:calendar_id>/events/all/ [name='EventListView'] calendars/ <int:calendar_id>/details/ [name='CalendarDetailView'] The current path, calendar/event/1/details, didn’t match any of these. In my urls.py in calendar app it is working for all other urls: app_name = 'calendars' urlpatterns = [ path('add/', login_required(CalendarCreateView.as_view()), name='calendar_add'), # working path('<int:calendar_id>/events/add/', login_required(EventCreateView.as_view()), name='event_add'), # working path('event/<int:event_id>/details/ ', EventDetailsView.as_view(), name='EventDetailsView'), #NOT working # path('event/1/details/ ', EventDetailsView.as_view(), name='EventDetailsView'), # path('<int:calendar_id>/details/', login_required(calendar_details.as_view()), name='details'), path('<int:calendar_id>/events/all/', EventListView.as_view(), name='EventListView'), # working path('<int:calendar_id>/details/', CalendarDetailView.as_view(), name='CalendarDetailView'), # working ] and the view for this is : class EventDetailsView(FormView): def get(self, request, event_id): # # Check if the event exists # Check if the request is authenticated if request.user.is_authenticated: # event = request.event event = get_object_or_404(Event, id=event_id) # Return full event details if authenticated data = { "id": event.id, "name": event.name, "description": event.description, "date": str(event.date), "start_time": str(event.start_time), "duration": event.duration, "last_modified": str(event.last_modified) } return JsonResponse(data) where I am trying to return the info of a specific event with fields: id, name, description, date, start_time, duration, last_modified Here is just the authenticated part of the view. This view for unauthenticated requests, the name and description values should be changed to empty strings. Also, if the given ID is not associated with … -
how to make download link inside excel auto save
I was trying to make excel file using openpyxl v3.1.2 in Django, Python v3.9, the excel file contains link displayed as 'Click Here', those are links to files, despite the links are open correctly, but they are not save into the machine.. I mean they open in browser, or in the suitable program, but they are not saved (downloaded) into my machine. How to make them downloaded directly into my machine, like when u download file from internet. here is my code: #views.py def export_applicants_xls(request, pk, applicant_id=None): job = get_object_or_404(Job, pk=pk) if applicant_id: candidate_list = Applicant.objects.filter(job=pk, pk=applicant_id) else: candidate_list = Applicant.objects.filter(job=pk) if not candidate_list: messages.error(request, _('No applicants for this job'), 'danger') return redirect('employer-job-detail', pk=pk) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') if applicant_id: response['Content-Disposition'] = f'attachment; filename=applicant_{applicant_id}_details.xlsx' else: response['Content-Disposition'] = f'attachment; filename=all_applicants_#{job.slug}.xlsx' wb = Workbook() ws = wb.active ws.title = 'Applicants' # Set header row in bold header_font = Font(bold=True) columns = [ 'CV File', 'ID card', 'Tawjihi file', 'University File', 'Experience File', 'Master file', 'Profession', 'Injury Insurance', 'Membership File', 'Temporary Membership'] for col_num, column in enumerate(columns, 1): cell = ws.cell(row=1, column=col_num, value=column) cell.font = header_font ws.column_dimensions[get_column_letter(col_num)].width = 15 # Adjust column width # Populate data rows for row_num, applicant in enumerate(candidate_list, 2): row_data … -
Search results are not showing. And my URL Tab shows: "http://127.0.0.1:8000/search?" instead of this: "http://127.0.0.1:8000/search?q=name"
Codes on views.py def searching(request): prod = None query = None if 'q' in request.GET: query = request.GET.get('q') prod = Products.objects.all().filter(Q(name__contains=query) | Q(des__contains=query)) return render(request, 'search.html', {'qr': query, 'pr': prod}) Codes on urls.py urlpatterns = [ path('', views.home, name='hm'), path('<slug:c_slug>/', views.home, name='prod_cat'), path('<slug:c_slug>/<slug:product_slug>', views.prodetails, name='details'), path('search', views.searching, name='searching'), ] Codes on search.html <div class="row flex px-xl-5"> {% for i in pr %} <div class="col-lg-3 col-md-4 col-sm-6"> <div class="product-item bg-light mb-4"> <div class="product-img position-relative overflow-hidden"> <a href="{{i.get_urls}}"><img class="img-fluid w-100" src="{{i.img.url}}" alt="" style="height:250px; width:500px;"> </a> </div> <div class="text-center py-4"> <a class="h6 text-decoration-none text-truncate" href="{{i.get_url}}">{{i.name}}</a> <p>{{i.des|truncatechars:80}}</p> <div class="d-flex align-items-center justify-content-center mt-2"> <h5>RS {{i.price}}</h5><h6 class="text-muted ml-2"><del>RS 123.00</del></h6> </div> <p>Stocks left: {{i.stock}}</p> <div class="d-flex align-items-center justify-content-center mb-1"> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small>(99)</small> </div> </div> </div> </div> {% endfor %} </div> Codes on base.html <div class="col-lg-4 col-6 text-left"> <form action="{% url 'searching' %}" method="get"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search for products"> <div class="input-group-append"> <span class="input-group-text bg-transparent text-primary"> <i class="fa fa-search"></i> </span> </div> </div> </form> </div> Actually, my problem is that when I search for a product, on the URL tab, it should be shown … -
Cannot resolve keyword 'calendar_id' into field. Choices are: description, end_date, event, id, name, owner, owner_id, start_date
Here is the code where I define the Event and Calendar models: class Calendar(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) start_date = models.DateField() end_date = models.DateField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) date = models.DateField( ) start_time = models.TimeField() # Example default time duration = models.DurationField() # Example default duration of 1 hour calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE) # owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name Here is the view I am trying to use: class EventListView(LoginRequiredMixin, ListView): model = Event template_name = 'list.html' context_object_name = 'EventListView' def get_queryset(self): calendar_id = self.kwargs['calendar_id'] return Calendar.objects.filter(calendar_id=calendar_id) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if not self.request.user.is_authenticated: for event in context['EventListView']: event.name = '' return context I have another similar view that looks like this, also using the calendar_id and this view works fine. I am not sure why the EventListView is showing this error. class CalendarDetailView(DetailView): model = Calendar template_name = 'calendars/detail.html' context_object_name = 'calendar' pk_url_kwarg = 'calendar_id' def get_queryset(self): return Calendar.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context -
Django Auth fails, even if user/pass exist in DB
Given I have this create user view class UserView(View): def post(self, request): try: data = json.loads(request.body) encrypted_username_hex = data.get('username', None) encrypted_password_hex = data.get('password', None) phone_number = data.get('phone_number', None) email = data.get('email', None) missing_fields = [field for field in ['username', 'password', 'email'] if data.get(field) is None] if missing_fields: return JsonResponse({"error": f"Missing required field(s): {', '.join(missing_fields)}"}, status=400) session_id = request.session.session_key print("user create ses", session_id) private_key_pem, _ = RSAKeyManager.get_keys(session_id) if not private_key_pem: return JsonResponse({"error": "Invalid session or RSA keys not found"}, status=404) print("private key", private_key_pem) username = RSAHandler.decrypt_from_hex(private_key_pem, encrypted_username_hex) password = RSAHandler.decrypt_from_hex(private_key_pem, encrypted_password_hex) user = CustomUser.objects.create_user(username=username, email=email, password=password, phone_number=phone_number) return JsonResponse({"user": user.email, "phone_number": user.phone_number}, status=201) except IntegrityError as e: if 'username' in str(e): return JsonResponse({"error": "This username is already taken."}, status=400) elif 'email' in str(e): return JsonResponse({"error": "This email is already in use."}, status=400) else: return JsonResponse({"error": "There was an error with your request."}, status=400) except ValidationError as e: return JsonResponse({"error": str(e.messages[0])}, status=400) except Exception as e: traceback.print_exc() return JsonResponse({"error": "Internal server error."}, status=500) And this custom user model: class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None, phone_number=None, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(username=username, email=email, phone_number=phone_number, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, …