Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter JSONField by key value in Django to retrieve similar values using MySQL/MariaDB database
I am trying to retrieve similar values to a specific key value from a JSONField using a MySQL database. I have used 3 different options as listed for views.py all of which do not work. According to Django documentation (https://docs.djangoproject.com/en/3.1/topics/db/queries/#containment-and-key-lookups) this can be done with an exact match to the key value, yet I would like to filter with the value only being similar and not exact. There is an example for using KeyTextTransform or KeyTransform (https://code.djangoproject.com/ticket/27205) but this is used with PostgreSQL only. Is there another way of doing this with a MySQL or MariaDB database? A post request is made to the following end-point with parameter name description as follows: http://localhost/get_meta/?description=text Data Example: { "meta": { "description": "The description text.", "field": 1 } } models.py class Model(models.Model): meta = models.JSONField(default=dict) views.py Option 1: def get_meta(self, request): queryset = Model.objects.filter(meta__contains=request.GET.get('description') or "") serializer_class = ModelSerializer(queryset, many=True) data = {'data': serializer_class.data} return Response(data) Option 2: def get_meta(self, request): queryset = Model.objects.filter(meta__description__contains=request.GET.get('description') or "") serializer_class = ModelSerializer(queryset, many=True) data = {'data': serializer_class.data} return Response(data) Option 3: def get_meta(self, request): queryset = Model.objects.filter(meta__contains={'description':request.GET.get('description') or ""}) serializer_class = ModelSerializer(queryset, many=True) data = {'data': serializer_class.data} return Response(data) -
Cannot assign "<QuerySet [<Profile: admin>, <Profile: test>]>": "Notifications.user" must be a "User" instance
when i get the user followers i got this err Cannot assign "<QuerySet [<Profile: admin>, <Profile: test>]>": "Notifications.user" must be a "User" instance. my code is #fun in models def user_add_post(sender, instance, *args, **kwargs): post = instance user = Profile.objects.filter(following=post.author.user) profile = Profile.objects.all() sender = post.author.user text_preview = post.title[:50] notify = Notifications(post=post, sender= sender, user = user, text_preview=text_preview, notifications_type=1 ) notify.save() post_save.connect(Post.user_add_post, sender=Post) how to fix this err -
Nested Admin files access forbidden on server
I have implemented NestedModelAdmin in my model in Django Admin panel. I have done this in order to add/edit/delete child objects of a model. The code is working fine on my local machine, but I am getting following error on the server, which is preventing me from perform CRUD operations in my modal in the admin panel. GET https://amazonaws.com/static/nested_admin/dist/nested_admin.min.css net::ERR_ABORTED 403 (Forbidden) GET https://amazonaws.com/static/nested_admin/dist/nested_admin.min.js net::ERR_ABORTED 403 (Forbidden) Any idea why this error might be occurring? -
Using Subquery to annotate Count of an unrelated model
This can be a duplicated of this question but I didn't understand if it is possible or not. I have two models that are unrelated (or have a nested nested relation) class Cycle(models.Model): start_date = models.DateField() end_date = models.DateField() class Event(models.Model) created_at = models.DateField() What I want is filter the current Cycle and to annotate the number of Events that were created between the Cycle's start_date and end_date, all in one query. What I have so far: now = timezone.now() number_events = Event.objects\ .filter(created_at__gte=OuterRef('start_date'), created_at__lte=OuterRef('end_date')) cycle = Cycle.objects \ .filter(start_date__lte=now, end_date__gte=now) \ .annotate(number_events=Count(number_events)) \ .first() This creates an invalid syntax, saying subquery must return only one column If I add values("id") in the number_events query, it raises more than one row returned by a subquery used as an expression If I add values("id")[:1] it works, but only counts one Event And if I try to do the query in SQL I can retrieve data SELECT *, (select COUNT(*) AS "number_events" FROM "events_event" U0 WHERE (U0."created_at" >= "cycles_cycle"."start_date" AND U0."created_at" <= "cycles_cycle"."valid_until")) FROM "cycles_cycle" WHERE ("cycles_cycle"."start_date" <= '2022-06-01' AND "cycles_cycle"."end_date" >= '2022-06-01') GROUP BY "cycles_cycle"."id" limit 1; Is there a way to create this query in django, or is it impossible … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect - DJANGO
so i was trying get files what i was upload it to html. but when i run the code, the web got error message : ModuleNotFoundError: No module named 'audio' OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'F:\KULIAH\SEMESTER8\SKRIPSI\MusicLockApp\' maybe i was made mistake from syntax. please help me to check it! #html {% for record in audio %} <audio controls="controls"> <source src="{{record.audio}}" type="audio/mp3"> </audio> {% endfor %} #urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), url(r'^$', include('audio.urls')), path('audio', views.Audio_store), ] #models fs = FileSystemStorage(location='media/mp3') fss = FileSystemStorage(location='media/txt') class Audio_store(models.Model): password=models.FileField(storage=fss, null=True) audio=models.FileField(storage=fs, null=True) def __str__(self): return self.audio #views def homepage(request): form = AudioForm() audio = Audio_store.objects.all() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("homepage") context={'form':form, 'audio':audio} return render(request, "homepage.html", context=context) -
Deleting an Item from the cart on Django not working
My "Remove" button to remove an item from cart is not working. My views.py file: from urllib.request import Request from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse_lazy from django.views.decorators.http import require_POST from requests import request from courses.models import Course from udemy.models import Enroll from .cart import Cart @require_POST def cart_add(request, slug): cart = Cart(request) # create a new cart object passing it the request object course = get_object_or_404(Course, slug=slug) cart.add(course=course, quantity=1, update_quantity=False) return redirect('cart:cart_detail') def cart_remove(request, slug): cart = Cart(request) course = get_object_or_404(Course, slug=slug) cart.remove(course) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) @login_required(login_url='/login') def cart_checkout(request): carts = Cart(request) for cart in carts: course = cart['course'] # course = get_object_or_404(Course, slug=course.slug) Enroll.objects.create(course=course, user_id=request.user.id) messages.success(request, 'Successfully checked out!') carts.clear() return redirect(reverse_lazy('cart:cart_detail')) My cart.html file: <div class="move-remove"> <div> <form action="" method="post"> {% csrf_token %} <input type="hidden" value="{{ course.slug }}"> <input type="submit" class="btn-success" value="Remove",name="Remove"> </form> </div> When I press the remove button it won't delete. I don't know why it is happening. whats wrong? Do I have to change in views or in my html file? -
Django - get objects from one table who belong to another objects in other table
I have a project to do which consists to creating a note manager in Django. So I created my tables in sql with foreign keys. And I have been facing a problem for several days. I have a page that lists all the students in the database, and I would like by clicking on a link, to be able to display all the notes belonging to each student. Here's my SQL tables (étudiants = students / Notes = grades) : sql students table / sql grade table models.py : class Etudiants(models.Model): numeroetudiant = models.BigIntegerField(db_column='numeroEtudiant', blank=True, null=True) # Field name made lowercase. nom = models.CharField(max_length=255, blank=True, null=True) prenom = models.CharField(max_length=255, blank=True, null=True) groupe = models.BigIntegerField(blank=True, null=True) photo = models.TextField(blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'etudiants' def __str__(self): return self.nom + " " + self.prenom class Notes(models.Model): examens = models.ForeignKey(Examens, models.DO_NOTHING, db_column='examens', blank=True, null=True) etudiant = models.ForeignKey(Etudiants, models.DO_NOTHING, db_column='etudiant', blank=True, null=True) note = models.BigIntegerField(blank=True, null=True) appreciation = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'notes' def __str__(self): return "Note de " + self.etudiant.nom + " " + self.etudiant.prenom + " à l'examen de " + self.examens.titre -
How can I generate and excel output from django python
Given a query set from my database, I am trying to output the results into an excel file. I have tried two versions of code... the code executes properly without outputting any error messages, but the excel file is not outputted, any suggestions on where I went wrong. import pandas as pd import csv, io, xlsxwriter from django.http import HttpResponseRedirect, HttpResponse, JsonResponse, FileResponse def print_excel(request) products = Product.objects.all() df = pd.DataFrame(list(products.values())) excel_file = io.BytesIO() xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter') df.to_excel(xlwriter, 'sheetname') xlwriter.save() #xlwriter.close() excel_file.seek(0) response = HttpResponse(excel_file.read(), content_type='application/ms-excel vnd.openxmlformats-officedocument.spreadsheetml.sheet') # set the file name in the Content-Disposition header response['Content-Disposition'] = 'attachment; filename=myfile.xls' return response I also tried the below approached where I tried to output an excel with the string rows import pandas as pd import csv, io, xlsxwriter from django.http import HttpResponseRedirect, HttpResponse, JsonResponse, FileResponse def print_excel(request) buffer = io.BytesIO() workbook = xlsxwriter.Workbook(buffer) worksheet = workbook.add_worksheet() worksheet.write('A1', "rows") workbook.close() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='myfile.xlsx') The two codes executes properly but I cant locate the excel file created. -
Adding a comment section with django
as title suggests I am trying to add a comment section to my website using the following code under movies app models.py class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') banner = models.ImageField(upload_to='movies_banner') category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10) status = models.CharField(choices=STATUS_CHOICES, max_length=2) cast = models.CharField(max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() created = models.DateTimeField(blank=True, default=timezone.now) slug = models.SlugField(blank=True, null=True) name = models.CharField(max_length=200, null=False, blank=False) class Comment(models.Model): movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE) commentor_name = models.CharField(max_length=200) comment_body = models.TextField() date_added = models.DateTimeField(auto_now=True) def __str__(self): return '%s - %s' % (self.movie.name, self.commentor_name) admin.py from django.contrib import admin from .models import Movie, MovieLinks, Comment admin.site.register(Movie) admin.site.register(MovieLinks) admin.site.register(Comment) under admin page I am able to add a comment https://i.stack.imgur.com/Tc5pp.png So up until now everything is configured correctly. the problem comes when I try to add it to the HTML using logic currently what we're looking to edit is line 70 - 82 but i've pasted the whole HTML as i have a feeling it'll be needed :) {% extends 'base.html' %} {% block body %} <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script> <main class="content"> <div class="single"> <section class="trailer"> <h3>Trailer</h3> <div class="trailer_frame"> <iframe width="560" height="315" src="{{object.movie_trailer}}" frameborder="0" allowfullscreen></iframe> </div> </section> <section … -
REACT + DJANGO app, uploading excel files into the backend, Django returns empty dictionary
So I have been trying to upload a excel file from the frontend using a post request to a Django backend, however whatever I do the request[FILES] python dictionary is empty. Does anyone have an idea of why this would happen? This is my POST view from the Django views.py file @api_view(["POST"]) @csrf_exempt def processFile(request, *args, **kwargs): data = request.data print(data.items()) print(str(data.get('file0'))) if len(request.FILES) == 0 : print("empty files") print(request.FILES) return Response("ok") And now the way I am making the POST request in the frontend. const fileList = async (actualFiles) => { var dataForm = new FormData(); console.log(actualFiles) for(let i=0;i<actualFiles.length;i++) { const id = 'file' + i; console.log("appending file" + i) dataForm.append(id, actualFiles[i]) } const res = await fetch(`http://localhost:8000/process-file/`, { method: 'POST', headers: { 'Content-Type': 'multipart/form-data; boundary=----somefixedboundary' }, body : dataForm, }) const data = await res.json() console.log("Data:" + data) } Worth mentioning: I have been trying for a while thinking the problem is in the request, however in the network tab on the browser I can see that it is all alright. I am adding the content type and boundary because according to Django documentation if you do not add those the server will not be able to process … -
'<' not supported between instances of 'int' and 'str' django Overlapping check
When I am checking overlapping in Django forms with this code i could not check the overlapping, geting the error of tuples How i can solve this error, form.py record=[] if count > 1: for i in range(count): start_run = self.data.get(f'runningdefinition_set-{i}-start_run',[]) end_run = self.data.get(f'runningdefinition_set-{i}-end_run',[]) application_run =self.data.getlist(f'runningdefinition_set-{i}-application_run',[]) record.append((i, start_run, end_run, application_run)) first_value=[] for j in record: first_value.append(j[0]) last_value=[] for k in record: last_value.append(k[1]) if first_value[0] < last_value[-1]: raise ValidationError("overlap not allowed") -
How can I automatically fill in the ModelChoiceFields?
I have three models. The model is as follows. models.py class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL) subject = models.ForeignKey(Subject, null=True, blank=True, on_delete=models.SET_NULL) class Category(models.Model): name = models.CharField(max_length=30, unique=True) slug = models.SlugField(max_length=20, unique=True, allow_unicode=True) subject = models.ForeignKey(Subject, null=True, blank=False, on_delete=models.SET_NULL) class Subject(models.Model): name = models.CharField(max_length=10, unique=True) slug = models.SlugField(max_length=20, unique=True, allow_unicode=True) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'category', 'subject', 'content'] widgets = { 'content': SummernoteWidget() } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({'class': 'textInput form-control form_title', 'placeholder': '제목을 입력하세요'}) self.fields['category'].widget.attrs.update({'class': 'form-select form-control form_category'}) self.fields['subject'].widget.attrs.update({'class': 'form-select form-control form_subject'}) category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label='카테고리를 선택하세요') In forms, 'subject' fields is ModelChoiceField and I want the 'subject' field to be automatically selected according to the value selected in 'category' -
How to add +/- button to a displayed Object list in django to increase or decrease object value
I'm new to Django and I want to display the items in my database and have a button next to each row that will add or decrease the value. I know how to do this in a form for single item, but not with them listed. Table with button to add and decrease -
{"non_field_errors":["Invalid data. Expected a dictionary, but got Company."]}
file company.py(models) from django.db import models COMPANY_TYPE = [('ИП', 'ИП'), ('АО', 'АО'), ('ТОО', 'ТОО')] class Company(models.Model): name = models.CharField(blank=False, max_length=255) company_type = models.CharField(blank=False, max_length=10, choices=COMPANY_TYPE, default='ИП') logo = models.CharField(blank=False, max_length=255) owner = models.ForeignKey('user.User', on_delete=models.CASCADE, related_name='companies') average_review = models.FloatField(blank=True, default=0, editable=True) count_of_review = models.IntegerField(blank=True, default=0, editable=True) created_date = models.DateTimeField(blank=False, auto_now_add=True) last_change_date = models.DateTimeField(blank=False, auto_now=True) def __str__(self): return self.name views.py class CompanyDetailView(APIView): permission_classes = [IsAuthenticated] def get(self, request, company_id): data = get_object_or_404(Company, id=company_id) payload = CompanyDetailSerializer(data=data) payload.is_valid(raise_exception=True) return Response(payload.data) serializers.py class CompanyDetailSerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('id', 'name', 'company_type', 'logo', 'owner', 'average_review', 'count_of_review', 'created_date', 'last_change_date') But it returns data {"non_field_errors":["Invalid data. Expected a dictionary, but got Company."]} I could not find any solutions, I am only started coding in rest framework) -
How to fix an error with related models, which serializers have HyperlinkedIdentityField?
I'm getting the next error when I try to perform GET request to /api/dishes-types/ page in my web app: ImproperlyConfigured at /api/dishes-types/ Could not resolve URL for hyperlinked relationship using view name "category-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I've tried to apply to my code all the solutions from this page, but nothing worked for me. How to solve this error ? I'm really got stuck... And here is my code. models.py: *I've replaced metaclasses and magic __str__ methods that are intended to admin panel from django.db import models class Category(models.Model): name = models.CharField(max_length=30, unique=True) class DishesType(models.Model): name = models.CharField(max_length=30, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Dish(models.Model): name = models.CharField(max_length=64, unique=True) type_of_food = models.ForeignKey(DishesType, on_delete=models.CASCADE) description = models.CharField(max_length=1000) prices = models.JSONField() serializers.py: from rest_framework.exceptions import ValidationError from rest_framework.fields import SerializerMethodField from rest_framework.relations import HyperlinkedIdentityField from rest_framework.serializers import HyperlinkedModelSerializer from Pub.models import Category, DishesType, Dish class BaseSerializerMixin(HyperlinkedModelSerializer): @staticmethod def validate_name(name): if not name.replace(" ", "").isalnum(): raise ValidationError( "'name' field may contain only letters, numbers and spaces. Change it, please !" ) return name # # DISH SERIALIZERS # class DishSerializerMixin(BaseSerializerMixin): dish_url = HyperlinkedIdentityField(view_name="dish-detail", lookup_field="name") class … -
How can I access the result of an asynchronous task in asyncio python using the task name?
I have been wanting to calculate the progress of an asynchronous task. So, I have created another async function "progress" that I am awaiting from the for loop inside the original function after every n iterations. Now, I created an async django view where I want to access the result of the task(progress function) with the name I set, and return that as HttpResponse. My Django View async def get_progress(request, job_id): task = get_the_task(name=job_id) return task.result Working Function of which I want to calculate the progress async def working_function(request, job_id): for i in range(x): after_every_n_iterations: await asyncio.create_task(progress(i, x), name=job_id) This is my progress function async def progress(work_till_done, total_work): return work_till_done/total_work*100 I don't know where to go from here. Kindly help me. -
Using create_user() method in django
I'm using Django 1.11.10. I want to create a login page with just one username and password. However when I try to use create user I take an Attribute error. How can I use this method? models.py class UserProfile(models.Model): user = models.OneToOneField(User) user = User.create_user(username='username',email=None,password='testpassword') def __str__(self): return self.user.username -
Django file not showing input data on website
So I had a similar issue earlier with the code not iterating correctly to get my table output to work but now i'm trying a description list and it is not showing any of my input data. Any help would be greatly appreciated! Views.py from django.shortcuts import render from django.http import HttpResponse from .models import products, typeWork def hello(request): context = typeWork.objects.all() context2 = {'context':context} return render(request, 'products/index.html', context2) def detail(request, product_id): context3 = typeWork.objects.get(id=product_id) context4 = {'context3':context3} return render(request, 'products/detail.html', context4) Detail.html {% extends 'base.html' %} {% block content %} <dl> <dt>Work</dt> <dd>{{context4.work}}</dd> <dt>Type of Work</dt> <dd>{{context4.genre}}</dd> </dl> {% endblock %} Working code for the table(like it shows input data on the table just adding to see if it may provide any insight on why the detail.html isn't showing the input data index.html {% extends 'base.html' %} {% block content %} <table class="table table-bordered table-hover"> <thead> <tr> <th>Work</th> <th>Type of Work</th> <th>Hours needed</th> </tr> </thead> <tbody> {% for context2 in context%} <tr> <td>{{context2.work}}</td> <td>{{context2.genre}}</td> <td>{{context2.hoursWorked}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} Picture of my actual issue Working table picture -
Django with postgreSQL DB on Docker - django.db.utils.OperationalError: could not connect to server: Connection refused
I am following this tutorial on 'Dockerizing' Django + PgSQL + gunicorn + nginx . Relevant info host machine OS is Ubuntu 20.0.4 LTS Docker-desktop: Docker version 20.10.16, build aa7e414 This is my setup so far: Dockerfile # pull official base image FROM python:3.9.6-alpine # set work directory WORKDIR /usr/src/app ############################# # set environment variables # ############################# # Prevents Python from writing pyc files to disc (equivalent to python -B option) ENV PYTHONDONTWRITEBYTECODE 1 # Prevents Python from buffering stdout and stderr (equivalent to python -u option) ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./my-django-proj/requirements.txt ./my-django-proj/ RUN pip install -r ./my-django-proj/requirements.txt # copy project COPY ./my-django-proj ./my-django-proj compose.yml services: web: build: . command: python my-django-proj/manage.py runserver 0.0.0.0:8000 volumes: - ./my-django-proj/:/usr/src/app/my-django-proj/ ports: - 8000:8000 env_file: - ./my-django-proj/my-django-proj/.env depends_on: - db db: image: postgres:14.3-alpine restart: always container_name: postgres14_3 #user: postgres ports: - 5432:5432 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=myusername - POSTGRES_PASSWORD=thepassword - POSTGRES_DB=thedbname volumes: postgres_data: Output log from sudo docker compose up -d --build postgres14_3 | postgres14_3 | 2022-06-01 12:03:35.017 UTC [1] LOG: starting PostgreSQL 14.3 on x86_64-pc-linux-musl, compiled by gcc (Alpine … -
which of the tools to choose for the backend of a web application? pure java/python django/php laravel [closed]
sup guys, I know some python, and don't know php well and I know java even worse, but I was asked to make a web application with a backend on one of these technologies. But I could not find their comparisons to choose one thing and explain why I chose this one. Anyone who understands the backend can tell me how, what and why would be the best choice? Thank you -
etting ssl_cert_reqs=CERT_OPTIONAL when connecting to redis
I am using redis with Django, and the error message is: Setting ssl_cert_reqs=CERT_OPTIONAL when connecting to redis means that celery might not validate the identity of the redis broker when connecting. This leaves you vulnerable to man in the middle attacks. My settings is as follows, and I am not sure how to make redis use ssl certs to connect to celery: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": env("REDIS_LOCATION"), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": env("REDIS_PASSWORD"), "REDIS_CLIENT_KWARGS": {"ssl_cert_reqs": True}, }, } } -
Django-filter: ModelChoiceFilter with request.user based queryset
I have a Django class based ListView listing objects. These objects can be filtered based on locations. Now I want that the location ModelChoiceFilter only lists locations which are relevant to the current user. Relevant locations are the locations he owns. How can I change the queryset? # models.py from django.db import models from django.conf import settings from rules.contrib.models import RulesModel from django.utils.translation import gettext_lazy as _ class Location(RulesModel): name = models.CharField(_("Name"), max_length=200) owner = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("Owner"), related_name="location_owner", on_delete=models.CASCADE, help_text=_("Owner can view, change or delete this location."), ) class Object(RulesModel): name = models.CharField(_("Name"), max_length=200) description = models.TextField(_("Description"), blank=True) owner = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("Owner"), related_name="location_owner", on_delete=models.CASCADE, help_text=_("Owner can view, change or delete this location."), ) location = models.ForeignKey( Location, verbose_name=_("Location"), related_name="object_location", on_delete=models.SET_NULL, null=True, blank=True, ) This is my current filters.py file which shows all the locations to the user. # filters.py from .models import Object import django_filters class ObjectFilter(django_filters.FilterSet): class Meta: model = Object fields = ["location", ] This is the view which by default shows objects the user owns. It's possible to filter further by location. But the location drop-down shows too many entries. # views.py from django.views.generic import ListView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Object from … -
How i can add like on product page
I can like my products from admin panel,and i want to add posibility to like them by url products/item/like,i have view of like but i dont know what i should add to there.This is my views.py class LikeToggleView(AjaxResponseMixin, JSONResponseMixin, FormView): http_method_names = ('post',) form_class = LikeForm product = None @csrf_exempt def dispatch(self, request, *args, **kwargs): product_id = kwargs['product_pk'] try: self.product = Product.objects.get(id=product_id) except Product.DoesNotExist: raise Http404() return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): pass this is forms.py class LikeForm(forms.ModelForm): user = forms.ModelChoiceField(User.objects.all(), required=False) product = forms.ModelChoiceField(Product.objects.all()) ip = forms.GenericIPAddressField(required=True) this is models.py class Like(TimeStampedModel): product = models.ForeignKey(Product, related_name='likes') user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='likes') ip = models.GenericIPAddressField(blank=True, null=True) class Meta: unique_together = (('product', 'user'), ('product', 'ip')) def __str__(self): return '{} from {}'.format(self.product, self.user or self.ip) -
How to implement password reset with help of django_rest_passwordreset?
I am trying to implement password reset in my Django (DRF) app. I am using django_rest_passwordreset lib I want this User sends api/password_reset/ -- OK User receives email with password reset link /api/password_reset/? token=23d9633863ede8c491a9b2f1 -- OK (can see this email) User clicks to the password reset link and changing password -- DON'T UNDERSTAND HOW TO IMPLEMENT How can I add the third step? My code urls.py urlpatterns = [ ... path('api/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), ] view.py @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): email_plaintext_message = "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key) send_mail( # title: "Password Reset for {title}".format(title="EDO website"), # message: email_plaintext_message, # from: EMAIL_HOST_USER, # to: [reset_password_token.user.email] ) settings.py EMAIL_HOST = 'smtp.yandex.ru' EMAIL_PORT = 587 EMAIL_HOST_USER = '****@yandex.ru' EMAIL_HOST_PASSWORD = '*************' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_USE_TLS = True -
How to Handel Update , Create , Delete Image Field with Signals?
what I want to do is when I create new Image , the server will rename the photo using the image_name function , on update delete the old and create the new , on delete Only delete the file , deleting is work but others not I want to do it with good way , because I tried to use upload_to with osand pathlib libs to Do it But I think I can create it better with Storages , SO I don't hardcode anything Models : class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, null=False, blank=False) describtion = models.TextField() price = models.FloatField() inventory = models.PositiveIntegerField() created_time = models.DateTimeField(auto_now_add=True) last_updated_time = models.DateTimeField(auto_now=True) labels = models.ManyToManyField( Label, through="ProductLabels", through_fields=( "product","label") ) categories = models.ManyToManyField( Category, through="ProductCategories", through_fields=( "product","category") ) objects = ProductManager() def __str__(self) -> str: return self.name def get_absolute_url(self) -> str: return reverse("products:product", kwargs={"pk": self.pk}) @property def photos(self): return ProductImage.objects.filter(product=self) @property def base_photo(self): photos = self.photos if photos: return photos.first().image class ProductImage(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(storage=select_storage) product = models.ForeignKey(Product, on_delete=models.CASCADE) # base = models.BooleanField(default=True) def __str__(self) -> str: return self.product.name Storages: from django.core.files.storage import FileSystemStorage , Storage from django.conf import settings product_photos_storage = FileSystemStorage(location=f"{settings.MEDIA_ROOT}/products/photos") # TODO add the Remote …