Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest frame work api with images, not displaying with <img src=" "> in html
i have made an images api with django rest frame work. when it is running server on goorm ide, it is okay to display but on the oracle cloud vm it is not displaying images on my in html is there any difference between runningn server on goorm ide and oracle cloud vm? -
Algorithm for finding shortest connection between friends in social network or betweent two wiki articles
I have models in Django like from django.db import models class TypeOfObject(models.Model): type = models.CharField(max_length=150, unique=True) def __str__(self): return self.type class Object(models.Model): title = models.CharField(max_length=150) content = models.TextField(blank=True) is_published = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) type = models.ManyToManyField(TypeOfObject, related_name='type_of_object', blank=False) relation = models.ManyToManyField('self', related_name='relation', blank=True, null=True) def __str__(self): return self.title Object can be Person or Article or Movie etc. They refers to each other. How to check, for example, how connected film Spider Man and Michael Jackson. We can find artists who starred in films, for example, Stoney Jackson and he starred in film with actor who starred in Spider Man. Lets count it for 1. And etc, we can estimate how some object related to another. Which way it better to do? -
Access cleaned data from django admin for pdf processing
Hi there I'm fairly new to django so please be kind if anything sounds a bit newbie to you. I am currently trying to add a print button to every existing django admin view of a project so it will not depend on a single model I could resolve manually for printing but every existing model which contains foreign keys to other models an so on. For simplicity I thought it would be the best to just get the cleaned_data of the form and process it for the pdf. I alread added the print button, the path url and so on and it will create a pdf file for me. What I am not able to do is to access the forms cleaned_data from my BaseAdmins (extends the ModelAdmin) class like this: form = BaseForm(request.POST) if form.isValid(): data = form.cleaned_data It will just give me random kinds of errors, like object has no attribute 'is_bound' So I think that I am generally wrong with the context where I am trying to get the cleaned_data from the form. Every tutorial I found is just showing how to get the data but not fully resolved if it contains foreign keys and not … -
Model constraints are not working with Faker ( Django )
I am just starting to use pytest and faker for testing while trying to create text for a field in testing db the constraints are being ignored and i don't know how to fix it. models.py from django.db import models # Create your models here. class Note(models.Model): body = models.TextField(null=True, blank=True, max_length=5) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] factories.py import factory from faker import Faker fake = Faker() from mynotes_api.models import Note class NoteFactory(factory.django.DjangoModelFactory): class Meta: model = Note body = fake.text() conftest.py import pytest from django.contrib.auth.models import User from pytest_factoryboy import register from tests.factories import NoteFactory register(NoteFactory) @pytest.fixture def new_user1(db, note_factory): note = note_factory.create() return note test_ex1.py import pytest def test_product(new_user1): note = new_user1 print(note.body) assert True test output the problem as visible in output is that the length of the text generated and being stored in the testing db is more than 5. kindly guide me in this regard. -
How to create relationships between 3 models in django?
I'm building a marketplace that have 2 user types i.e. buyers and sellers. Now I want to create a relationship model between buyers, sellers and OrderedItems, so that the sellers gets notified once the buyers orders an item. This is the model I made: class Ordered(models.Model): ordered_items = models.ManyToManyField(Cart) seller = models.ForeignKey(SellerProfile, on_delete = models.SET_NULL, null = True) buyer = models.ForeignKey(CustomerProfile, on_delete = models.CASCADE) ordered_on = models.DateTimeField(auto_now_add = True) But I don't know how to implement this in views.py Any suggestion will be really helpful Thank you -
passing values from one function to another in django
I am creating an app in which I have to transfer value from one function to other in Django, after reading some articles I have found out I can use global functions inside the Django function. I just want to ask is it good to use global function because the app I am wokring on is gonna be live and people will use it I dont want any trouble at later stages. -
Filter is not working properly in Django REST Framework
This is my TestViewSet. class TestViewSet(ListAPIView, CreateAPIView, UpdateAPIView): permission_classes = [ IsAuthenticated, ] pagination_class = CustomPagination serializer_class = TestSerializer model = Test create_class = CreateTestSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['department__name', 'code', 'billing_category__id', 'billing_category__name'] def get_queryset(self): name_str = self.request.query_params.get("name") department_id = self.request.query_params.get("department_id") pk = self.kwargs.get("id") self.pagination_class.page_size = page_size if name_str is not None: return self.model.objects.filter( Q(name__icontains=name_str) | Q(name__iexact=name_str) | Q(name__istartswith = name_str) ) elif pk is not None: return self.model.objects.filter(id=pk) elif department_id is not None: return self.model.objects.filter(department_id=department_id) else: return self.model.objects.all() name is CharField and department is ForeignKey in Test Model. When i am passing this url - http://127.0.0.1:8000/api/v1/package/test/?name=fun&department_id=7 It is ignoring deparment_id. I just don't know why. Individually both are working fine. I'm wondering why it is ignoring deparment_id ? Thank you !! -
MiddlewareMixin missing required argument: 'get_response' django
Does anyone have any ideas on why I am getting this error? My program was working before and I don't know what I changed to cause it to break. My main website works but whenever I make this get request to http://10.0.0.233:8000/watcher/form/list I get the error below. I searched my whole project and did not find MiddlewareMixin used anywhere. urls.py: from django.urls import path from . import views urlpatterns = [ path('form/list',views.get_all_form_items), ] Views.py @api_view(['GET']) def get_all_form_items(request): snippets = form_item_db.objects.all() serializer = form_item_db_serializer(snippets, many=True) return Response(serializer.data) Error: Django version 4.0, using settings 'backend.settings' Starting development server at http://10.0.0.233:8000/ Quit the server with CTRL-BREAK. [05/Jan/2022 02:11:55] "GET /watcher HTTP/1.1" 200 644 [05/Jan/2022 02:11:55] "GET /static/js/main.1924b030.js HTTP/1.1" 304 0 [05/Jan/2022 02:11:55] "GET /static/css/main.31d6cfe0.css HTTP/1.1" 304 0 Internal Server Error: /watcher/form/list Traceback (most recent call last): File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\bestg\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 493, … -
how to show multiple image objects in django template?
models.py class ProductVariantsImages(DateTimeModel): product_variant = models.ForeignKey(ProductVariants, on_delete=models.CASCADE, related_name='product_variants_images') variant_images = models.ImageField(upload_to='uploads/') def __str__(self): return str(self.id) HTML <div class="input-group"> {{variant_images}} </div> views.py @login_required def item_approval(request, pk): if request.method == "GET": product_form = AdminProductForm(request.POST) item = ProductVariants.objects.get(item_num=pk) variant_images = ProductVariantsImages.objects.filter(product_variant=item) print(variant_images) product_form = AdminProductForm(instance=product) item_form = ProductVariantsForm(instance=item) variant_images = ProductVariantsImagesForm(instance=product_variant_images)# here I get multiple objects print(variant_images) return render(request, 'loom_admin/product_details.html', {'item_form':item_form, 'product':product, 'product_form':product_form, 'variant_images':variant_images, }) while running I get 'QuerySet' object has no attribute '_meta' when I put variant_images = ProductVariantsImagesForm(instance=product_variant_images[0]) the error disappear. But I am getting first image object. What if I want to do to get multiple images that related to the filter query in django template? -
Drf: returns 403 instead of 401 after jwt token expires?
"DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], I am using session authentication for django admin and swagger and jwt for rest of the part. The issue is I am getting 403 after token expires but I think it should return 401 since the error is Given token not valid for any token type. Or 403 is the correct response ? -
Django migrations, calculate new fields value based on old fields before deleting old fields?
We are intenting to rework one of our models from old start-end date values to use starting date and length. However, this does pose a challenge in that we want to give default values to our new fields. In this case, is it possible to run migration where we create new field, give it a value based on models old start-end fields from django.db import models class Period(models.Model): #These are our new fields to replace old fields period_length=models.IntegerField(default=12) starting_date=models.DateField(default=Date.today) #Old fields. We want to calculate the period length based on these before we remove them start_day = models.IntegerField(default=1) start_month = models.IntegerField(default=1) end_day = models.IntegerField(default=31) end_month = models.IntegerField(default=12) Starting months and ending months can be anywhere between 1 and 12, so we need to run bunch of calculations to get the correct length. Is there a way for us to run a function in migrations that, after adding the new fields, calculates their new values before calling for removal of the old fields? I do know I can create basic add/remove fields with makemigrations, but I want to add the value calculations in between. Other option I have considered is to first run a migration to add the fields, then a … -
Any specific reasons why one should use `update_or_create` in Django?
So I have been using Django models' update_or_create function to upsert rows in a model. Wanted to ask, except the transaction being atomic, are there any added benefits? We can always do a = Models.objects.get(id=21) a.some_field = 'new_value' a.save() -
My Django project use Stripe payment gateway. how to remove billing address
I am used Stripe payment gateway for get payment but checkout page get Billing address fields. how to remove this fields. checkout page Hear is my code: checkout_session = stripe.checkout.Session.create( line_items=[ { "price_data": { "currency": "usd", "product_data": { "name": "order", }, "unit_amount_decimal": 5 * 100, }, "quantity": 1, }, ], customer_email="test@gmail.com", mode="payment", success_url=success_url, cancel_url=cancel_url, ) -
Make Django ListView display horizontal rather than vertical
I just started learning Django and I'm trying to display some blogs while following the tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Introduction. I have a list view class (shown below). However, the elements appear one after the other on seperate lines. Is there any way I can fix this so, say, three elements appear on one line? I tried using #all-blogs { display: inline-flex; } but this makes everything appear in one line. Here is my code. ListView Class: class BlogListView(generic.ListView): model = Blog context_object_name = 'all_blogs' paginate_by = 15 blog_list.html <div id="all-blogs"> {% for blog in all_blogs %} <div class="blog"> <a href="{{ blog.get_absolute_url }}"> <h1 class="blog-title">{{ blog.title }}</h1> <h1 class="blog-author">By: {{blog.author}}</h1> <p class="blog-published">{{blog.published}}</p> <p class="blog-description">{{blog.description}}</p> </a> </div> {% endfor %} </div> Any help is appreciated. Thanks in advance -
how to specify search_filter='(objectClass=group)',search_scope='SUBTREE',attributes = ['member']) for django python3 ldap
I am using django python3 ldap package to sync some users from ldap server to my django application. Its getting connected to ldap server with my configurations defined in settings but user lookup is failed. The search base that i am using is LDAP_AUTH_SEARCH_BASE = "CN=SOME_USERS,OU=Security Group,OU=Example,DC=Example,DC=com" But I get my result with a different package named ldap3. for ldap3 I can specify some extra parameters along with search_base like below from ldap3 import Server, Connection, SAFE_SYNC server = Server('my_server') conn = Connection(server, 'my_user', 'my_password', client_strategy=SAFE_SYNC, auto_bind=True) conn.search(search_base='CN=DTS_USERS,OU=Security Group,OU=Viacom18,DC=viacom18,DC=com',search_filter='(objectClass=group)' ,attributes = ['member']) I just want to know how can I specify "search_filter='(objectClass=group)' ,attributes = ['member']" with django python3 ldap. I checked the documentation at https://github.com/etianen/django-python3-ldap but could not find any helpful thing. Any help will be appreciated? -
Celery workers stop receiving tasks after a certain period without any error
I'm using Celery beat and workers for task scheduling in a Django project. Redis is being used as the broker. I've daemonized it with systemd. Django project settings for Celery # Celery application definition CELERY_BROKER_URL = "redis://localhost:6379" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" CELERY_TIMEZONE = "UTC" CELERY_MAX_TASKS_PER_CHILD = 1 CELERY_IGNORE_RESULT = True # Celery periodic task schedule CELERY_BEAT_SCHEDULE = { "task-1": { "task": "project.apps.app1.tasks.task_no_1", "schedule": datetime.timedelta(seconds=5), }, "task-2": { "task": "project.core.tasks.task_no_2", "schedule": datetime.timedelta(seconds=10), }, "task-3": { "task": "project.apps.app1.tasks.task_no_3", "schedule": datetime.timedelta(seconds=10), }, "task-4": { "task": "project.apps.app1.tasks.task_no_4", "schedule": datetime.timedelta(seconds=5), }, "task-5": { "task": "project.apps.app1.tasks.task_no_5", "schedule": datetime.timedelta(seconds=10), }, "task-6": { "task": "project.apps.app1.tasks.task_no_6", "schedule": datetime.timedelta(seconds=30), }, "task-7": { "task": "project.apps.app1.tasks.task_no_7", "schedule": datetime.timedelta(seconds=30), }, } /etc/default/celeryd # Name of nodes to start CELERYD_NODES="worker1 worker2" # Absolute or relative path to the 'celery' command: CELERY_BIN="/home/adnan/project/env/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="project.core" # How to call manage.py CELERYD_MULTI="multi" CELERYD_USER="adnan" CELERYD_GROUP="www-data" CELERYD_LOG_LEVEL="INFO" # - %n will be replaced with the first part of the nodename. # - %I will be replaced with the current child process index # and is important when using the prefork pool to avoid race conditions. CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" # Options for Celery Beat … -
Gunicorn, nginx, django, inside of a docker container. Gunicorn successfully runs on port 80 but nginx fails
I'm trying to set up a simple blogging site that I wrote using the django framework. The website works except that it isn't serving static files. I imagine that's because nginx isn't running. However, when I configure it to run on any port other than 80 I get the following error: nginx: [emerg] bind() to 172.17.0.1:9000 failed (99: Cannot assign requested address) When I run it on a port that is already being used by gunicorn I get the following error: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) My nginx configuration file is as follows: upstream django { server 127.0.0.1:8080; } server { listen 172.17.0.1:9000; server_name my.broken.blog; index index.html; location = /assets/favicon.ico { access_log off; log_not_found off; } location /assets { autoindex on; alias /var/www/html/mysite/assets; } location / { autoindex on; uwsgi_pass unix:///run/uwsgi/django/socket; include /var/www/html/mysite/mysite/uwsgi_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django admin: "How to properly display multi-layered relations?"
I'm new to Django framework and trying to build a math test application. Idea is to generate a test from a pool of questions. I have a following DB entities: class TestResult(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) score = models.IntegerField(blank=True, null=True) class Meta: db_table = 'test_results' class Question(models.Model): text = models.CharField(unique=True, max_length=255) type = models.IntegerField(blank=True, null=True) class Meta: db_table = 'questions' class Answer(models.Model): question = models.ForeignKey(Questions, on_delete=models.CASCADE) text = models.CharField(max_length=255) is_correct = models.BooleanField() class Meta: db_table = 'answers' class AskedQuestion(models.Model): question = models.ForeignKey(Questions, on_delete=models.CASCADE) test = models.ForeignKey('TestResults', on_delete=models.CASCADE) class Meta: db_table = 'asked_questions' class GivenAnswer(models.Model): answer = models.ForeignKey(Answers, on_delete=models.CASCADE) test = models.ForeignKey(TestResults, on_delete=models.CASCADE) class Meta: db_table = 'given_answers' I am able to display AskedQuestion and GivenAnswer as 2 separate StackedInline for TestResult. But I want to display Question + Answer pairs when I navigate to TestResult page in Django admin. Any suggestions would be appreciated. -
[Django-pymongo]: Retain Mongo connection across request?
I have below code to open connection to mongo cluster deployed in altas under django view. def homePage(request): context = {} import pymongo client = pymongo.MongoClient(<connection str>) db = client.foo return render(request, 'Home/index.html', context) I see for each request it opens a new connection which is adding delay to load page. Is there any way i can move this connection code some where else and reuse connection handle across all request? I tried moving code to settings.py and tried exporting db handle to views.py but after sometime connections times out. Version of libs are: Django 4.0.1 django-settings-export 1.2.1 pip 21.1.2 pymongo 4.0.1 -
error Template does not exist, but template is exist
Templates does not exit, but template is already exist. In this project, I am doing upload file. Please help to solve this problem. urls.py: from django.contrib import admin from django.urls import path from usermaster import views from django.conf.urls.static import static from mysite5 import settings urlpatterns = [ path('admin/', admin.site.urls), path('upload/', views.index), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py: from django.http.response import HttpResponse from django.shortcuts import render from usermaster.forms import MachineForm # Create your views here. def index(request): if request.method == 'POST': form = MachineForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['upload_file']) model_instance = form.save(commit=False) model_instance.save() return HttpResponse("File uploaded successfuly") else: form = MachineForm() return render(request,'usermaster/upload_file.html',{'form':form}) def handle_uploaded_file(f): with open('usermaster/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) models.py: from django.db import models # Create your models here. class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField() upload_file = models.FileField() forms.py: from django import forms from usermaster.models import Machine class MachineForm(forms.ModelForm): class Meta: model = Machine fields = '__all__' upload_file.html: <html> <head> <title>Django File Upload</title> </head> <body> <p><h1>Django File Upload</h1></p> <form method="post" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </body> </html> Templates does not exit, but template is already exist. In this project, I am doing upload file. I don't know why template … -
FieldError: Unsupported lookup for CharField or join on the field not permitted on Django
Why do I get this error: FieldError: Unsupported lookup 'unaccent' for CharField or join on the field not permitted? Info Language: Python Platform: Django Database: PostgreSQL Code View: def search(request): query = request.GET.get("query") searched = Book.objects.filter(title__unaccent__icontains=query) # Error here return render(request, "main/search.html", { "query": query, "searched": searched, }) Expected output Unaccent the query and search for the unaccented version in the database. Description I get the error FieldError: Unsupported lookup 'unaccent' for CharField or join on the field not permitted when I try to query the database using __unaccent while using the advanced search features mentioned in the django docs. -
PermissionDenied return to home
For my blog on all the relevant views such as delete and update I have this if request.user.id != post.author_id: raise PermissionDenied() This is working as expected however it just sends the user to a page that says 403 forbidden. I would rather just redirect the user to the homepage. Would it be insecure or poor practice to do something like return HttpResponseRedirect('/') or is it fine as is and I am overthinking it -
item['total_price'] = item['price'] * item['quantity'] KeyError: 'quantity'
Good afternoon, I'm writing a store on django, but the following problem occurred when going to the shopping cart page: item['total_price'] = item['price'] * item['quantity'] KeyError: 'quantity'. The error itself lies in cart.py , and it seems simple, but I do not know how to solve it. Forms.py: PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) views.py from django.shortcuts import redirect, get_object_or_404, render from django.views.decorators.http import require_POST from shop.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) cart.py from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart … -
How to pass django context values to the javascript variable?
I want to pass all the values of the {{ i.nsn }} turn by turn to the ajax script. {% for i in dibbs %} <p>{{ i.nsn }}</p> {% endfor %} If I tried the ajax script in the way {% for i in dibbs %} <script> var nsn = {{ i.nsn }} console.log("Hello") $('.togglebtn').on("click",function(){ console.log("Hello") $.ajax({ type: 'GET', url: "http://localhost:8000/toggle/"+nsn, contentType: 'application/json', success: function (data) { appendData(data); function appendData(data) { var mainContainer = document.getElementById("switch_{{forloop.counter}}"); for (var i = 0; i < data.length; i++) { var div = document.createElement("div"); div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ; mainContainer.appendChild(div); } } } }); }); </script> {% endfor %} The ajax script also repeats as per the loop. My url is different for every nsn. I want to send a single ajax request when I clicked in the button. I want to execute a single ajax function for a single click removing the for loop. -
How to get the ID of the record created in the model after saving it from a Form
Let's say I submit a form to the back-end and I save a record of the model in the following way: views.py: def viewName(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() #I want to get the id of this after it is saved else: print (form.errors) form = ProjectForm() return render(request, 'index.html', context) forms.py: class ProjectForm(ModelForm): class Meta: model = Project fields = '__all__' Right after saving the form, I would like to get the id of the record for the model. I tried with form.id and form.pk as I saw in other similar questions without success. How can I get the id or the pk of the new entry added to the Project model?