Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
use of select_related in this case of django rest?
I have a situation where I am not sure whether I would be using select_related or not. I have a model like this: class Example(models.Model): title = models.CharField(max_length=255, blank=True) message = models.TextField(blank=True) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name="user_example", ) /................./ Now in my view I have use filtering logic like this: def get_queryset(self): search = self.request.query_params.get("search", None) if search_query is not None: queryset = Reactions.objects.filter( Q(user__name__icontains=search) | Q(user__email__icontains=search) ).distinct() Here Example model has a fk relation with User, so its a forward relation not a reverse relation. Should I be appeding .select_related('user').filter(...) in this above example to reduce the no of queries or there is no need here...I can't figure it out. -
Retrieve the distinct results with all columns fields in django model queryset
Query to be fetched from model Listingimages with distinct results. In my model featured_image expects multiple images as in form input attribute has multiple, but i need only one value from featured_image column with respective foreign key listingproducts_id. I am using the mysql DB. So please help me to solve the problem. My models looks as class Listingproducts(models.Model): title = models.CharField(max_length=200,null=True) price = models.IntegerField(null=True) descriptions = models.TextField(max_length=200,null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Listingimages(models.Model): listingproducts = models.ForeignKey(Listingproducts,on_delete=models.CASCADE, null=True) featured_image = models.ImageField(null=True, default='default.jpg') created = models.DateTimeField(auto_now_add=True,null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) images = Listingimages.objects.values('listingproducts').distinct() i tried in my view Above queryset returns only listingproducts column, Also i am not able to retrieve listingproducts column. -
Which correct folder and path to aditional js file
I'm trying to add a js file to specific ModelAdmin. In admin.py i have: ... class AdminProductImages(admin.TabularInline): class Media: js = ('users/js/img_produt_upload.js',) class AdminProductModel(admin.ModelAdmin): inlines = [AdminProductImages,AdminProductFeatures] ... settings.py ... STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ... But with this set return 404 -
Django channels and file uploads
I'm learning Django on the fly so bear with me. My goal here is for a user to be able to upload a file, the server script process it and send the results on each iteration to the client live. My current structure is: User uploads a file (csv), this is read via views.py then renders the blank html view, JS in the html creates a new websocket, and well this is where I'm not able to pass data outside of consumers.py or process the data. I'm also not sure the structure of view > JS script > consumers > ? is the best route for processing files but I've not found much documentation on file uploads and channels. views.py from django.shortcuts import render import pandas as pd def someFunc(request): if request.method == "POST": global csvUpload csvUpload = pd.read_csv(request.FILES['filename']) return render(request, 'app/appPost.html') I render the view here first so that the blank page displays prior to the script running. appPost.html JS script var socket = new WebSocket('ws://localhost:8000/ws/app_ws/') socket.onmessage = function(event){ var data = JSON.parse(event.data); console.log(data); var para = document.createElement("P"); para.innerText = data.message; document.body.appendChild(para); } consumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class WSConsumer(WebsocketConsumer): def connect(self): self.accept() self.render() async_to_sync(self.add_group)('appDel_updates_group') … -
Getting the product.id in my django slug product details
I'm having issues trying to get my product.id in my product_details templates. This is my views.py product_details def product_details(request, slug): data = cartData(request) cartItems = data['cartItems'] post = get_object_or_404(Product, slug=slug) context = { 'post': post, 'cartItems': cartItems, } return render(request, 'e_commerce/product_details.html', context) models.py class Product(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=200, unique=True, null=True, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2) image = models.ImageField(upload_to='product_image', null=True, blank=True) digital = models.BooleanField(default=False,null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,default=1) description = models.CharField(max_length=250, default='', null=True, blank=True) size = models.CharField(max_length=200, null=True, blank=True, help_text='Input size of product') urls.py path('<slug:slug>/', views.product_details, name='product_details'),#e_commerce details page Then the product_details template: <div class="container"> <div class="card"> <div class="container-fliud"> <div class="wrapper row"> <div class="preview col-md-6"> <div class="preview-pic tab-content"> <div class="tab-pane active" id="pic-1"><img src="{{ post.image.url }}" /></div> </div> </div> <div class="details col-md-6"> <h3 class="product-title">{% block title %} {{ post.name }} {% endblock title %}</h3> <div class="rating"> <div class="stars"> </div> </div> <h5 class="product-description">{{post.description }}</h5> <h4 class="price">price: <span>NGN {{ post.price }}</span></h4> <h5 class="sizes">size: {{ post.size }}</h5> <h5 class="lead">Category: {{ post.category }}</h5> <hr> <button data-product=**{{product.id}}** data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> </div> </div> </div> </div> </div> Everything is working out fine and good except getting the product.id. I need it in order to consume the javascript function I created to …