Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django problem - server deployed on Heroku, everytime I login and I don't spend time on website I can't login with same credentials
Two years ago I have programmed a Django website and I deployed on Heroku. As I remember in that times if i was automatically logged out I could log in with no problems. Now I have started to work on this website in the testing side, a project from my dissertation thesis and everytime I am logging in and if my computer goes sleep mode or I don't click my website for a brief amount of time I can't login back with the same credentials. Have you encountered the same problem? I don't know what to do. -
Unable to open my Django db using PGAdmin (via Docker)
I am trying to visually browse my Django app's db data using pgadmin4. But I am having an issue connecting to the DB. I tried using both the local host and also Docker's IP address I obtained via 'docker inspect container name' but to no avail. Appreciate any help! Following are the database settings in my settings.py DATABASES = { "default": env.dj_db_url("DATABASE_URL", default="postgres://postgres@db/postgres") } Following is my docker-compose.yml version: "3.9" services: web: build: . ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/my_backend depends_on: - db environment: - "DJANGO_SECRET_KEY=xyz" - "DJANGO_DEBUG=True" db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: I tried the following so far: Deleted all images,volumes, containers and restarted using docker-compose up -d --build Re-ran the django 'migrate' command Added psql I installed using Brew to the env zsh path. Tried Pgadmin with 2 different hostnames as below Following are the inputs I have for pgadmin Host name: Tried both localhost and 172.18.0.2 Maintaainance DB: postgres username: postgres Password: Left it Blank Following screenshots show the error -
I keep getting an integrity error while trying to create an appointment object from my django admin panel
I created an appointment model that has foreign key relationships with a couple of other models in my database. The Doctor model has a one-to-one relationship with the User model. The User model extends from the built-in django AbstractUser class Below is the code for my appointment model: class Appointment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) symptoms = models.ForeignKey(Symptom, on_delete=models.CASCADE) diagnosis = models.ForeignKey(Diagnosis, on_delete=models.CASCADE, null=True, blank=True) date = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user.username} - {self.doctor.user.username} - {self.date.strftime('%Y-%m-%d %H:%M:%S')}" and below is the code for the Doctor and User models: class User(AbstractUser): email = models.EmailField(unique=True, null=True) phone_number = models.CharField(max_length=11, unique=True, help_text='Phone Number') is_user = models.BooleanField('Is User', default=False) is_doctor = models.BooleanField('Is Doctor', default=False) class Doctor(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(max_length=500, help_text='DesCription') category = MultiSelectField(choices=DIAGNOSIS, max_choices=5, max_length=1000, help_text='Category') experience = models.IntegerField(help_text='Experience') def __str__(self): return self.user.username and this is the error I keep getting when I try to create an appointment object from my django admin panel: IntegrityError at /admin/core/appointment/add/ FOREIGN KEY constraint failed I tried creating an appointment object and expected an appointment object to be created in my database but that didn't happen -
What is the best method to query db in django rest framework
I have models.py class Category(MPTTModel): # few fields class Brand(models.Model): # few fields class Attribute(models.Model): # few fields class Product(models.Model): category = models.ForeignKey(Category, # other conditions) brand = models.ForeignKey(Brand, # other conditions) attributes = models.ManyToManyField(Attribute, # other conditions) # few other fields In views.py, I have class ProductAPIView(generics.GenericAPIView): serializer_class = ProductSerializer queryset = Product.objects.all() I came across select_related and prefetch_related which will optimise the db queries on foreign key fields and many-to-many fields. I changed the queryset to queryset = Product.objects.select_related('category', 'brand').all() How can i change the queryset in ProductAPIView to include the attributes field also and improve the performance here ? And how can I check the queries counts and time taken for execution ? -
How to retrieve uploaded image from a MYSQL database
I am designing a website where when the user uploads the image it returns the 10 prominent colors present in the image. I am able to upload the image into mysql database but I've troubles retrieving the image from the database and passing it into my main color finding program import base64 import io from PIL import Image up_im="" cap="" # Create your views here. def starttest(request): if request.method=="POST": global up_im,cap con=sql.connect(host="localhost", user="root", passwd="****", database='test_pro',auth_plugin='mysql_native_password',buffered=True) cursor=con.cursor() pos=request.POST for key,value in pos.items(): if key=='IMAGE': up_im=value if key=="caption": cap=value c="insert into userdata values('{}','{}')".format(up_im,cap) cursor.execute(c) retr="select IMAGE from userdata where caption= '{}'".format(cap) cursor.execute(retr) data=cursor.fetchone() uploaded_image=data[0][0] binary_data=base64.b64decode(uploaded_image) show_image=Image.open(io.BytesIO(binary_data)) show_image.show() con.commit() I have connected mysql python and html using django This is the error I get (https://i.stack.imgur.com/sqOUK.png) this is the line of error And I followed this tutorial https://www.geeksforgeeks.org/retrieve-image-and-file-stored-as-a-blob-from-mysql-table-using-python/ -
Filtering rooms by users
I have a ChatRoom model that has a users field. And I need to get a model in Views in which the users = request field.user and user. I get the error 'local variable 'myroom'referenced before assignment'. Help to get the object using the get method. models.py class ChatRoom(models.Model): users = models.ManyToManyField(User, related_name='users') def __str__(self): return self.pk Views.py def homechat(request): if request.method == 'POST': user = request.POST user = list(user)[1] user = USER.objects.get(username=user) try: room = ChatRoom.objects.get(Q(users=user) & Q(users=request.user)) return redirect('room', room=room.pk) except room.DoesNotExist: room = ChatRoom.objects.create(users1=user, users2=request.user) room.save() return redirect('room', room=room.pk) return render(request, 'chatapp/index.html') -
Read a CSV file and make HTTP POST to API URL from each line in python?
I have a csv file and I want to POST it to an Django REST API URL. I can post but It's only 1 for example (1 User) and when I use a .csv file I can't post it and I reveived an error of "400". import requests import os import csv header= { "Accept": "application/json", "Content-Type": "application/json" } # CSV file path csv_folder = "csv" csv_file_name = "my_data.csv" csv_file_path = os.path.join(csv_folder, csv_file_name) url = 'http://127.0.0.1:8000/api/url/' def csv_reader(read, file_header): rows = [] with open(read, 'r') as file: csvreader = csv.reader(file) file_header = next(csvreader) for row in csvreader: rows.append(row) print(file_header) print(rows) print("") print("==== Sending POST to an API URL ===") print("") response = requests.post(url, json=row) print(response) if response.status_code == 200: print("Data inserted successfully") else: print(f"Failed to insert data: {response.status_code}") csv_reader(csv_file_path, header) Is there anything I can add to post it successfully to an URL ? Thank you in advance I tried to POST but I recieved and error response 400 I expected to post Per row to the API. -
Django project deployed on aws ec2 not loading after ssl configuration
I have deployed my django website on ec2 instance with custom domain. Everything was working until i configured ssl then the site would load for very long time and return "This site can’t be reached". Here is my my nginx file: server{ server_name example.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/lsh_bank/app.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server{ if ($host = getraven.co) { return 301 https://$host$request_uri; } listen 80; server_name example.com; return 404; # managed by Certbot } -
why wont my video is disaplayed in template
url configuration urlpatterns = []+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) View def Error404(request): return render(request,'error404/error404.html') html file <video src="{% static 'assets/img/banner/banner.mp4' %}" type="video/mp4" alt=""> anyone help me to solve this -
Read properties from common config in frontend and backend
I have a Django server in the backend and React server in the front end. for example, I have this function in the backend: def create(request): fname = request.data['first_name'] lname = request.data['last_name'] and this is my front: function() { axios.post({first_name:x, last_name:y}, url, headers) } I need to read first_name from a common config that is shared with the front and back. in other words, if I want to change first_name to firstname, I only need to change common config(not frontend or backend codes) -
Django: css document wont load on base html template
I made the following script inside of my site folder(same place where templates folder is located), but when I run the script, and look at the site, the changes dont show. I also inspected the css code, and its not finding the file I linked it to, but I'm sure the file is there in the directory I linked. Here is the code for both files: Users/Docs/Django/src(site folder w/ manage.py)/static/base.css body { background-color: lightblue; font-family: verdana; } Users/Django/src/templates/base.html {% load static %} <!doctype html> <html> <head> <link rel="stylesheet" href="{% static 'base.css' %}"> <title>Coding for Entrepreneurs is doing Try Django</title> </head> <body> {% include 'navbar.html' %} {% block content %} AAAAAA {% endblock %} </body> </html> -
Write exception to log when django is unable to run
Django Gurus, I have the following error messages on my console and I have the following logging configuration. LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, "file": { 'class':'logging.FileHandler', "filename": str(BASE_DIR) + "/" + "logs"+ "/" + "app.log", "level":"DEBUG", }, }, "loggers": { "django.utils.autoreload": { "level": "CRITICAL" }, "django": { "handlers": ["file"], "level": "DEBUG", "propagate": True, }, } } Stacktrace on my console: System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InsufficientPrivilege: permission denied for table django_migrations The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.11/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.8/3.8.11/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 78, in applied_migrations return {(migration.app, migration.name): migration for migration in self.migration_qs} File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__ … -
Django progress bar is not orking
product_tag from django import template import math @register.simple_tag def prog_bar(total_quantity,availability): progress_bar = availability progress_bar = availability * (100/total_quantity) return math.floor(progress_bar) HTML <div class="progress mb-5"> <div class="progress-bar bg-danger" role="progressbar" style="width:{% prog_bar i.availability i.total_quantity %}%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"> </div> </div> <div class="progress-rate"> <span> Availability: {{ i.availability }} </span> </div> I followed one tutorial video his code is working perfectly but my code is not working. Please help me to solve this problem -
Django 4.2.1 with django-cookiecutter 2023.05.09: makemigrations doesn't create migration file for new model
I'm using Django 4.2.1 with the latest version of django-cookiecutter (2023.05.09) on MacOS Ventura 13.3.1, and I'm having trouble getting the makemigrations command to create a migration file for a new model I've added to my Django project. Here's what I've done thus far: I added the new model to my models.py file in my app directory: from django.db import models class TestModel(models.Model): name = models.CharField(max_length=50) I created an empty migration file for the app with the makemigrations command: python manage.py makemigrations myapp --empty I ran the makemigrations command again to create a migration for the new model, but it didn't create a new migration file: python manage.py makemigrations I've double-checked that the TestModel app is included in my INSTALLED_APPS list in my settings.py file, and I've checked that there are no syntax errors in my models.py file. I've also tried running the check command to see if there are any issues with my code, but it doesn't show any problems: python manage.py check I've also tried running the makemigrations command with the --verbosity 3 option to get more detailed output, but it doesn't show any errors or warnings related to the TestModel app. I've also checked that the migration … -
Django 4, how can I download a generated CSV file to browser while passing additional context to template?
In views.py, I have a view that displays invoice information and a button that reads a CSV template and adds more data, and then downloads the new CSV to the browser. At the same time, I want to return some context to generate toast notifications about the processing status. It seems I need to do this via multiple HTTP requests/responses, and I'm not sure how to go about it. Here's the view: class InvoiceView(TemplateView): model = Cost template_name = "pipeline/invoices_list.html" costs = Cost.objects.all() def get_context_data(self, **kwargs): # some context data return context def post(self, request, *args, **kwargs): if "batch-pay-csv" in request.POST: response, batch_payment_status = create_batch_payment_template(self.costs) context = self.get_context_data(**kwargs) context['batch_payment_status'] = batch_payment_status return response and an abbreviated version of the create_batch_payment_template() function (in utils.py): def create_batch_payment_template(costs): ''' Create a batch payment file from the template in /static. ''' invoices = costs.filter(invoice_status__in=["REC", "REC2"]) processing_status = {} # format: invoice PO number {status (success/error), message} response = HttpResponse( content_type='text/csv', headers = {'Content-Disposition': 'attachment; filename = "WISE_BATCH_PAYMENT.csv"'}, ) # for invoice in invoices, write stuff to the CSV context = processing_status return response, context I'm starting to think it would be easier to generate a download button on the template rather than try to … -
Admin.E108 when customizing admin interface
I received this error: ERRORS: <class 'bjjtournament_app.admin.MemberAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'Group1', which is not a callable, an attribute of 'MemberAdmin', or an attribute or method on 'bjjtournament_app.Competitors'.`` I think the error is in admin.py class MemberAdmin(admin.ModelAdmin): list_display = ["group_label"] admin.site.unregister(Group1) admin.site.register(Group1, MemberAdmin) def __str__(self): return self.group_label Can someone explain to me what the error is about? Thanks! -
Uploading images from a CSV file to Django model instances while using bulk_create
I have a project built with Django Rest Framework. In one of the views, I'm implementing a functionality that takes a CSV file sent from the frontend (React.js), and that creates model instances from the rows of the CSV file. This is the model that I'm trying to upload: class ModelExample(models.Model): name = models.CharField(...) logo = models.ImageField(...) . . . This is the code that I'm using to create the model instances: class ModelExampleCreateAPIView(APIView): def get(self, request, format=None): . . . modelExampleList = list() reader = pd.read_csv(file) for rowIndex, row in reader.iterrows(): newModelExample = ModelExample( name=row['Name'], # logo = row['Logo'] ) modelExampleList.append(newModelExample) ModelExample.objects.bulk_create(modelExampleList) . . . This is an example of the CSV file that I'm using: Name Logo Name Example 1 https://url-to-logo-1 Name Example 2 https://url-to-logo-2 My question is how can I assign the logo column to the model instances. The solutions I have found so far force to save the model instances inside of the loop (in the view) instead of using bulk_create. Since I'm creating a considerable amount of model instances at once, I need to use the bulk_create instead of saving one by one. All suggestions are very appreciated These are some of the links I … -
TypeError while iterating list of dictionaries in docker container
I have a Django project. I use Wordpress as an admin panel. I call WP API during handling one of views. Here is the view: def blog(request): sys.stderr.write('views.blog started to process\n') if request.method == 'GET': list_of_blogposts = [] # load all posts try: response = wp.get_all_post() all_posts = json.loads(response.text) sys.stderr.write('path /blog - all done' + all_posts) except Http404: msg = 'Unable to load blogposts.' sys.stderr.write(msg) raise Http404(msg) except TimeoutError: msg = 'Requst timed out.' sys.stderr.write(msg) raise TimeoutError(msg) except Exception: msg = 'Exception' sys.stderr.write(msg + str(traceback.extract_stack())) # iterate all posts try: # get all images m = wp.get_all_images() media = json.loads(m.text) for post in all_posts: img = post["featured_media"] url = u.get_image_url(media, img) b = { "body": post["content"]["rendered"], "title": post["title"]["rendered"], "summary": post["excerpt"]["rendered"], "image_url": str(url), "post_id": post["id"], "publishedAt": u.convert_dt_to_str(post["date"]) } # add post to list for response list_of_blogposts.append(b) except TypeError or ValueError or RuntimeError or KeyError: sys.stderr.write('Iteration through posts failed.') raise Exception('Unexpected error. Try again later.') context = {'posts_list': list_of_blogposts} return render(request, 'web/blog.html', context) else: raise Http404("Incorrect HTTP method.") It works great as I want. When I create Docker image and run it on linux server I got - TypeError: string indices must be integers, not 'str' at line where is img = … -
django tests - error in github action while running in parallel
in a github action yml file it's defined this step to run django tests: python manage.py test --failfast --parallel 2 looks like --parallel 2 breaks it: multiprocessing.pool.RemoteTraceback: """ Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/multiprocessing/pool.py", line 125, in worker result = (True, func(*args, **kwds)) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/test/runner.py", line 449, in _run_subsuite result = runner.run(subsuite) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/test/runner.py", line 366, in run test(result) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/unittest/suite.py", line 84, in __call__ return self.run(*args, **kwds) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/unittest/suite.py", line 122, in run test(result) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/test/testcases.py", line 381, in __call__ self._setup_and_call(result) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/test/testcases.py", line 416, in _setup_and_call super().__call__(result) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/unittest/case.py", line 650, in __call__ return self.run(*args, **kwds) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/unittest/case.py", line 599, in run self._feedErrorsToResult(result, outcome.errors) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/unittest/case.py", line 516, in _feedErrorsToResult result.addFailure(test, exc_info) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/test/runner.py", line 296, in addFailure self.check_picklable(test, err) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/test/runner.py", line 216, in check_picklable self._confirm_picklable(err) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/test/runner.py", line 186, in _confirm_picklable pickle.loads(pickle.dumps(obj)) TypeError: cannot pickle 'traceback' object """ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/runner/work/fiscozen/fiscozen/fiscozen_django/manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/opt/hostedtoolcache/Python/3.10.6/x64/lib/python3.10/site-packages/django/core/management/base.py", line 458, in … -
Django Custom ModelBackend access cookies
I've a custom user model with my own auth backend How i need a access to cookies in def get_user How it can be done? class AuthBackend(ModelBackend): def authenticate(self, request, **kwargs): login = request.POST.get('username') login = kwargs['username'] password = kwargs['password'] logger.info(password) try: auth_user = Company_Users.objects.get(auth_login=login) hash_password = hashlib.sha512(password.encode('utf-8')).hexdigest() if auth_user.auth_password == hash_password: auth_user.is_active = True auth_user.is_authenticated = True return auth_user except Company_Users.DoesNotExist: pass def get_user(self, user_id): ### here i need cookies info <----------------- HERE try: user = Company_Users.objects.filter(pk=user_id).first() if user is None: return None return user except User.DoesNotExist: return None -
Django HTMLCalendar
I am first time using HTMLCalendar to render calendar for my application, however I am not getting last day of the month shown e.g. June 2023 only shows days from 1 to 29 but not 30. What is wrong in my below code? class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): try: # Get all events that start on this day events_per_day = events.filter(start_time__day=day) # Get all events that span across this day events_spanning = events.filter(start_time__lt=datetime.datetime(self.year, self.month, day+1), end_time__gt=datetime.datetime(self.year, self.month, day)) d = '' if events_spanning: # Render all spanning events in a row d += '<div>' for event in events_spanning: d += f'<div class="border rounded p-1 mb-1 bg-hover">{event.get_html_url}</div>' # Exclude this event from the events_per_day list events_per_day = events_per_day.exclude(id=event.id) d += '</div>' # Render all other events for this day for event in events_per_day: d += f'<div>{event.get_html_url}</div>' if day != 0: if datetime.datetime(self.year, self.month, day).weekday() in \[5, 6\]: # add class for weekends return f"<td class='weekend'><span class='date my-text'><a href='{reverse('add_event')}' type='button' class='pt-1 btn-shape-weekend text-decoration-none align-middle' data-bs-toggle='tooltip' data-bs-placement='left' data-bs-title='Click to record time'>{day}</a></span><div class='day'> {d} </div>" elif date.today() == date(self.year, … -
Accessing an image field inside a Django model
So I'm trynna access the first image of the product but for some reason it's not showing. First these are the models that I have: class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=20, decimal_places=2) stock = models.PositiveIntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE, default='', null=True) image = models.ManyToManyField('Image', blank=True) serial_number = models.CharField(max_length=100, blank=True) def __str__(self): return self.name class Image(models.Model): name = models.CharField(max_length=100, default='') image = models.ImageField(upload_to='product_images/') def __str__(self): return self.name As you can see they're connected. Reason why is because each object has multiple images. I only want to display the first image. So here's the view: def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('Cart:', cart) items = [] order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': True} cartItems = order['get_cart_items'] for i in cart: cartItems += cart[i]['quantity'] product = Product.objects.get(id=i) total = (product.price * cart[i]['quantity']) order['get_cart_total'] += total order['get_cart_items'] += cart[i]['quantity'] item = { 'product':{ 'id': product.id, 'name': product.name, 'price': product.price, 'imageURL': product.image.first().image.url }, 'quantity':cart[i]['quantity'], 'get_total': total } items.append(item) In this view, when the user is authenticated, I'm able to display the product's info with no problems in the html. I used a for loop … -
How does Celery worker run the code defined elsewhere in a task?
I tried reading official documentation as well as other SO threads, but it is still not clear how Celery works. From what I understand: Django app: Celery is installed in Django (or any app) where @shared_task decorator function defines the work to be performed. Message broker: A message broker gets this task from 1. and queues it. Celery Worker: A completely separate Celery worker picks up the task and runs it. This worker can be in a completely different machine even, so long as it has access to the message broker. So, then the burning question is: How does the Celery worker get the code defined in @shared_task to run the task? Basically, how does 3. get what's defined in 1. if they are only connected using a message broker? Is the python code stored in the message broker as string? What is the data structure of the message broker item/record? -
How to pass multiple arguments to a template tag with multiple "as" arguments in Django Template?
With @register.simple_tag, I defined the custom tag test() which has 2 parameters as shown below: from django.template import Library register = Library() @register.simple_tag def test(first_name="John", last_name="Smith"): return first_name + " " + last_name Then, I pass "Anna" and "Miller" to test() with two as arguments in Django Template as shown below: {% test "Anna" as f_name "Miller" as l_name %} {{ f_name }} {{ l_name }} But, there is the error below: django.template.exceptions.TemplateSyntaxError: 'test' received too many positional arguments Actually, there is no error if I pass only "Anna" to test() with one as argument as shown below: {% test "Anna" as f_name %} {{ f_name }} Output: Anna Smith And, there is no error if I pass "Anna" and "Miller" to test() without as arguments as shown below: {% test "Anna" "Miller" %} Output: Anna Miller So, how can I pass multiple arguments to a template tag with multiple as arguments in Django Template? -
Can't get celery results in django-db backend but my settings seem to be correct (Django, Postgres, Redis)
I cannot get celery results to store in my django-db backend- I have tried many solutions without any luck. I'm kind of stuck at this point.. My setup is using Django 4.2, Postgres db (cockroach-db), and Redis (Heroku). I start django normally, then I start the celery worker with this command: celery -A kmaofny worker --loglevel=info -E My celery worker see's the tasks, and they are completed, however it does not store the results in my database. Here are my settings and configurations: settings.py INSTALLED_APPS = [ ... 'django_celery_results', ... ] DATABASE_URL = POSTGRES_CREDS['URI'] DATABASES = { 'default': dj_database_url.config(default=DATABASE_URL, engine='django_cockroachdb') } # Celery Configuration REDIS_URL = os.environ.get('REDIS_URL', BROKER_URL) CELERY_BROKER_URL = REDIS_URL CELERY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' DJANGO_CELERY_RESULTS_TASK_ID_MAX_LENGTH=191 CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 celery.py import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'kmaofny.settings') app = Celery('kmaofny') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() init.py from .celery import app as celery_app __all__ = ('celery_app',) Any help is appreciated- I am stuck at this point with no errors. Further, I get <django_celery_results.backends.database.DatabaseBackend object at 0x000001A9B3B64040> when I …