Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does Django offer code completion for Query.filter method?
If I have a Django model like: class Example(models.Model): is_in_stackoverflow = models.BooleanField() and I try to filter said model like: Example.objects.filter(is_in_stackoverflow=True) My IDE (Pycharm to be specific) knows to offer me other kwargs based on the fields I specific for my model (for this case it might offer me is_in_stackoverlow__in or is_in_stackoverlow__isnull) I would like to replicate this functionality in a library I am writing. I tried looking into the django source code but was unable to figure this magic out. -
Sorting sizes with two or more numbers in Django
I am trying to sort items that have sizes described by two numbers like the following 10 x 13 100 x 60 7 x 8 The size is saved as a string. I want them sorted like this 7 x 8 10 x 13 100 x 60 how can this be achieved with Django? -
How to filter Many to Many field in django admin page using a foreign key value?
I am trying to filter my many to many variation fields with respect to the product. means I only want the variations related to the product to show in the admin. now its showing all the variations available for every product. I added formfield_for_manytomany() function to my admin.py but how can I get the current product(id) in the cart or order to filter the variations? It may be simple, but I am new in this field! admin.py from django.contrib import admin from .models import * from products.models import Variation class CartAdmin(admin.ModelAdmin): list_display = ('cart_id', 'date_created') class CartItemAdmin(admin.ModelAdmin): list_display = ('user','cart', 'product', 'quantity','is_active') def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "variation": product = Products.objects.get(id='??') # how I get the current product in the cart or order kwargs["queryset"] = Variation.objects.filter(product=product.id) return super().formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(Cart, CartAdmin) admin.site.register(CartItem, CartItemAdmin) CartItem Model class CartItem(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True) product = models.ForeignKey(Products, on_delete=models.CASCADE) variation = models.ManyToManyField(Variation, blank=True) quantity = models.IntegerField() is_active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) def item_total(self): return self.product.price * self.quantity def __str__(self): return self.product.name Product and Variation Model class Products(models.Model): name = models.CharField(max_length=50, unique=True) slug = AutoSlugField(populate_from='name', max_length=100, unique=True) isbn = models.CharField(max_length=20, unique=True, blank=True, null=True) sub_category … -
Requests_HTML getting Error "There is no current event loop in thread Thread-3" - Python
I am trying to load javascript and parse this website. I have the code below that, based on what I have come across, should work. I keep getting the following error message when I compile however. There is no current event loop in thread 'Thread-3' I am really new to Requests-HTML and don't understand what this could be due to. I have been doing some research but everything doesn't seem very relevant to what I am doing and everything seems to be using something called "async". How do I fix this error? Thanks in advance! import requests from bs4 import BeautifulSoup google_initiate(request) def google_initiate(request): form = SearchForm(request.POST or None) if form.is_valid(): url = 'https://www.google.com/search?biw=1866&bih=1043&tbm=shop&q=desk&tbs=mr:1,price:1,ppr_min:,ppr_max:,avg_rating:None' session = HTMLSession() response = session.get(url) response.html.render() print(response.html) google_parsed = response.html.find('.sh-dgr__gr-auto.sh-dgr__grid-result') response.close() session.close() return google_parsed -
Django in Heroku
Hola intento utilizar aplicacion django con BD postgres en Heroku y tengo este error Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/psycopg2/init.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in init self.build_graph() File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/loader.py", line 216, in build_graph … -
AttributeError: 'ManyRelatedManager' object has no attribute 'log_order'
I have the following model classes with many to many relations and I am trying to loop through the query to find if there is a match in one of the fields log_order but I keep getting AttributeError: 'ManyRelatedManager' object has no attribute 'log_order': To get a better idea here is the model: class Log(models.Model): ................................... log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) date = models.DateTimeField(...........) class LogForm(forms.Form): ............................. log_order = forms.IntegerField() class ActiveSession(models.Model): log = models.ManyToManyField(Log) .................................. In my views I am trying to get the data in the form and saving in the log model which is currently working fine. My next step is to loop through the ActiveSession.log to check if the log_order is available to just update it instead of adding a new log to the session. Here is the views: def addlog(request, id): url = request.META.get('HTTP_REFERER') # get last url active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id) if request.method == 'POST': # check post form = LogForm(request.POST) if form.is_valid(): data = Log() data.log_order = request.POST.get('log_order') data.save() # save data to table active_session.log.add(data) print('Log added to Session') # for i in active_session.log.log_order: # print(i) # # for i in active_session.log.log_order.all(): # if data.log_order == i: # print("Available in Active Session") # else: # … -
Django: how to make the clean function work
I have a function to validate that the date field is not less than today's date but it does not work, when I send the data through the form the function does nothing. forms.py class CrearTareaForm(forms.ModelForm): descripcion = forms.CharField(max_length=500, required=True, widget=forms.TextInput(attrs={'placeholder':'Ingrese Descripcion'})) inicio = forms.DateTimeField( input_formats= ['%Y-%m-%dT%H:%M'], required=True, widget=forms.DateTimeInput( attrs={ 'type': 'datetime-local', 'class': 'form-control' } )) def clean_inicio(self): inicio = self.cleaned_data['inicio'] if inicio < datetime.date.today(): raise forms.ValidationError("The date cannot be in the past!") return inicio views.py def creartarea(request): data = { 'tarea': CrearTareaForm() } if request.method=="POST": if request.POST.get('nombre') and request.POST.get('descripcion') and request.POST.get('inicio') and request.POST.get('termino') and request.POST.get('repetible') and request.POST.get('activo') and request.POST.get('estado') and request.POST.get('creador') and request.POST.get('tarea_anterior'): tareasave= Tarea() tareasave.nombre=request.POST.get('nombre') tareasave.descripcion=request.POST.get('descripcion') tareasave.inicio=request.POST.get('inicio') tareasave.termino=request.POST.get('termino') tareasave.repetible=request.POST.get('repetible') tareasave.activo=request.POST.get('activo') tareasave.estado=EstadoTarea.objects.get(pk=(request.POST.get('estado'))) tareasave.creador=Empleado.objects.get(rut=(request.POST.get('creador'))) tareasave.tarea_anterior=Tarea(pk=(request.POST.get('tarea_anterior'))) cursor=connection.cursor() cursor.execute("call SP_crear_tarea('"+tareasave.nombre+"','"+tareasave.descripcion+"', '"+tareasave.inicio+"', '"+tareasave.termino+"', '"+tareasave.repetible+"', '"+tareasave.activo+"', '"+str(tareasave.estado.id)+"', '"+str(tareasave.creador.rut)+"', '"+str(tareasave.tarea_anterior.id)+"')") messages.success(request, "La tarea "+tareasave.nombre+" se guardo correctamente ") return render(request, 'app/creartarea.html', data) else: return render(request, 'app/creartarea.html', data) help me please!!!! -
Create one-to-one model record, or update if it already exists, in this Django view
UserComputedInfo model has a one-to-one relationship with CustomUser model. I want to update or create a record in UserComputedInfo during a form update to CustomUser. I managed to create/update a record in views.py Here is the code; from .models import UserComputedInfo def profile(request, username): if request.method == "POST": user = request.user form = UserUpdateForm(request.POST, request.FILES, instance=user) if form.is_valid(): user_form = form.save() # How to save post_code to copy_input in UserComputedInfo model user_computed_info_instance = UserComputedInfo(user_id=user.id) user_computed_info_instance.latitude = 1.18 # or whatever value to be assigned user_computed_info_instance.save() messages.success(request, f'{user_form.username}, Your profile has been updated!') return redirect("profile", user_form.username) return redirect("homepage") This is a follow-up question to a flawed answer I posted to my own past question. Save values into another database table with one-to-one relationship in Django during form update The answer works the first time when a new record is being created. However, it fails to work the second time profile() is run because there is already an existing record. How do I modify profile() such that a new record will be created if there is no existing record and an update will be made if the record already exists? I am using Django v4, python v3.9, sqlite database on Windows 10 -
Getting Relative Import Error While Registering Models Django
I was following the django documentation tutorial to make my first app, and then I reached the admin.py part and was trying to register my models, but then I got this error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. My Folder Structure: ├───Poll │ └───__pycache__ └───polls ├───migrations │ └───__pycache__ └───__pycache__ Visual Representation: My Code in admin.py: from django.contrib import admin from models import Question, Choice admin.site.register(Question) admin.site.register(Choice) -
Add cart on django-shopping-cart ( error 'str' object has no attribute 'id')
I use django-shopping-cart 0.1 to add carts, but here the data comes from an api, so I did not create a product model When trying to add I have this error: ('str' object has no attribute 'id' ) this error comes from the cart.py module of django-shopping at: id = product.id I remind you that at the level of the API which retrieves the products, I have the fields (code, designation) so I pass the 'code' field as a parameter to add a basket, as there is no 'id' View.py @login_required def cart_add(request,code): url='http://myapi/Article/GetArticle' x=requests.get(url) content=x.json() articles=content['articles'] for article in articles : if article.get('code') == code : cart=Cart(request) myarticle=article.get('code') cart.add(product=myarticle) return render(request,'cart/deatil.html') Module Cart.py class Cart(object): def __init__(self, request): self.request = request self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, action=None): """ Add a product to the cart or update its quantity. """ id = product.id newItem = True if str(product.id) not in self.cart.keys(): self.cart[product.id] = { 'userid': self.request.user.id, 'product_id': id, 'name': product.name, 'quantity': 1, 'price': str(product.price), 'image': product.image.url } else: newItem = True for key, value in self.cart.items(): … -
Filtering Foreign Key Based on Another SlugRelatedField in POST Requests in Django Rest Framework
I'm using Django Rest Framework and have a model with multiple ForeignKey relationships and am POSTing their slugs rather than id. The issue is that the second ForeignKey requires a queryset that is filtered based on the first. Here is a not-so-perfect example: # models.py class Student(models.Model): slug = models.SlugField(...) class Class_(models.Model): slug = models.SlugField(...) class ReportCard(models.Model) student = models.ForeignKey(Student) class_ = models.ForeignKey(Class_) grade = models.CharField(...) # serializers.py class ReportCardSerializer(serializers.ModelSerializer): student = serializers.SlugRelatedField(queryset=models.Student.objects.all(), slug_field='slug') class_ = serializers.SlugRelatedField(queryset=models.Class_.objects.filter(???), slug_field='slug') # need to filter based on student here class Meta: model = models.ReportCard fields = '__all__' # use all fields How do I do this? student in the serializer does not return the model and I don't know how to access the data inside of ReportCardSerializer to grab the string from the POST request to manually filter class_. -
Better way to insert and list on the same page with django
I'm creating a todo list using django, and I found it more interesting to be able to list and insert on the same page than creating a page just to insert The way I managed to do it so far was as follows: class IndexView(CreateView, ListView): models = Todo template_name = 'index.html' queryset = Todo.objects.all() context_object_name = 'todos' fields = ['nome'] success_url = reverse_lazy('index') I wonder, is there a better way to do this? -
Django doesn't creates objects for all rows in postgresql
I'm scripting a migration tool to get my data from an old software to a new version with different data structures. While looping through the csv-files I'm creating the objects. The problem is that every object gets created in postgres but django doesn't. I'm getting errors like: duplicate key value violates unique constraint "api_order_pkey" DETAIL: Key (id)=(159865) already exists. Order.objects.get(pk=159865) does return "Does not exist" But a SELECT * FROM api_order WHERE pk = 159865 directly in Postgres finds a row. with open("order.csv","r") as f: reader = csv.reader(f) for row in reader: Order.objects.create(pk = row[0], ordernr= row[1],....)` thats of course a short version of it. On the import of about 250.000 rows this problem appears with about 100 rows. I had the same problem with deleting. I ran Order.objects.all().delete() but in Postgres there where still a few rows left while Order.objects.all() returned an empty Queryset. Is there something I can do about this? Has anyone had a similar problem? -
How do I get the JWT tokens from user in Django RestFramework
I have a DRF project using Simple-JWT for authentication. When a user logs in, they get a response containing the access and refresh tokens in the serializer.data. However: When testing on the Apis I can manually copy and paste these tokens and add them to headers when making requests. However in production, Where are these tokens stored on the user's side? How will the user be able to add the access token to requests that are protected? (they can't copy-paste like me) How will they use the refresh token to renew the access token I would appreciate if someone cleared this up for me. -
(421, b'Service not available')
I have a simple method (send_activation_email) called from a view which handles user registration by extending default django user auth. It sends an activation email. Now I get the error: Please help me out guys Exception Type: SMTPConnectError Exception Value: (421, b'Service not available') The Method Implementation def send_activation_email(user, request): current_site = get_current_site(request) subject = 'Activate your membership Account' message = render_to_string('accounts/account_activation_email.html',{ 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_message = get_template('accounts/account_activation_html_email.html').render({ 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) send_mail(subject=subject, message=message, from_email= None, recipient_list=[user.email], html_message= html_message #,fail_silently=False ) Email Configuration in Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'asoliu34@gmail.com' EMAIL_HOST_PASSWORD = 'syxkgrfbczefd' #past the key or password app here EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'default from email'. Call the function in view send_verification_email(request, user) Template {% autoescape off %} Hi {{user.first_name}}, Please click on below link to verify your email http://{{domain}}{% url 'activate' uidb64=uid token=token %} {% endautoescape %}. -
Django: returning empty {} with 400 Bad request for post method
I am trying to implement an attendance system as part of a bigger project that handles multiple schools at the same time but the endpoint is returning an empty {} with a 400_BAD_REQUEST Attendance/models.py class Attendance(models.Model): Choices = ( ("P", "Present"), ("A", "Absent"), ("L", "On leave"), ) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="user_attendance", blank=False, null=True) leave_reason = models.CharField(max_length=355, blank=True, null=True) Date = models.DateField(blank=False, null=True, auto_now=False, auto_now_add=True) Presence = models.CharField( choices=Choices, max_length=255, blank=False, null=True) attendance_taker = models.ForeignKey( User, on_delete=models.CASCADE, related_name="attendance_taker_attendance", blank=False, null=True) def __str__(self): return f'{self.user}' class Meta: verbose_name = _("Attendance") verbose_name_plural = _("Attendance") constraints = [ UniqueConstraint( fields=('user', 'Date'), name='unique_attendance_once_per_date') ] Attendance/serializers.py class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance fields = ['user', 'Presence', 'leave_reason', 'Date'] constraints = [ UniqueConstraint( fields=('user', 'Date'), name='unique_attendance_once_per_date') ] def create(self, validated_data): instance = Attendance.objects.create( user=validated_data['user'], Presence=validated_data['Presence'], leave_reason=validated_data['leave_reason'], attendance_taker=self.context['request'].user, Date=datetime.today ) instance.save() return instance Attendance/views.py class AttendanceListCreateAPIView(CreateAPIView): permission_classes = [IsClassPart] queryset = Attendance.objects.all() serializer_class = AttendanceSerializer def post(self, request, format=None): user = request.user try: perms = Perm.objects.get(user=user) except ObjectDoesNotExist: perms = None serializer = AttendanceSerializer(data=request.data) if serializer.is_valid(): if user.role == "TEACHER": if user.homeroom == serializer.validated_data['user'].room: Response({"message": "You don't have permission to perform this action 1"}, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif perms is not None: if user.role … -
How to sort a queryset by its Q objects order?
I've a simple searching form and view: # forms.py class SearchForm(forms.Form): q = forms.CharField(label='Search', max_length=1024, required=False) # views.py def search(request): search_form = forms.SearchForm() q = '' if request.method == 'GET': search_form = forms.SearchForm(request.GET) if search_form.is_valid(): q = search_form.cleaned_data['q'] products = models.Product.objects.filter(publication_status='published') if q.strip() != '': # If there's something to search for which not whitespaces products = products.filter( Q(title__contains=q) | Q(description__contains=q) | Q(main__name__contains=q) | Q(sub__contains=q) ) context = { 'products': products, 'search_form':search_form, } return render(request, 'search.html', context=context) # search.html {% if products %} <h3>Products:</h3> <ul> {% for p in products %} <li><ul> <li><a href="{% url 'product' p.pk %}">{{ p }}</a></li> <li>{{ p.description }}</li> <li><a href="{% url 'main' p.main.pk %}">{{ p.main }}</a></li> <li><a href="{% url 'sub' p.main.pk p.sub %}">{{ p.sub|verbose }}</a></li> </ul></li><br> {% endfor %} </ul> {% else %} <h3>No products found matching your search!</h3> {% endif %} If the word "polo" is the title of product 2 and it's also the description of the product 1, The problem is when I'm trying to search for that word, The product 1 is rendered in the first place in the template (because it's the first matching). What I'm trying to do is to sort the queryset first by title then by description … -
Putting additional data to CRUD django model- iterating with id,pk/ Python3/Django/CRUD
this is in models.py class Word(models.Model): english = models.CharField( max_length=100) polish = models.CharField( max_length=100) this is in views.py words=[] def dictionary(request): words= Word.objects.all() context={'words':words} return render(request, 'base/dictionary.html', context) ` `` def word(request, pk): word= Word.objects.get(id=pk) context={'word':word} return render(request, 'base/word.html', context) I would like to add this dictionary from my workplace to already existing database with models - English-Polish pair. I've created a CRUD model of this type of simple dictionary, yet I am wondering if I have to put all the words inside by myself , or there will be a possibility to append each pair with specific id , ready to be rendered into html template and database ? words=['fallopian tube' : 'jajowód', 'mrsa bacteria' : 'bakteria gronkowca złocistego', 'carotid aneurysm': 'tętniak tętnicy szyjnej',...] -
Django: how to get the user from user form input
I am trying to implement an attendance system as part of a bigger project that handles multiple schools at the same time, I am trying to get some user details from the user that is being marked as present, absent, or on leave serializer.py class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance fields = ['user', 'Presence', 'leave_reason', 'Date'] constraints = [ UniqueConstraint( fields=('user', 'Date'), name='unique_attendance_once_per_date') ] def create(self, validated_data): instance = Attendance.objects.create( user=validated_data['user'], Presence=validated_data['Presence'], leave_reason=validated_data['leave_reason'], attendance_taker=self.context['request'].user, Date=datetime.today ) instance.save() return instance my current implementation of the view: class AttendanceListCreateAPIView(CreateAPIView): permission_classes = [IsClassPart] queryset = Attendance.objects.all() serializer_class = AttendanceSerializer def post(self, request, format=None): user = request.user try: perms = Perm.objects.get(user=user) except ObjectDoesNotExist: perms = None serializer = AttendanceSerializer(data=request.data) if serializer.is_valid(): if user.role == "TEACHER": if user.homeroom == request.data['user'].room: Response({"message": "You don't have permission to perform this action 1"}, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif perms is not None: if user.role != 'STUDENT' and user.perms.is_monitor: if user.room != request.data['user'].room: Response({"message": "You don't have permission to perform this action 2"}, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response({"message": "You don't have permission to perform this action 3"}, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) the error is in request.data['user'].room: as django says 'str' object has no attribute 'room' -
How to access a field of the body of a post request that stores an array of files sent from postman to a Django server?
Sorry for the cumbersome question, but I am sending four files to a Django server using postman, and my goal is to access each file and get specific information about them, like their pathname and file size. Here's the POST request on postman: post_req_postman And here's how it looks like when the server receives the request: request_printed_to_terminal Basically, as shown in the screenshot and as I said, I want to access the following array in the files field of the request: [<InMemoryUploadedFile: Screen Shot 2022-09-11 at 10.14.05 PM.png (image/png)>, <InMemoryUploadedFile: Screen Shot 2022-09-11 at 10.14.04 PM.png (image/png)>, <InMemoryUploadedFile: Screen Shot 2022-09-11 at 10.13.51 PM.png (image/png)>, <InMemoryUploadedFile: Screen Shot 2022-09-11 at 10.13.48 PM.png (image/png)>]} Here's is the relevant Django code that handles the file uploads: import io import json from operator import itemgetter import os from django.http import Http404,HttpResponse from django.shortcuts import render from rest_framework.views import APIView from rest_framework.parsers import JSONParser from django.views.decorators.csrf import csrf_exempt from google.cloud import storage os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/gabrieltorion/downloads/filestoragehelpusdefend-3082732cedb4.json" class uploadFiles(APIView): payLoad = None print("Will listen for new file uploads") bucketMemoryMax = 400_000_000_000_00 @csrf_exempt def post(self, request): storageClient = storage.Client() if request.data['name'] == 'uploadFiles': print("request.data: ", request.data) #the screen shots are in 'files' businessId, files = itemgetter("businessId", "files")(request.data) … -
500 error Django Rest Frameworks Serializer
newbie here. I am following a React+Django tutorial (create a store) in which we are using Django RestFrameworks (and this is my first time using it). We are using serializers with JWT tokens for authentication. The problem I'm having is when I try to create a new "order" in the page, I get a 500 error: Internal Server Error: /api/order/add Traceback (most recent call last): File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/Volumes/Samsung_T5/GitHub/ecommerce/backend/base/views/order_views.py", line 59, in addOrderItems return Response(serializer.data) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 555, in data ret = super().data File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 253, in data self._data = self.to_representation(self.instance) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 522, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/Volumes/Samsung_T5/GitHub/ecommerce/venv/lib/python3.9/site-packages/rest_framework/fields.py", line 1886, in to_representation return method(value) File "/Volumes/Samsung_T5/GitHub/ecommerce/backend/base/serializers.py", line 74, in get_user return serializer.data File … -
Django app: An error occurred in the application and your page could not be served
My project is built in django + tailwindcss. I am trying to upload it in heroku but getting this error. An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command. I am relatively new to django and was following a YT tutorial step by step still it didnt work. https://www.youtube.com/watch?v=UkokhawLKDU This tutorial doesnt have anything to do with tailwindcss , do i have to run some commands for tailwind? what am i doing wrong? Here is the output for heroku logs --tail Warning: heroku update available from 7.53.0 to 7.63.4. 2022-09-17T16:53:56.309485+00:00 app[api]: Release v1 created by user ahsanalibalouch12345@gmail.com 2022-09-17T16:53:56.309485+00:00 app[api]: Initial release by user ahsanalibalouch12345@gmail.com 2022-09-17T16:53:56.497743+00:00 app[api]: Release v2 created by user ahsanalibalouch12345@gmail.com 2022-09-17T16:53:56.497743+00:00 app[api]: Enable Logplex by user ahsanalibalouch12345@gmail.com 2022-09-17T16:54:22.920882+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=shrouded-cliffs-70022.herokuapp.com request_id=62d4d40d-ca5f-46c9-a992-5e92c56141b8 fwd="103.115.199.5" dyno= connect= service= status=502 bytes= protocol=https 2022-09-17T16:54:23.506721+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/favicon.ico" host=shrouded-cliffs-70022.herokuapp.com request_id=1034c961-9b8a-4286-80a3-bb531751b5fe fwd="103.115.199.5" dyno= connect= service= status=502 bytes= protocol=https 2022-09-17T16:59:49.841794+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=shrouded-cliffs-70022.herokuapp.com request_id=989fcb86-466f-45b6-85dd-ad6bfef64b11 fwd="103.115.199.5" dyno= connect= service= status=502 bytes= protocol=https 2022-09-17T16:59:50.158999+00:00 heroku[router]: at=info code=H81 … -
celery.beat.SchedulingError: Couldn't apply scheduled task broadcast_notification_8: 'int' object is not iterable.... thanks to anyone
celery.beat.SchedulingError: Couldn't apply scheduled task broadcast_notification_8: 'int' object is not iterable.... thanks to anyone Traceback (most recent call last): File "C:\Users\USER\AppData\Roaming\Python\Python37\site-packages\celery\beat.py", line 401, in apply_async entry_args = _evaluate_entry_args(entry.args) File "C:\Users\USER\AppData\Roaming\Python\Python37\site-packages\celery\beat.py", line 211, in _evaluate_entry_args for v in entry_args TypeError: 'int' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\AppData\Roaming\Python\Python37\site-packages\celery\beat.py", line 287, in apply_entry result = self.apply_async(entry, producer=producer, advance=False) File "C:\Users\USER\AppData\Roaming\Python\Python37\site-packages\celery\beat.py", line 414, in apply_async entry, exc=exc)), sys.exc_info()[2]) File "C:\Users\USER\AppData\Roaming\Python\Python37\site-packages\celery\exceptions.py", line 108, in reraise raise value.with_traceback(tb) File "C:\Users\USER\AppData\Roaming\Python\Python37\site-packages\celery\beat.py", line 401, in apply_async entry_args = _evaluate_entry_args(entry.args) File "C:\Users\USER\AppData\Roaming\Python\Python37\site-packages\celery\beat.py", line 211, in _evaluate_entry_args for v in entry_args celery.beat.SchedulingError: Couldn't apply scheduled task broadcast_notification_8: int' object is not iterable celery.beat.SchedulingError: Couldn't apply scheduled task broadcast_notification_8: 'int' object is not iterable.... thanks to anyone My tasks.py @shared_task(bind=True) def broadcast_notification(self, data): print(data) try: notification = BroadcastNotification.objects.filter(id=int(data)) if len(notification) > 0: notification = notification.first() channel_layer = get_channel_layer() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(channel_layer.group_send( "notification_broadcast", { 'type': 'send_notification', 'message': json.dumps(notification.message), })) notification.sent = True notification.save() return 'Done' else: self.update_state( state = 'FAILURE', meta = {'exe': 'Not Found'} ) raise Ignore() except: self.update_state( state = 'FAILURE', meta = { 'exe': 'Failed', # 'exc_type': type(ex).__name__, # 'exc_message': traceback.format_exc().split('\n') # 'custom': … -
django.template.exceptions.TemplateDoesNotExist: Error
I'm learning to use Django for some side projects but I keep getting the same error whenever I try to set a template. I've tried giving the directory for the app, and when I check the error it says that the file does not exist. When I go and look at the directory it does exist though? The Error My Directory -
How to get value of <option> in django view?
I have form with option to choose which country are you coming from. In my model I've got country_living field with choices: LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra'), ('ANGOLA', 'Angola')] class Employee(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) username = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=140, blank=True) date_of_birth = models.DateField(blank=True, default='1929-11-11') education = models.CharField(max_length=50, blank=True) country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default='AFGANISTAN', blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) password = models.CharField(max_length=30, null=True) In my class-based view I get those fields like: def get(self, request): employees = models.Employee.objects.all() living_countries_list = LIVING_COUNTRIES context = { 'employees': employees, 'living_countries_list': living_countries_list } return render(request, 'authentication/employee_register.html', context) and my html: <select name="country" id="id_category"> {% for each in living_countries_list %} <option value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> {% endfor %} </select> In my post method I get option and check if it exists country = request.POST.get('coutry') if not country: print('no country') context['has_error'] = True print(country) Problem is even if country is selected when I click submit button I can't get value of it Thanks for help:)