Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom popup for selecting related object raw_id_field in Django admin
I have an admin with a ForeignKey raw_id_field. With Django, this causes the ForeignKeyRawIdWidget to be used. This widget has a spyglass icon which links to the relevant object's changelist for selection. I want to re-link this widget to a custom view and HTML template, so I can autogenerate the object if required, etc. My current problem is figuring out how to return the selected object ID to the form. I also require custom view handling here, which may complicate things as I may have to create the related object before returning its ID. How does the popup communicate this back to the add form window? -
Connect AWS s3 with django
I'm testing my django project on s3 locally. But when running the server it doesn't seem to be serving static files AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' But it doesn' t seem working when I check my browser's console it shows http error code of 403 request forbidden when accessing to my static files. why this happens, should I change my s3 settings. -
Django Adding Password Reset to Custom Models
I am working on site with two models College and Employee . I used auth_views Password Reset views and was able to do working password reset for model User but whatever I try I am unable to implement it for Custom models(Employee and College) models.py class Employee(models.Model): emp_id = models.CharField(primary_key=True,max_length=50) name = models.CharField(max_length=50) gender = models.CharField(max_length=50,default="None") email = models.EmailField(max_length=50) password = models.CharField(max_length=50,help_text="Minimum of 8 Characters") dept = models.CharField(max_length=50) phone = models.CharField(max_length=20) last_login=models.DateTimeField(auto_now_add=True, blank=True) is_active=models.BooleanField(default=False) class College(models.Model): emp_id = models.CharField(primary_key=True,max_length=50) name = models.CharField(max_length=50) gender = models.CharField(max_length=50,default="None") email = models.EmailField(max_length=50) password = models.CharField(max_length=50,help_text="Minimum of 8 Characters") college = models.CharField(max_length=50) phone = models.CharField(max_length=20) last_login=models.DateTimeField(auto_now_add=True, blank=True) is_active=models.BooleanField(default=False) Views.py def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = College.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "password_reset_email.txt" c = { "email":user.email, 'domain':'127.0.0.1:8000', 'site_name': 'Two Factor', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'myemailaddress' , [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ("password_reset_done") password_reset_form = PasswordResetForm() return render(request=request, template_name="password_reset.html",context={"password_reset_form":password_reset_form}) def password_reset_confirm(request,uidb64,token): def get(self, request, uidb64, token, *args, **kwargs): try: uid = force_text(urlsafe_base64_decode(uidb64)) print(uid) user = College.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): … -
How can I include a Python program in a webpage using django as a back end technology
i'm using Django to develop the backend and I have to integrate a python algorithm in a webpage to sort the choices of a form -
Python, django: I think there is simple way to put all the phone numbers that Admin put on the html page, into the list_numbers'
I am not sure about the codes I wrote... and check if everything is okay. Admin put all the numbers on the sms page (html). this page is hidden, this is only for admin Admin hit the submit button views.py perform the function of sending sms to those numbers def sms(request): if request.method == "POST": number1 = request.POST.get('number1') number2 = request.POST.get('number2') number3 = request.POST.get('number3') ... ... account_sid = 'AC@@@@@@@@@@@@@@@@@@@@@@@@@@@@' auth_token = 'b25986445ce6ad186b1f7efac287fbe6' client = Client(account_sid, auth_token) def sms_one(sendto): client.messages.create(body="Just reminder of your booking \ \nSee you soon \ \n\nAny changes? please let us know\ \nDo.Not.Reply.to.This.Number.\ \nInstead, click => https://******.com/contact", from_='**********', to=sendto) list_numbers = [number1, number2, number3, ...............] def sms_all(listnumbers): for number in listnumbers: sms_one(number) sms_all(list_numbers) return render( request, 'basecamp/sms.html' ) else: return render(request, 'basecamp/sms.html', {}) of course, I could send sms by python shell or terminal but I wanna do this on the website because I thought it is easy way to do (if I have to do everyday many numbers). that's why I made html page and this function. but I am not sure about the List function to collect all the numbers. I thought there is better, simple way... -
what causes syntax error in django-urls.py
enter code here from django.conf.urls import url from .import views urlpatterns = [ url(r'^$', views.item, name='item') url(r'^p/(<p>\d+)$', views.item2, name='item2') url(r'^p/new/$', views.item3, name='item3') I'm getting a syntaxError: invalid syntax from the last url line I entered don't know what's causing this -
Is there a way to see imported modules/files from the django shell?
I have some lines of code that I use to practice django_rest_framework and I just pasted them in the python shell from python manage.py shell. I have gotten some errors and would like to know what imports I already have. Is there a function to figure out what was imported? This may be applicable to a python shell as well that isn't obtained from django. This may not be necessary but here is the example code that I pasted in the shell while following this tutorial: from .api_basic.models import Article from .api_basic.serializers import ArticleSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser a = Article( title='Article Title', author = 'Parwiz', email = 'par@gmail.com' ) b = Article( title='New Title', author = 'John', email = 'joh@gmail.com' ) a.save() b.save() serializer = ArticleSerializer(a) print(serializer.data) # gives a dict content = JSONRenderer().render(serializer.data) serializer2 = ArticleSerializer(Article.objects.all(), many=True) content2 = JSONRenderer().render(serializer.data) -
Django Forms, HttpResponseRedirect & Dynamically Altering Pages
The goal of a page is to take a set of inputs through an html form, process the information in Python (Through a Django View Function associated with the form-action / post request currently) creating a 2D image and downloadable text file, and render a page / template with the new context. Reading djano/web documentation recommends a HttpResponseRedirect() object for a function handling a form post request. As I understand a HttpResponseRedirect object cannot pass a context to the url it redirects towards. What is a logical way to handle the form post request-> 2D image/text processing based on form variables -> template rendering with new context flow? The idea is to be able to render a new 2D image/downloadable text file to the template each time the form is posted. Thank you. -
Django - Reverse of an asymmetric relationship
For the model: class Entity(models.Model): title = models.CharField(max_length=10, primary_key=True) ... parent = models.ForeignKey("self", null=True, default=None, on_delete=models.CASCADE) how do I get all entities that point to current entity as parent? As an example, for entities: a = Entity.objects.create(title="Parent") b = Entity.objects.create(title="Child 1", parent=a) c = Entity.objects.create(title="Child 2", parent=a) It is easy to filter all objects that have parent as 'a' (I am trying to create a subquery; iteration is not an option): Entity.objects.filter(parent=a) But how do I filter all objects that have a particular child, say, 'b'? Entity.objects.filter(?=b) # What should I write in the place of "?" so it returns 'a' -
Cannot use ImageField because Pillow is not installed when it is in fact installed
Hello I've been trying to add an ImageField for one of my models in my Django app. When I ran the following code: python3 manage.py makemigrations A statement came out, saying I needed to install Pillow, which I did ('Successfully installed Pillow-8.2.0'). However, when I tried to run makemigrations again, the following error occurred: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". I am aware that there are several threads out there that have discussed similar issues (like python/django - "Cannot use ImageField because Pillow is not installed") and I have tried doing whatever was recommended (reinstalling 64-bit Python, upgrading pip, making sure I don't have PIL, attempting to install an older Pillow version) but none worked. Particularly, attempting to install an older Pillow version caused errors with the following message: Pillow 7.1.0 does not support Python 3.9 and does not provide prebuilt Windows binaries. I am using Windows 10, Python 3.9, Django 3.2.0 and Pillow 8.2.0 . Would really appreciate it if anyone can help me with this, thank you! -
django real time cli with ajax
i want to create real time cli i'm sending commandes with the input (netmiko) and i recive the results in the text aria but it doesn't work my script : <script type="text/javascript"> $(document).('submit','#post-form',function(e)){ e.preventDefault(); $.ajax({ type:'POST', url:'cli_run', data:{ cmds:$('cmds').val(), csrfmiddlewaretoken:$('input[cmds=csrfmiddlewaretoken]').val(), }, outputs: function(data){ $('h2').html(data);}});} </script> --> and this is my template : div class="row"> <div class="card col-12 col-md-6"> <div class="card-header"> <label> <h3>ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ Cli : </h3></label> </div> <br> <div class="card-body text-center"> <form action="{% url 'cli_run' device.id%}" method="POST"> {% csrf_token %} <textarea name="cmds" id="cmds" rows="10" cols="80"></textarea> <input type="submit" name="Submit"> </form> </div> </div> <div class="card col-12 col-md-6"> <div class="card-header"> <label> <h3>output : </h3></label> </div> <br> <div class="card-body text-center"> <textarea rows="10" cols="80"> {% for i in outputs %} {{i}} {% endfor %} </textarea> </div> </div> and this is my view , i connect with the decice with 'RTR' and i use a list (output ) to show the results def cli_run(request, pk ): device = Device.objects.get(id=pk) RTR = {'ip': device.ipadress,'username': device.hostname,'password': device.password,'device_type': 'cisco_ios',} net_connect = ConnectHandler(**RTR) output = net_connect.send_command(request.POST.get("cmds")) outputs.append(output) context = {'device':device,'output':output,'RTR':RTR,'outputs':outputs,"devices":devices} return render(request, 'accounts/cli_run.html',context) -
Django update a Foreign Key model using reverse lookup
I am working on a Django project and stuck at a problem. My models look like this: class Products(models.Model): basket_name = models.CharField(max_length = 5, blank = False) product_name = models.CharField(max_length = 30, blank = False) quantity = models.PositiveSmallIntegerField(null = False, blank = False, default=1) class ShelfProduct(models.Model): shelf_name = models.CharField(max_length = 15, default="defaultshelf") products = models.ManytoManyField(Products) ..... other fields.... class KioskShelf(models.Model): kiosk_name = models.CharField(max_length= 15, default="default") shelfproduct = models.ManytoManyField(ShelfProduct) ...other fields.... class MapperModel(models.Model): kioskshelf = models.ForeignKey(KioskShelf, on_delete = models.CASCADE) ...other fields.... I am trying to update the product quantity in Products models for a particular kiosk name and particular shelf. I tried like this: data = MapperModel.objects.filter(kioskshelf__kiosk_name = 'kiosk1').filter(kioskshelf__shelfproduct__shelf_name = 'Shelf A') But after this am not sure how to update the quantity in Products table. Am not even so sure if my approach is correct. Please assist me how to do it. Thanks a lot in advance. -
Could not load bms.Publisher(pk=3): (140 6, "Data too long for column 'name' at row 1") when change sqlite to mysql in django
I have used Django to develop a web app. When I tried to transfer the database from sqlite to mysql, error occurs: Could not load bms.Publisher(pk=3): (140 6, "Data too long for column 'name' at row 1") model.py: class Publisher(models.Model): name = models.TextField(blank=True, help_text="Publisher name") contact = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['name', ] I used python manage.py loaddata to load saved JSON data from sqlite to mysql, but got a lot of such errors. Is there an easy way to load sqlite data in mysql in django? -
How could you make this really reaaally complicated raw SQL query with django's ORM?
Good day, everyone. Hope you're doing well. I'm a Django newbie, trying to learn the basics of RESTful development while helping in a small app project. Currently, there's a really difficult query that I must do to create a calculated field that updates my student's status accordingly to the time interval the classes are in. First, let me explain the models: class StudentReport(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE,) headroom_teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE,) upload = models.ForeignKey(Upload, on_delete=models.CASCADE, related_name='reports', blank=True, null=True,) exams_date = models.DateTimeField(null=True, blank=True) #Other fields that don't matter class ExamCycle(models.Model): student = models.ForeignKey(student, on_delete=models.CASCADE,) headroom_teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE,) #Other fields that don't matter class RecommendedClasses(models.Model): report = models.ForeignKey(Report, on_delete=models.CASCADE,) range_start = models.DateField(null=True) range_end = models.DateField(null=True) # Other fields that don't matter class StudentStatus(models.TextChoices): enrolled = 'enrolled' #started class anxious_for_exams = 'anxious_for_exams' sticked_with_it = 'sticked_with_it' #already passed one cycle So this app will help the management of a Cram school. We first do an initial report of the student and its best/worst subjects in StudentReport. Then a RecommendedClasses object is created that tells him which clases he should enroll in. Finally, we have a cycle of exams (let's say 4 times a year). After he completes each exam, another report is created … -
Determine if YouTube video is original music
How can I do this? I'm making an automated system that will download all available music on youtube from each given artist from a list of artists. I need to be able to know that a video is original music and not a cover or something else. How can I do this? Any help is appreciated, thanks. Ideally I'd like to use python. -
Call API from a custom button in django admin view
I have this modelAdmin for one of my models in django: class OfferingAdmin(admin.ModelAdmin): fieldsets = [ ('Select Issuer', {'fields': [ 'issuer',]}), ('Offering Information', {'fields': [ 'offering_name',]}), ('Send Notes', {'fields': [ 'notes', 'send_notes']}), ] readonly_fields = ('send_notes',) list_display = ('offering_name',) list_filter = ('offering_name',) def send_notes(self, request): url = (config('base_url') + "send-notes/") return format_html('<a href="{}" class="button">Send Notes</a>',url) send_notes.short_description = 'Send Notes' where send_notes is an anchor button that directs to one of my urls and on to my views here: def send_notes(request): logger.debug("got called") try: notes_payload = json.dumps({ "notes": request.POST.get('notes') }) headers = { 'Content-Type': 'application/json', 'Accept':'application/json' } notes_response = requests.post( config('notes_endpoint'), headers=headers, data=notes_payload ) if notes_response.status_code == 200: logger.debug("sending email success!") return True else: logger.debug("fa_wire_call email returned non-200 code.") return False except Exception as e: logger.debug("sending email returned an exception.") logger.debug(e) return I am able to successfully send notes by clicking the button. But I also need to update the data I currently have in the modelAdmin. How may the two be done simultaneously inside the admin view? The sample repository is here: https://github.com/pdarceno/django-prosy-form -
building web proxy with python
I'm building a website with django framework. I'm trying to add a web proxy tool in my website which will access the website entered through a proxy. All methods I have researched are, for example if I use requests, urllib libraries it sends requests through proxy and gets me the response.text but I want to open a web page. another solution I have tried is '''import subprocess as sp''' and '''sp.Popen(browser)''' and it works in my system level because I need to mention chrome path everytime but I can't do it with end users. What is the instructions to make this system complete? thank you in advance... -
Docker: PostgreSQL Django FATAL: password authentication failed for user "django"
I'm trying to connect Django to the PostgreSQL server but still didn't manage to see what's the problem. The docker container seems up and running correctly, but in Django, I get this error: Pgdb throws me this error: pgdb | 2021-06-09 23:49:00.871 UTC [35] FATAL: password authentication failed for user "django" pgdb | 2021-06-09 23:49:00.871 UTC [35] DETAIL: Role "django" does not exist. pgdb | Connection matched pg_hba.conf line 99: "host all all all md5" Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt docker-compose.yml version: '3.8' services: django: build: . container_name: django command: > sh -c "python manage.py makemigrations && python manage.py runserver 0.0.0.0:8000" volumes: - .:/usr/src/app/ ports: - '8000:8000' environment: DB_NAME: django DB_USER: django DB_HOST: pgdb DB_PORT: 5432 DB_PASSWORD: django CELERY_BROKER: redis://redis:6379/0 depends_on: - pgdb - redis celery: build: . command: celery -A conf worker -l INFO volumes: - .:/usr/src/app/ depends_on: - django - redis pgdb: image: postgres container_name: pgdb environment: POSTGRES_USER: django POSTGRES_PASSWORD: django ports: - '5432:5432' volumes: - pgdata:/var/lib/postgresql/data/ redis: image: 'redis:alpine' volumes: pgdata: Django settings includes: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), 'PASSWORD': os.environ.get('DB_PASSWORD'), }, … -
Can I validate model calculated results in django.models or rest_framework?
Can I validate model calculated results in django.models or rest_framework? e.g. class PointChange(models.Model): point_last_kpi = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=False) point_last_non_kpi = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=False) point_last = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=False) I want to create a validation for 'point_last' as a value of 'point_last_non_kpi' + 'point_last_kpi'. How to do that using django or django-rest-framework? Or validate it in views? -
Django Shell returns FOREIGN KEY constraint failed when using ManyToManyField
Here my models.py user and stock, the idea that each stock has users field that stores the users that use it. from django.db import models class User(models.Model): email = models.EmailField(max_length=254, primary_key=True) password = models.CharField(max_length=150) name = models.CharField(max_length=150) def __str__(self): return f'Name: {self.name}, Email: {self.email}, Password: {self.password}' class Stock(models.Model): name = models.CharField(max_length=100) symbol = models.CharField(max_length=6, primary_key=True) users = models.ManyToManyField(User) def __str__(self): return f'Name: {self.name}, Symbol: {self.symbol}, Users: {self.users}' in the shell created user and stock, but when I try to add the user to stock.users I receive an error >>> user <User: Name: Michael, Email: michael@gmail.com, Password: 12345> >>> stock <Stock: Name: Apple, Symbol: aapl, Users: stocks.User.None> >>> stock.users.add(user) Traceback (most recent call last): File "C:\Users\Michael\Documents\python_project\stocksWebsite\venv\lib\site-packages\django\db\backends\base\base.py", line 242, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Michael\Documents\python_project\stocksWebsite\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 957, in add self._add_items( File "C:\Users\Michael\Documents\python_project\stocksWebsite\venv\lib\site-packages\django\db\transaction.py", line 246, in __exit__ connection.commit() File "C:\Users\Michael\Documents\python_project\stocksWebsite\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Michael\Documents\python_project\stocksWebsite\venv\lib\site-packages\django\db\backends\base\base.py", line 266, in commit self._commit() File "C:\Users\Michael\Documents\python_project\stocksWebsite\venv\lib\site-packages\django\db\backends\base\base.py", line 242, in _commit return self.connection.commit() File "C:\Users\Michael\Documents\python_project\stocksWebsite\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Michael\Documents\python_project\stocksWebsite\venv\lib\site-packages\django\db\backends\base\base.py", line 242, … -
How to require a link in a django form?
I'm basing my code off of this template, but when the user makes a new post, I want to require them to include a link in their post. I initially thought I could change this in forms.py but the code there is: from django import forms from .models import Comment class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] So I'm not sure now if I should change this file. I don't know if changing anything in views.py matters: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['content'] template_name = 'blog/post_new.html' success_url = '/' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data['tag_line'] = 'Add a new post' return data Thank you for any help!! I am relatively new to Django and am using Python 3.7.4 -
Constraining instantiation of a regular class based on foreginkeys to a regular class and an abstract class
I am creating my first django project and after having created a model A I realize that I want to create other models B, C ... that have certain traits in common with A but which needs to be separat models. Thus I created an abstract class 'InteractableItem' with these traits. I want users to be able to like interactable items, however I also want to constrain the instantiation of a 'Like' model such that each user only can like a given interactable item once. To solve this I tried creating a models.UniqueConstraint in the like model between the fields 'user' and 'interactableitem'. This gave me the following error ERRORS: feed.Like.interactableitem: (fields.E300) Field defines a relation with model 'InteractableItem', which is either not installed, or is abstract. feed.Like.interactableitem: (fields.E307) The field feed.Like.interactableitem was declared with a lazy reference to 'feed.interactableitem', but app 'feed' doesn't provide model 'interactableitem'. I realise that my error is the referencing of an abstract class through a ForeignKey, however I dont see a way to constrain the instantiation of the like if the 'user' liking and the 'interactableitem' being like are not both fields in 'like'. This is where I need help. How do you establish … -
Management Formset error is getting triggered
The HTML code below is returning a ['ManagementForm data is missing or has been tampered with']. This HTML was what gave me the custom look I was going for, but why is this happening? I don't understand, since I have declared the management_data tag. On the views, I have initialized the formset like the follwing: > formset_forms = formset_factory(FormsetForm, extra=1) > formset = formset_forms(form_kwargs=create_forms) > > if request.POST: > formset = formset_forms(request.POST or None, form_kwargs=create_forms) HTML <form method="POST" enctype="multipart/form-data" action="."> {{ formset.management_data }} <!-- Security token --> {% csrf_token %} {{ formset.non_form_errors.as_ul }} <table> {% for form in formset.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th name={{field.label}}>{{ field.label }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %}"> {% for field in form.visible_fields %} <td name={{field.label}}> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> </form> -
Django ORM - selecting related records by setting criteria on some fields but excluding current record from returned records
I am using Django 3.2 I am writing a function to return related records when an object is retrieved from the database. I am using the tags field (a TaggitManager instance) to determine which records are related. I then want to remove (i.e. exclude the current record) from the set of related records. Here is the line of code that is supposed to return objects related (in terms of tags): object = self.get_object() object_tag_fields = [x.name.strip() for x in object.tags.get_queryset()] if object_tag_fields: query_match = Q() for tag_field in object_tag_fields: query_match |= Q(tags__name__contains=tag_field) related_foos = Foo.objects.filter(query_match).exclude(id=object.id).distinct() Howerver, when I run the above code, it ALWAYS includes the fetched object, in the set of related objects. I have also tried the following (to no avail): Foo.objects.exclude(id=object.id).filter(query_match).distinct() Foo.objects.filter(~Q(id=object.id)).filter(query_match).distinct() Both statements include the fetched object in the set of related objects. How do I correct the query so that all records that are related (by tag) are returned - EXCLUDING the current fetched object? -
ModuleNotFoundError: No module named 'django' After installing new module with pipenv
I am trying to use cloudinary on my project on heroku, before i was intaling all modules by pip, but this time because i was doing it with guide on internet i install cloudinary with pipenv, and in my project appears Pipfile and Pipfile.lock. On my pc all was working not bad, but when i deployed it on heroku it gives me moduleNotFound error, it loks like pip not intalling any modules from requirements.txt, although it says that all is ok. PipFile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] cloudinary = "*" dj3-cloudinary-storage = "*" [dev-packages] [requires] python_version = "3.8" requirements.txt django gunicorn django-heroku django-rosetta django-tinymce dj-database-url social-auth-app-django django-crispy-forms six Pillow django-import-export python-social-auth pipenv cloudinary dj3-cloudinary-storage Command i was running pipenv install cloudinary dj3-cloudinary-storage Traceback File "./manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' Tell me if you need any additional information