Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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:) -
Django Project : 'dict' object has no attribute 'code'
I retrieved a list of products via an API, then I use django-shopping-cart to generate my cart But I have an error 'dict' object has no attribute 'code'. the error is at this line : if product.code == code ,while there is indeed the code attribute in the dict def cart_add(request,code): url='http://myapi/Product/GetProducts' x=requests.get(url) content=x.json() all_products=content['products'] for product in all_products : if product.code == code : cart=Cart(request) cart.add(product = product.code) return render(request,'shop/deatil.html') At the API level, the dictionary specification is of the form: dict = { "products": [ { "code": "4mlk2", "designation": "kaka" }, { "code": "455ml", "designation": "koko" }, .... ] } -
Django button click gets triggered but not updating model
I tried to upload the image several times, for some reason it just won't upload. I will explain in detail - This table is on my django template.It will display data from a model called "WorkOut". This page has a form above this table for manual data input. Three fields in the table are going to be dynamic, that is where the issue is. In the picture you will see the "Start Time" field that says none. I want to fill this field with a button click. Idea is to click the button, that will trigger a views.py function and that will update the model and then display on this page. Once I do this successfully I will add the end time and do some calculations after. I added a small form in the for loop to generate the button- <td> <form method="get"> <input type="submit" class="btn" value="Start Time" name="start_time"> </form> </td> Here is the views function that it is suppose to trigger- def index_2(request): if(request.GET.get('start_time')): time=datetime.now().strftime('%H:%M:%S') WorkOut.objects.update(start=time) products=WorkOut.objects.all() context={'products': products} return render(request, 'myapp/index.html', context) This page is the index and no separate url for the button click. I don't think I need one. Here is the main index views: def … -
getting error with _set in Django Query-Set, object has no attribute
I use _set to make ManyToMany relationship between customer and Service but endup having Error: AttributeError at /customer/1/ 'carOwner' object has no attribute 'serviceOrderX_get' Is there anyone who want to help me.. models.py ... class carOwner(models.Model): name_X = models.CharField( max_length=150, null=True) email_X = models.CharField( max_length=150, null=True) phoneNo_X =models.CharField( max_length=150, null=True) def __str__(self): return self.name_X class serviceOrderX(models.Model): CATEGORES = (...) carName_X = models.CharField( max_length=150, null=True) carNO_X = models.CharField( max_length=150, null=True) carOwner_X = models.ManyToManyField(carOwner) catagores_X = models.CharField(max_length=200,null=True,choices=CATEGORES) price_X = models.IntegerField( null=True) service_X = models.ManyToManyField(orderService) def __str__(self): return str(f'{self.carName_X} , {self.carNO_X}') views.py ... def CustomerX(request , pk): customersX = carOwner.objects.get(id=pk) cuter = customersX.serviceOrderX_get.all() contX = { 'customer' : cuter , } return render(request, 'customer.html' , contX) -
Django HttResponse has no attr status_code, but docs have :)
I'm using default django httpresponse, like this: return HttpResponse("Validation Error", status_code=400) And i got exception like "HttpResponse has no attribute status_code". But in the docs we have info about this attr (docs link) If we look at source code, we can see: class HttpResponse(HttpResponseBase): ... def __init__(self, content=b'', *args, **kwargs): super().__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content ... Not explict usage of status_code, let's look parent's init: class HttpResponseBase: def __init__(self, content_type=None, status=None, reason=None, charset=None, headers=None): ... if status is not None: try: self.status_code = int(status) except (ValueError, TypeError): raise TypeError('HTTP status code must be an integer.') if not 100 <= self.status_code <= 599: raise ValueError('HTTP status code must be an integer from 100 to 599.') self._reason_phrase = reason And here in params we can see status. If we back to my example, correct version of this looks: return HttpResponse("Validation Error", status=400) And my question is: "Is there place in docs where was talk about status of HttpResponse and if not, how i can make issue or bring this info to django-developers?" The way I see it, it's not obvious enough. -
Unable to login to Django admin with Custom superuser
I am developing a school management system where I am creating custom user by extending User model using AbstractUser. I am able to create the superuser using custom user model but whenever I am trying to login using custom superuser account Django gives the following error Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. This is my customUser model class CustomUser(AbstractUser): ADMIN = "1" STAFF = "2" STUDENT = "3" Email_to_User_Type_Map = { 'admin': ADMIN, 'staff': STAFF, 'student': STUDENT } user_type_data = ((ADMIN, 'Admin'), (STAFF, 'Staff'), (STUDENT, 'Student')) user_type = models.CharField( default=1, choices=user_type_data, max_length=10) Below function represents creating custom user function def create_customUser(username, email, password, email_status): new_user = CustomUser() new_user.username = username new_user.email = email new_user.password = password if email_status == "staff" or email_status == "student": new_user.is_staff = True elif email_status == "admin": new_user.is_staff = True new_user.is_superuser = True new_user.is_active = True new_user.save() please help