Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'bytes' object has no attribute '_committed'
I will create multi image add page. But the following error occurs. Could your help me? I think mistake in views.py. I'm not sure. Note : It's frustrating that Stackoverflow asks for a long explanation. error: AttributeError at /en/projects/multiimageadd/10/ 'bytes' object has no attribute '_committed' @login_required @permission_required('is_superuser') def MultiImageAdd(request, id): blog = BlogModel.objects.filter(id=id).first() if request.method == 'POST': images = request.FILES['images'] for image in images: Images.objects.create(project=project, image=image) return redirect("home") return render(request,"multiImage.html") <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <div class="card"> <div class="card-header"> </div> <div class="card-body"> <form class="needs-validation" method="POST" action="" enctype="multipart/form-data" novalidate=""> {% csrf_token %} <div class="row"> <div class="col-sm-12"> <div class="form-group row"> <label for="id_images" class="col-xl-3 col-md-4">Images:</label> <span class="form-control col-md-8"> <input required type="file" name="images" id="id_images" multiple> </span> </div> </div> </div> <div class="pull-right"> <button class="btn btn-primary" type="submit">Save</button> </div> </form> </div> </div> </div> </div> </div> models.py class Images(models.Model): blog = models.ForeignKey(BlogModel, related_name='blogmodel', on_delete=models.CASCADE, blank=True,null=True) image = models.ImageField(blank=False, null=True) -
Custom Error Reporting Capability in Django
I have setup the ADMINS variable in settings.py. I've configured my email and everything works as intended. I get a very good, detailed error message from my production box when it encounters an error. I also understand the MANAGERS variable and how it can handle 404 errors and send alerts. OK, fine... However, I have another use case whereas I'd like to send the error report (standard 500 detailed report) to a set of individuals based on the app the error occurs in (or a default if outside a specific app). So, let's say I have 1 person developing/supporting webapp1 and 2 supporting webapp2. If the error occurs in webapp2, I only want to send to those 2 and if in webapp1 the person developing/supporting that app. If the error doesn't occur in a specific app, I'd send to everyone defined in ADMINS variable. First off, is there a better way to address this use-case than through custom error process? and.. Secondly, is this possible within the custom error capability? -
Django3: change style of selection field in admin view?
In my django project I have a project model with a many to many field for users, which can be added and removed. This works well, however, the selection field in the admin view is a bit inconvenient. Selection works by clicking on the usernames. To select multiple users CTRL has to be held. If you do that wrong all selections can be removed just by clicking on a certain item. So, it is easy to loose the current selection with this tool. A better tool would be something that works like the user-groups and -rights window, with two separate panels, unselected and selected items. My question is whether this tool: can be replaced this tool: So that users not joined the project are listed on the left and joined users are on the right? Or vice versa. -
Problem deployment Django Rest Framework app to Heroku
I'm trying to deploy a simple app to Heroku, and recently started getting the following error: remote: -----> $ python manage.py collectstatic --noinput remote: Post-processing 'drf-yasg/swagger-ui-dist/swagger-ui-es-bundle.js' failed! remote: Traceback (most recent call last): remote: File "/tmp/build_33d50075/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_33d50075/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 417, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 134, in collect remote: raise processed remote: whitenoise.storage.MissingFileError: The file 'drf-yasg/swagger-ui-dist/swagger-ui-es-bundle.js.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f4a4526efb0>. remote: The JS file 'drf-yasg/swagger-ui-dist/swagger-ui-es-bundle.js' references a file which could not be found: remote: drf-yasg/swagger-ui-dist/swagger-ui-es-bundle.js.map remote: Please check the URL references in this JS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic … -
How to group by in ManyToMany relationships in Django?
I am creating a web application with Django and I have some problems using its ORM to make queries. I have these models: class Country(models.Model): name = models.CharField(max_length=25) class Song(models.Model): title = models.CharField(max_length = 25) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="songs") ratings = models.ManyToManyField(Country, through='Rating') class Rating(models.Model): rating = models.PositiveSmallIntegerField() country_id = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) song_id = models.ForeignKey(Song, on_delete=models.SET_NULL, null=True) A Country rates many Songs (with ratings 1-10), and a Song can be rated by many Countries, so there's a ManyToMany relationship between these models through the Rating table. I am making a query to get the number of 10 points a Song has received, but I don't know how. To do that, I tried this query: result = Rating.objects.filter(rating=10).values('song_id').annotate(ten_points = Count('rating')) I read Django documentation and I understood that values() method is like group by clause in SQL, but it doesn't work because this query returns a queryset of dictionaries like this: <QuerySet [{'song_id': 1, 'ten_points': 1}, {'song_id': 2, 'ten_points': 1}, {'song_id': 2, 'ten_points': 1}, {'song_id': 3, 'ten_points': 1}, {'song_id': 3, 'ten_points': 1} Why am I getting different dictionaries with the same key and value 1, instead of a dictionary with the key and the value the total number of … -
hello need help for displaying comments on per post on home page
can some one be able to help me out please. i want to display number of comments on blog home page where all post is showing up. i want to show number of comments on little comment icon under every post,is having. thanks my model: class BlogPost(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=60, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) image = models.ImageField(upload_to=upload_location, null=False, blank=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date_published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date_updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.CharField(max_length=20, choices=CATEGORIES_NAME, default='Entertainment') slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title class BlogComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(Account, on_delete=models.CASCADE) post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) timestamp = models.DateTimeField(default=now) def __str__(self): return str(self.sno) my homepage view: BLOG_POSTS_PER_PAGE = 4 def home_screen_view(request): context = {} query = "" if request.GET: query = request.GET.get('q', '') context['query'] = str(query) blog_posts = sorted(get_blog_queryset(query), key=attrgetter('date_updated'), reverse=True) comments = BlogComment.objects.all() # Pagination page = request.GET.get('page', 1) blog_posts_paginator = Paginator(blog_posts, BLOG_POSTS_PER_PAGE) try: blog_posts =blog_posts_paginator.page(page) except PageNotAnInteger: blog_posts =blog_posts_paginator.page(BLOG_POSTS_PER_PAGE) except EmptyPage: blog_posts =blog_posts_paginator.page(blog_posts_paginator.num_pages) context['blog_posts'] = blog_posts context['comments'] = comments return render(request, "personal/home.html", context) -
Django3: ManyToMany field causes: Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin
I have a custom user model without username, but using email instead. class User(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) uuid = models.CharField(max_length=36, default=uuid4, unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email And a project model that has multiple users: from user.models import User class Project(models.Model): project_id = models.AutoField(primary_key=True) name = models.CharField(max_length=256, unique=True, blank=False) created = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=10000, default="") slug = models.SlugField(max_length=256, unique=True) created_by = CurrentUserField(related_name='creator') users = models.ManyToManyField(User, related_name='users') .... My UserAdmin model looks like this: class CustomUserAdmin(UserAdmin): list_display = ("email", "is_staff", "is_superuser") readonly_fields = ("last_login", "date_joined", "uuid") ordering = ("email",) fieldsets = ( ( "Fields", { "fields": ( "email", "uuid", "date_joined", "last_login", "is_active", "is_staff", "is_superuser", "groups", "user_permissions", "password", ) }, ), ) admin.site.register(User, CustomUserAdmin) However, when I go to admin view to a project instance and try to add user I get: FieldError at /admin/user/user/add/ Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Request Method: GET Request URL: http://localhost:8000/admin/user/user/add/?_to_field=id&_popup=1 Django Version: 3.2.11 Exception Type: FieldError Exception Value: Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. I added my user model as a default model in settings, so I don't know … -
update the basket without using update button just with select tag Django & ajax
hi guys my form need update button to sending data but I want to send data(quantity of product) by select tag and no one has a solution **ajax $(document).on("click", ".update-button", function (e) { e.preventDefault(); var prodid = $(this).data("index"); $.ajax({ type: "POST", url: '{% url "basket:basket_update" %}', data: { productid: $(this).data("index"), productqty: $("#select" + prodid + " option:selected").text(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { total = (parseFloat(json.subtotal) + 11.50).toFixed(2); document.getElementById("basket-qty").innerHTML = json.qty; document.getElementById("subtotal").innerHTML = json.subtotal; document.getElementById("total").innerHTML = total; }, error: function (xhr, errmsg, err) {}, }); }); **html <label for="select">Qty</label> <select id="select{{product.id}}" style="width:50px;height:31px;"> <option value="" selected disabled hidden>{{item.qty}}</option> <option value="">1</option> <option value="">2</option> <option value="">3</option> <option value="">4</option> </select> <a type="button" id="update-button" data-index="{{product.id}}" class="update-button text-decoration-none small ps-3">Update</a> -
How to solve error 401 unauthorized login in DRF simple jwt user login
I am creating DRF authentication APIs for Abstract Base users in my Django project and I am using simple JWT. The registration and email verification APIs work fine, but when I try to log in using the credentials of a valid user, I get an error 401 unauthorized access. Here is my login class-based view in views.py: class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) Here is the LoginSerializer in serializers.py class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255, min_length=3) password = serializers.CharField(max_length=68, min_length=8, write_only=True) username = serializers.CharField(max_length=255, min_length=3, read_only = True) tokens = serializers.CharField(max_length=68, min_length=8, read_only = True) class Meta: model = User fields = ['email', 'password', 'username', 'tokens'] def validate(self, attrs): email = attrs.get('email', '') password = attrs.get('password', '') user = auth.authenticate(email=email, password=password) if not user: raise AuthenticationFailed('Invalid Credentials, try again!') if not user.is_active: raise AuthenticationFailed('Acccount disabled, please contact admin') if not user.is_verified: raise AuthenticationFailed('Email is not verified') return { 'email': user.email, 'username': user.username, 'tokens': user.tokens } return super().validate(attrs) In settings.py the only settings dealing with DRF-simple Jwt are: REST_FRAMEWORK = { 'NON_FIELD_ERRORS_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } So the error raised is "Invalid credentials" meaning that details of the user don't exist, … -
django collectstatic on server
Recently, my DB on my server has shat the bed. I imagine the mistake was somewhere on my end and my wagtail database ended up being wiped clean. I've managed to get my sqlite db working again but my collectstatic is still failing. I have tried renaming my static folder using mv static staticold and reran python manange.py collecstatic but it still fails. The error message reads: Post-processing 'scss/main.css' failed! ... ... raise ValueError("The file '%s' could not be found with %r." % (filename, self)) ValueError: The file 'images/5f5a5b3515c4dd0c2c455925_110642301_938622823267359_7859124022958180678_n201.jpg' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x7f00badf6f60>.` I don't really care about these old images, though I would like my js and css files to be updated with collectstatic -
user table not created on django deployment but superuser created on heroku bash
I'm trying to upload my first django app and I've been struggle with this issue for sometime, help is appreciated. I already set up my project to be on heroku, I followed this tutorial: https://www.youtube.com/watch?v=6DI_7Zja8Zc in which django_heroku module is used to configure DB, here is the link to library https://pypi.org/project/django-heroku/ The app throws the error on login as if user tables didn't exist but I already create a super user using the heroku bash feature, after apply migrations using "heroku run python manage.py migrate". When I run "ls" command on heroku bash this is my directory: manage.py Procfile requirements.txt runtime.txt smoke staticfile "smoke" is my folder app, should I could see the db in this directory? if the db was not created how could I create a superuser using heroku bash feature? This is the DB configuration that django gives me on server: {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'NAME': PosixPath('/app/db.sqlite3'), 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': ''}} I see that db is sqlite3 and should be postgreSQL but I understand that django-heroku library should do that. I don't know … -
Getting Django migration error "sequence must have same owner as table it is linked to", but all tables and sequences have the same owner
I'm trying to run a migration in a Django project. (Django 3.1, Python 3.9.9) I'm in my virtual environment. I keep getting a puzzling error. python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, intake, sessions Running migrations: Applying intake.0021_auto_20220115_1147...Traceback (most recent call last): File "/Users/me/Sites/client/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.ObjectNotInPrerequisiteState: sequence must have same owner as table it is linked to But when I list out my tables and sequences, they all have the same owner. intake=# \dt List of relations Schema | Name | Type | Owner --------+----------------------------+-------+----------- public | auth_group | table | dbuser public | auth_group_permissions | table | dbuser public | auth_permission | table | dbuser public | auth_user | table | dbuser public | auth_user_groups | table | dbuser public | auth_user_user_permissions | table | dbuser public | django_admin_log | table | dbuser public | django_content_type | table | dbuser public | django_migrations | table | dbuser public | django_session | table | dbuser public | intake_byattorney | table | dbuser public | intake_client | table | dbuser (12 rows) intake=# \ds List of relations Schema | Name | Type | Owner --------+-----------------------------------+----------+----------- public | auth_group_id_seq | sequence … -
I want that in my project the members who are having role as manager should not be able to see the priority field while updating the form
MODELS.PY : class Ticket(models.Model): status_choice = ( ("Approval","Approval"), ("Assigned","Assigned"), ("Scoping","Scoping"), ("In Progress","In Progress"), ("Completed","Completed"), ("Cancelled","Cancelled"), ("Rejected", "Rejected") ) priority_choice = ( ("High","High"), ("Moderate","Moderate"), ("Low","Low"), ) category = models.ForeignKey("vats.Category",on_delete=models.CASCADE) subcategory = models.ForeignKey("vats.Subcategory",on_delete=models.CASCADE) title = models.CharField(_("Title"), max_length=50,) problem_descp = models.TextField(_("Problem Description"), max_length=500) created_by = models.ForeignKey("registration.User", related_name=_("Issues"), on_delete=models.CASCADE) priority = models.CharField(_("Priority"), max_length=50,null=True,blank=True,choices=priority_choice) start_date_time = models.DateTimeField(_("Start Date Time"), auto_now_add=True) end_date_time = models.DateTimeField(_("End Date Time"), null=True, blank=True) assigned_to = models.ForeignKey("registration.User",related_name=_("Tasks"), on_delete=models.SET_NULL,null=True,blank=True) status = models.CharField(_("Status"), max_length=50,choices=status_choice,null=True,blank=True) class Meta: verbose_name = _("Ticket") verbose_name_plural = _("Tickets") def __str__(self): return self.title def is_open(self): if self.status == 'Completed' or self.status == 'Cancelled': return False return True Forms.py : class TicketForm(forms.ModelForm): # subcategory = forms.ModelChoiceField(queryset=Subcategory.objects.filter(category__id = self.fields['category'])) class Meta: model = Ticket fields = ("category", "subcategory", "title","problem_descp") class TicketUpdateForm(forms.ModelForm): class Meta: model = Ticket fields = ("category","subcategory", "title","problem_descp","status","assigned_to","priority") def __init__(self, *args, **kwargs): super(TicketUpdateForm,self).__init__(*args, **kwargs) self.fields['category'].disabled = True self.fields['subcategory'].disabled = True self.fields['title'].disabled = True self.fields['problem_descp'].disabled = True -
Using Django-modeltranslation in combination with PostgreSQL SearchVector
I'm using django-modeltranslation to translate model fields. And suppose I have the following model (where the name is translated in the DB): class Book(models.Model): name = models.CharField(max_length=90) Then, in a DRF view, I have an endpoint that takes a query text and searches through the book names using this code: from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank class BookView(APIView): def get(self, request): q = request.get('q') vector = SearchVector('name') # this is where the issue is query = SearchQuery(q) matches = Book.objects.annotate(rank=SearchRank(vector, query))\ .filter(rank__gt=0.1)\ .order_by('-rank') # etc. This works great when I was working with English only. But now I added a new language, and all aspects of the localisation are working fine, except this search. It's looking at the name_en field values only. If the target language is German for example, and I explicitly change the following line from: vector = SearchVector('name') to: vector = SearchVector('name_de') Then the search works over the correct field. Is there a way to pass in the correct field to SearchVector? -
Current data on django containers get cleared after rebuilding a Container
I dockerized my Django application, but every time and make an update and rebuild images, all the data gets cleaned. Below are the Dockerfile and docker-compose.yml files: Docker ########### # BUILDER # ########### # pull official base image FROM python:3.8.10-buster as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apt-get update \ && apt-get install -y postgresql gcc python3-dev libpq-dev musl-dev python3-setuptools binutils libproj-dev gdal-bin # lint RUN pip3 install --upgrade pip RUN pip3 install flake8 COPY . . # RUN flake8 --ignore=E501,F401 . # install dependencies COPY ./requirements.txt . RUN pip3 wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.8.10-buster # create directory for the app user RUN mkdir -p /home/app # create the app user # RUN addgroup -S app && adduser -S app -G app RUN useradd app && usermod -aG app app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME WORKDIR $APP_HOME RUN mkdir $APP_HOME/static WORKDIR $APP_HOME RUN mkdir $APP_HOME/mediafiles WORKDIR $APP_HOME # install dependencies RUN apt update && apt install libpq-dev binutils libproj-dev gdal-bin -y COPY --from=builder … -
Why am I getting error "Client with IP address x.x.x.x isnt allowed to connect to this MySql server" when trying to connect to MySql from Django?
I am trying to create tables for my models in this full stack project (Django/React). After I run the python manage.py migrate command I'm expecting to see: Migrations for X: X\migrations\0001_initial_py - Create model Departments - Create model Employees Instead I get the following error: (9000, "Client with IP address 'X' is not allowed to connect to this MySQL server." I have tried the command pip install pymysql then edited the settings.py file adding import pymysql pymysql.install_as_MySQLdb() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mytestdb', 'USER': 'testadmin@mytestmysql', 'PASSWORD': 'XXXXXXXXXX#', 'HOST': 'mytestmysql.mysql.database.XXXXXXXXXXXXX.com', 'PORT': '3306' -
How can I send React variable to Django view?
I'm using Django and React for a project that consumes Trello's API. I created functions in django views.py that will get user's boards, lists and cards. The problem is, to get a list, I need that the user select a board, because the list's endpoint requires a board id (and so on). I can show the user's boards on my react page and storage the board's id on a variable in Index.js (on pages folder), but I have no ideia how I can send the selected board id to views.py to consume Trello's api according to the user's selected board. Here's my code. Django views.py: from rest_framework.decorators import api_view from rest_framework.response import Response from dotenv import load_dotenv from treegia.settings import TRELLO_URL import os import requests load_dotenv() TRELLO_KEY = os.getenv('TRELLO_KEY') TRELLO_TOKEN = os.getenv('TRELLO_TOKEN') @api_view(['GET']) def get_boards(request): if request.method == 'GET': board_endpoint = TRELLO_URL+'members/me/boards' jsonObj = {'fields':'name,id', 'key':TRELLO_KEY, 'token':TRELLO_TOKEN} boards = requests.get(board_endpoint, json=jsonObj).json() return Response(boards) @api_view(['GET']) def get_lists(request): if request.method == 'GET': list_endpoint = TRELLO_URL+ 'boards/' + id_board + '/lists' jsonObj = {'fields':'name,id', 'id':id_board, 'key':TRELLO_KEY, 'token':TRELLO_TOKEN} lists = requests.get(list_endpoint, json=jsonObj).json() return HttpResponse(lists) @api_view(['GET']) def get_cards(request): if request.method == 'GET': card_endpoint = TRELLO_URL+ 'lists/' + id_list + '/cards' jsonObj = {'fields':'name,id', 'id':id_list, 'key':TRELLO_KEY, … -
login via dj-auth with view
i need login via system(self) inside of a view of django that import dj-rest-auth. i try these code but get error: value = { "username" : '0967826354', "password" : '##heelo!!heelo' } data = LoginView.as_view()(value) return Response(data) error: sensitive_post_parameters didn't receive an HttpRequest. If you are decorating a classmethod, be sure to use @method_decorator. -
Bootstrap main element goes behind sidebar
I am using the Dashboard example from Bootstrap 5: https://getbootstrap.com/docs/4.0/examples/dashboard/. It runs fine when I open the html file outside of my app. But then I add it to my Django Web App and the element goes behind the side bar as shown below, which leaves a gap on the right side of the page: The page should look like this, where the graph doesn't go behind the sidebar Here is the relevant code I'm using: Dashboard.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale = 1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Dashboard Template for Bootstrap</title> <link rel="stylesheet" href="{% static 'appbase.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0"> <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Company name</a> <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search"> <ul class="navbar-nav px-3"> <li class="nav-item text-nowrap"> <a class="nav-link" href="#">Sign out</a> </li> </ul> </nav> <div class="container-fluid"> <div class="row"> <nav class="col-md-2 d-none d-md-block bg-light sidebar"> <div class="sidebar-sticky"> <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link active" href="#"> <span data-feather="home"></span> Dashboard <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <span data-feather="file"></span> Orders </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <span data-feather="shopping-cart"></span> Products </a> </li> <li … -
set default image on model from s3 bucket
For user profiles i have a default image on the model image = models.ImageField(default='default.jpg', upload_to='profile_pics') I now have this image in the s3 bucket. How can I reference this image from the s3 bucket and not local if I try and use the direct image path on the model https://uploadfiles.s3.amazonaws.com/profile_pics/default.jpg or the bucket path 'uploadfiles/profile_pics/default.jpg i get the error This backend doesn't support absolute paths I'm not sure how else I would reference the image I do have proper access to the buckets and uploading is working properly -
How to merge more than one queryset in django
I'd like to merge more than one queryset and keep a common column called "line_nm" I have created some queryset with a formula, for: day, week and year models.py class PbaSetOperator(models.Model): work_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) prodc_qty = models.IntegerField(blank=True, null=True) work_mh = models.FloatField(blank=True, null=True) in_house = models.FloatField(blank=True, null=True) reduction = models.FloatField(blank=True, null=True) views.py set_operator_today = set_operator.filter(work_ymd = date).values('line_nm').order_by('line_nm').annotate( set_operator_today_value=(480 * (Sum('in_house') / Sum('work_mh')) set_operator_week = set_operator.filter(work_ymd__range = (getWeekStart(), getWeekEnd())).values('line_nm').order_by('line_nm').annotate( set_operator_week_value=(480 * (Sum('in_house') / Sum('work_mh')) set_operator_year = set_operator.filter(work_ymd__range = (getYearStart(), geYearEnd())).values('line_nm').order_by('line_nm').annotate( set_operator_year_value=(480 * (Sum('in_house') / Sum('work_mh')) The expected result is a queryset like bellow: 'line_nm':01, 'set_operator_today_value':100, 'set_operator_week_value':110, 'set_operator_year':115 How can I do it? I have tried the chain method of itertools and convert to a list, however without success. There is a common column called "line_nm" and I want to use it like a left join. -
How to modify unchanged model admin inlines?
Kind of duplicate of both of these: How to force-save an "empty"/unchanged django admin inline? How to force creation of unchanged django admin inline object in django 1.9 But I am still wondering is there any better way to do it in any later Django updates? I aimed to modify my model admin stacked inline objects (pre or post save doesn't matter) when parent model admin instance is changed. I tried overriding save_formset and save_related in model admin class as written in Django docs here and here using commit=False. For example: def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.any_field = "value" instance.save() The method formset.save(commit=False) returns inline form instances only if they are changed on Django Admin panel as mentioned in django docs, but it doesn't return list of inline objects if they are not changed, even after sending commit=False. I need to edit those inline objects regardless if they were changed on admin panel or not. -
Django how to stop BackgroundScheduler when application stops
I'm currently running a scheduled task with BackgroundScheduler, it works fine but when a finish the app execution with Ctrl+C for example, the job is still present in django_apscheduler_djangojob table, so any time further that I run the application the previous job will start again and a new one will be launched either, resulting in duplicates. def start(): scheduler = BackgroundScheduler(timezone='America/Sao_Paulo') scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job(telemetry.requestData, 'interval', minutes=1, name='requestData', jobstore='default') register_events(scheduler) scheduler.start() -
Django ASO booking system
Hey i have a problem about make proper booking system in my ASO sercvice. I wanna that when customer fill a form to make reservation can see the nearest available days. I tried to making somethink in init of this form but cant undestand how to refer to calendar queryset. Someone could give me some tips or code how to handle this issue? -
Django relation views not showing checklists that belong to each task
I want to display under each task, each checlists that belong to the given task My models class Project(models.Model): project_manager = models.ForeignKey(Profile, on_delete=CASCADE) title = models.CharField(max_length=55, null=True, blank=True) developers = models.ManyToManyField(Profile, related_name='projects') slug = models.SlugField(max_length=500, unique=True, blank=True) description = models.TextField(default="Project description") date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() due_date = models.DateTimeField() teams = models.ForeignKey(Team, blank=True, null=True, on_delete=CASCADE) tasks = models.ManyToManyField("Task", blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def get_url(self): return reverse('project_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def num_task(self): return self.tasks.count() @property def num_task_completed(self): return self.tasks.filter(task_completed = True).count() class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Task, self).save(*args, **kwargs) def __str__(self): return self.title def get_url(self): return reverse('task_detail', kwargs={ 'slug':self.slug }) class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() check_completed = models.BooleanField(default=False) task = models.ForeignKey(Task, blank=True, null=True, related_name='tasks', on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, **kwargs) def return_url(self): return reverse('project_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title and in my view where …