Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why i get 'NoneType' object has no attribute 'quantity' this error in my code
I want to subtract product quantity to user_give_quantity . But it has show these types of error 'NoneType' object has no attribute 'quantity' class Order(models.Model): item_name = models.CharField(max_length=255, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=True) distribute_price = models.IntegerField(null=True) mrp_price = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) user_give_quantity = models.IntegerField(null=True, blank=True) user_price = models.IntegerField(null=True, blank=True) def __str__(self): return self.item_name def total_price(self): return self.mrp_price * self.user_give_quantity def available_quantity(self): return self.product.quantity - self.user_give_quantity -
django what happends if I bulk_update values which are not changed?
So I have a function like this, which bulk-updates a many-many field for the parent_object with the given data. The problem is, not every object given in the data parameter will have its position changed. So, What will happen if I tell django to bulk_update values whose positions aren't changed already? Will any exceptions be raised? For instance, let the list of objects in a many-many field be: [id=1'blue', id=2'green', id=3'yellow'] If I tell django to update these values like [id=1 update to 'blue', id=2 update to 'purple', id=3 update to 'magenta'] will any errors occur? def overwrite_object_positions(self, data: list, parent_object): """ Overwrites object-positions, enclosed within a transaction. Rolls-back if any error arises. """ transaction.set_autocommit(False) try: self.get_overwrite_objects(parent_object).bulk_update(data, ['position']) except Exception as err: transaction.rollback() raise ValueError(err) else: transaction.commit() finally: transaction.set_autocommit(True) -
nested serialize Django object
hi guys i want to serialize my model's object. and my model like this : class User (models.Model): name = models.CharField(max_length=30) family_name = models.CharField(max_length=30) and i have another model like this: class Child (models.Model): little_name = models.CharField(max_length=30) user = models.ForeignKey("User", on_delete=models.CASCADE,) i want to serialize one of my child object with all fields in user field for example like this: {"id": 1 , "little_name": "Sam", "user": {"id": 1, "name": "Karim", "family_name":"Kari" } } i use model_to_dict() and dict() and serializer of django but i can't get user field compeletly and they return it like this : {"id": 1 , "little_name": "Sam", "user": "id": 1, } and i don't want to use django rest serializer what can i do ?!? -
Getting This Error : TemplateDoesNotExist at post/1/
Can anyone please help me with this error when i am trying to access the page it shows this error Exception Type: TemplateDoesNotExist Exception Value: firstblog/post_detail.html Exception Location: C:\Users\ADMIN\Envs\test\lib\site-packages\django\template\loader.py, line 47, in select_template views.py class PostDetailView(DetailView): model = Post url.py urlpatterns = [ path('',PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('about/',views.about, name='blog-about'), ] -
Is it possible to create SQLite Triggers, Procedures, Views in Django?
I am working on my DBMS college Project. I am using Django to create an event management website, my teacher told me to also add Triggers, Views, and Procedures to my website but I don't know how to do it. Please tell me how to write SQLite Triggers, Procedures, Views in a Django Project. -
Django Save generated pdf from django-renderpdf
I'm using this package to generate pdf files and it works like a charm. Now I have to send the generated file per email and I'm wondering how to automatically save the generated file on a specific path or sending directly per email. The problem is not sending the email, but how to get the content of the pdf to save it or to send it. Here what I have so far: from django_renderpdf.views import PDFView class InvoiceSpecification(PDFView): template_name = 'reports/invoice/specification.html' prompt_download = True @property def download_name(self) -> str: invoice = Invoice.objects.get(pk=self.kwargs['pk']) return f"WeeklyMetre_{invoice.invoice_number}.pdf" def get_context_data(self, **kwargs): context = super(InvoiceSpecification, self).get_context_data(**kwargs) mlss = MarketLaborSpecification.objects.filter(invoice_id=self.kwargs.get('pk')).order_by('specification__category', 'specification__position') market_labor_specifications = {} for mls in mlss: if mls.specification.category.name not in market_labor_specifications.keys(): market_labor_specifications[mls.specification.category.name] = [] if not any(d.get('position', 'bla') == mls.specification.position for d in market_labor_specifications[mls.specification.category.name]): market_labor_specifications[mls.specification.category.name].append( { 'position': mls.specification.position, 'name': mls.specification.name, 'validated': mls.validated_quantity, 'invoice_price': mls.invoice_price } ) else: for d in market_labor_specifications[mls.specification.category.name]: if d['position'] == mls.specification.position: d['validated'] += mls.validated_quantity break invoice = Invoice.objects.get(pk=self.kwargs.get('pk')) context.update({ 'page_title': _('Incoice overview: {}'.format(invoice)), 'invoice': invoice, 'market_labor_specifications': market_labor_specifications, }) return context The template is a simple html file. Any help will be appreciated ;) -
I wanted to create a google classroom like thing with python [closed]
Actually, I wanted to create a google classroom like thing (not with all the features just video conferencing) with python on web. I searched for it a lot but could not find out anything. Please help me out with this and plz send a sample code if you can. ASAP!!!!! -
How I can store api keys in django tenants app
I am facing a problem to store apikeys for django tenant application, where each subdomain owners need to have payment processing, so is ther any way owners can add their keys without the help of developers, when they create a new domain. I tried to store in db on shared app and called but the out put is empty for tenant users, but getting the value printed in main domain. from accounts.models import ExternalKeys api_key = ExternalKeys.objects.all().order_by('pk').first().secret_key try: print(api_key) except: pass -
For loop not working in python shell while inputting data in sqlite Db
For loop not working to input data from a python df column to a django model, i have used similar techniques in the past but this time the loop only iterates once, i tried checking the colist and it prints list of cos perfectly, doesnt seem to work inside the loop. Help would be much appreciated. import pandas as pd from Main.models import ServiceCos df = pd.read_csv('Assets/SERVICESdf.csv') colist = df['Company Name'] cos_list = df['Symbol'] for c in colist: s = ServiceCos(company_N_ser=c) #company_N_ser is the field name s.save() -
Django Internationalization sımple question
Hello guys i've a simple question for django. I have a model like this: Link_tr Link_en Link_fr And at template i want to use like this: {{pk1.Link_{{LANGUAGE_CODE}}}} but django dont accept. I hope someone can solve my problem. -
cx_Oracle.DatabaseError: DPI-1013: not supported
0 I am trying to run a code to create tables in oracle database.I am using Python 3.9.0 and Oracle Database 10g Express Edition Release 11.2.0. in windows 64 bit. -
How can I use multible images for Django product model?
I want to create a online shop website in Django and I don't know how to make a model of product that can have many images. For example it can contain 0, 5 or even 50 Images. I don't want to write spagetti code with 10 image fields with blank=True + null=True. And by searching on the internet I have not found anything that can help me. So please just don't send other stackoverflow question. Also I will add a new product from Admin page not from templates :) hope this question is gonna be answered! -
Django fetch latest matching rows for each entity
I'm using Django. My tables look like that: class Person: id = ... name = ... city = models.TextField(null=False) class Picture: id = .... date_captured = models.DateTimeField() Person = models.ForeignKey(Person, related_name='+', null=False, on_delete=models.CASCADE) I want to fetch for each person from the city XXX all the images from the latest date their image was taken. For example: If person A from city XXX had his pictures taken on July 10, 12, 14 And person B from city XXX had his pictures taken on July 6, 10, 19 And person C from city YYY had his pictures taken on July 1, 5, 25 Then I want to fetch for person A all his images from July 14 (NOTE that there can be multiple images of person A from the 14th, and I need all of them), and for person B all of his images from July 10, and ignore Person C since he is not from city XXX. How can this be done -
customizing registration django fields
i am trying to make my own blog, and every blog have a registration template, when it comes to customizing it in my template i did it all wrong so please help template.html: <form action="" method="post"> {% csrf_token %} <label for="username">Username</label><br> {{forms.username}} <br> <label for="email">Email</label><br> {{forms.email}}<br> <label for="password1">Password</label><br> {{forms.password1}} <br> <label for="password2">Confirm Password</label><br> {{forms.password2}} <br> {% if forms.errors %} {% for field in forms %} {% for error in field.errors %} <h5 style="color: red;">{{ error|escape }}</h5> {% endfor %} {% endfor %} {% for error in forms.non_field_errors %} <h5 style="color: red;">{{ error|escape }}</h5> {% endfor %} {% endif %} <br> <input type="submit" value="Register"> </form> my forms.py: class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_username(self): username = self.cleaned_data.get("username") if User.objects.filter(username=username).exists(): raise forms.ValidationError("Username is not unique") return username def clean_email(self): email = self.cleaned_data.get("email") if User.objects.filter(email=email).exists(): raise forms.ValidationError("Email is not unique") return email my views.py: def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() else: form = RegisterForm() context = {'forms':form} return render(request, 'register/register.html', context) i dont know how to edit my template to have a customized registration form. thank you<3 -
dramatiq: Requested setting INSTALLED_APPS, but settings are not configured
I have following code structure manage.py src/ invoices/ helpers/ invoce_worker.py (def retrieve_invoices - dramatiq task) I run dramatiq task using dramatiq --watch . src.invoices.helpers.invoice_worker and get following error [2020-12-26 12:56:02,331] [PID 32562] [MainThread] [dramatiq.MainProcess] [INFO] Dramatiq '1.9.0' is booting up. [2020-12-26 12:56:02,348] [PID 32562] [MainThread] [dramatiq.MainProcess] [CRITICAL] Worker with PID 32565 exited unexpectedly (code 1). Shutting down... Process Process-1: Traceback (most recent call last): File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/home/m0nte-cr1st0/.virtualenvs/sortif-backend/lib/python3.8/site-packages/dramatiq/cli.py", line 330, in worker_process module, broker = import_broker(args.broker) File "/home/m0nte-cr1st0/.virtualenvs/sortif-backend/lib/python3.8/site-packages/dramatiq/cli.py", line 120, in import_broker module, broker = import_object(value) File "/home/m0nte-cr1st0/.virtualenvs/sortif-backend/lib/python3.8/site-packages/dramatiq/cli.py", line 109, in import_object module = importlib.import_module(modname) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "./src/invoices/helpers/invoice_worker.py", line 5, in <module> from src.invoices.helpers.invoices_filter import get_unfiltered_invoices File "./src/invoices/helpers/invoices_filter.py", line 5, in <module> from src.mails.models import MailAttachment File "./src/mails/models.py", line 7, in <module> from src.prest_jwt_auth.models import ClientEmail File "./src/prest_jwt_auth/models.py", line 5, in <module> class Plan(models.Model): File "/home/m0nte-cr1st0/.virtualenvs/sortif-backend/lib/python3.8/site-packages/django/db/models/base.py", … -
What is the most elegant or Pythonic way to initialise a Django object?
I am new to Python and Django but feel like there must be a neater way of accomplishing this than I have found. I have a Django model that has a date attribute with a non-trivial default value, meaning that I need a little bit of logic to set it up. I have tried several ways of doing this, but unfortunately this is the only one that has worked for me so far (in models.py within a weeks app): def first_day_of_next_week(): return timezone.now().date() - datetime.timedelta(days=timezone.now().date().weekday() + datetime.timedelta(days=7) class Week(models.model): start_of_week = models.Datefield('Date of the first day of the week', unique=True, default=first_day_of_next_week()) I strongly dislike having a function floating outside of any class like that (but don't have the experience to know whether it is actually bad). I have tried incorporating it into a static or class method, or within an __init__ process within Week, but can't get any of those approaches to work properly (in particular, Django seems to complicate hijacking __init__). Now that I have the Week model working, I want to instantiate weeks with Week.objects.get_or_create() from views.py, but here I hit the problem that I need the same first_day_of_next_week() logic to be accessible within views.py. (This is what … -
csrf verification failed even after using the token
{% extends 'base.html' %} {% block content %} <form action="add" method="POST"> {% csrf_token %} Enter a number : <input type="number" name="num1" required/><br /> Enter another number : <input type="number" name="num2" required/> <input type="submit" /> </form> {{result}} {{res}} {% endblock %}`` i have just started learning django. why i still get csrf verification failed when i have included the token in the form? -
Unble to use the working Django modles for index.html page ( Modles data entried in admin page but not visible in index.html page)
I have created modles in modles.py as below: class Title(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title , migrate successfully, later on, registered the moodle in admin.py as admin.site.register(Title), But the issue is I can see in admin pannel that modles created and upadted the data but in index.html page, I used as {{Title.title}} which seems not working. Need help ????? Do i need to create views and what I should types in views.py -
Not able to register through frontend. Keeps saying Bad Request
I am trying to build a basic authentication website using DJANGO and REACT. But there seems to be a problem in communication between frontend and backend. I have built a Rest API using DJANGO REST FRAMEWORK and authentication using KNOX whose code is as follows: # api.py from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer, LoginSerializer # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Login API class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Get User API class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user # serializers.py from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate # User serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( validated_data['username'], validated_data['email'], validated_data['password'] ) … -
How to let Django automatically provoke Celery's beat?
Currently, whenever I need to run my Django + Celery, I would need to do the following two commands: python manage.py runserver celery -A celery beat -l INFO This is a bit annoying. If my Django app cannot automatically run Celery beat, then what is the point of these two lines in the __init__.py ? from __future__ import absolute_import from .celery import app as celery_app Sorry, I just start learning Celery. Some of its aspect was not very clear to me. -
django rest framework know if view is class or function
I was implementing my custom permission where I had to check if view is function or class. I have done the following def has_permission(self, request, view): print("request ===", view, inspect.isfunction(view), inspect.isclass(view)) Here both inspect.isfunction(view), inspect.isclass(view) gives me false. How can I determine if a view is functin or class ?? -
getting error no such column: mains_profile_friends.user_id
I am going through a Django tutorial and getting this error when trying to open friends page in browser( In local Host ) in my blog app. I use Django==3.1.2. views.py @login_required def friend_list(request): p = request.user.profile friends = p.friends.all() context = {'p':p,'friends':friends} return render(request, 'mains/friends.html' , context ) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') friends = models.ManyToManyField(User, related_name='friends',blank=True,default='',null=True) friends.py {% block content %} <div class="container"> <div class="row"> <div class="col-md-8"> {% if friends %} <div class="card card-signin my-5"> <div class="card-body"> {% for user_p in friends %} <a href="{{ user_p.get_absolute_url }}">{{ user }}</a> <a class="text-dark" href="{{ user_p.get_absolute_url }}" ><b>{{ user_p }}</b></a> <small><a class="btn btn-danger float-right" href="{% url 'mains:delete_friend' user_p.id %}" >UnFriend</a></small> <br /><br /> {% endfor %} {% endif %} {% endblock content %} urls.py path('friends/', views.friend_list, name='friend_list'), The Problem When i open friends.html in browser it is giving me an error :- no such column: mains_profile_friends.user_id. What i have tried. 1). I have replaced all the names related to friend_list view. 2). I have also migrated in Terminal. Help me in this !! I will really appreciate your Help. Thank you in Advance. -
Signaling a long running Huey task to stop
I'm using Huey to perform some processing operations on objects I have in my Django application. @db_task() def process_album(album: Album) -> None: images = album.objects.find_non_processed_images() for image in images: if album.should_pause(): return process_image(album, image) This is a simplified example of the situation I wish to solve. I have an Album model that stores a various number of Images that are required to be processed. The processing operation is defined in a different function that s wrapped with @task decorator so it'll be able to run concurrently (when the number of workers > 1). The question is how to implement album.should_pause() in the right way. Current implementation looks like this: def should_pause(self): self.refresh_from_db() return self.processing_state != AlbumProcessingState.RUNNING Therefore, on each iteration, the database is queried to update the model, to make sure that state field didn't change to something other than AlbumProcessingState.RUNNING, which would indicate that the album processing tasks should break. Although it works, it feels wrong since I have to update the model from the database on each iteration, but these feelings might be false. What do you think? -
Access to XMLHttpRequest at .' from origin . has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present
I build my API using Django and trying to use this API from angular but getting a CORS policy error. below is my code. since I am new to both Django and angular, I would appreciate it if anyone could help me with the issue. Django settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'bd_api', 'rest_auth', 'rest_framework.authtoken' , 'django.contrib.sites' , 'allauth' , 'allauth.account', 'rest_auth.registration', 'django_filters', 'corsheaders' , ] CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ 'http://localhost:4200', ] SITE_ID = 1 MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... Angular codes files intercept.ts import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class HttpHeaderInterceptor implements HttpInterceptor { constructor() {} intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { const headers = new HttpHeaders({ // 'Access-Control-Allow-Origin': '*', 'Accept': 'application/json', }); const reqWithToken = request.clone({headers}); return next.handle(reqWithToken); } } http.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '../../environments/environment'; @Injectable({ providedIn: 'root' }) export class HttpserviceService { baseUrl = environment.api_url; // headers = {Authorization: true} constructor(private http: HttpClient) { } public getContries(cond=''){ … -
There is no current event loop in thread 'Thread-12'
I am using Django with requests-html to scrape amazon and Udemy so I have a form that takes in details like the url, price and website but when I fill the form it returns There is no current event loop in thread 'Thread-12'. with any random thread (sometimes it is Thread-2, Thread-9, etc.) I don't know what is causing this error but is there any way that I can dispose of threads that don't have event loops by detecting them. views.py from django.http.response import HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from requests_html import HTMLSession from Products.webscraper import get_udemy_course_price, get_amazon_product_price @login_required def index(request): if 'url' in request.POST and 'desired price' in request.POST and 'website' in request.POST: product_url = request.POST.get("url") desired_price = request.POST.get("desired price") website = request.POST.get("website") session = HTMLSession() if website == "autodetect": if "amazon" in product_url: website = "amazon" if "udemy.com" in product_url: website = "udemy" if "udemy.com" in product_url: title, current_price, thumbnail_url = get_udemy_course_price( session, product_url) elif "amazon" in product_url: title, current_price, thumbnail_url = get_amazon_product_price( session, product_url) else: return HttpResponse("Please enter an Amazon or Udemy URL") print(f"Product URL: {product_url}, Desired price: {desired_price}, Website: {website}, Title: {title}, Current Price: {current_price}, Thumbanil URL: {thumbnail_url}") return render(request, "Pages/index.html") The …