Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Limiting file types for a specific DocumentChooserBlock() Block in Wagtail Steamfield
I'm trying to limit query results for a specific DocumentChooserBlock inside of a wagtail stream field block. I already know that you can limit file types for DocumentChooser for a page type by using hooks, but I would like to avoid limiting possible file types page wide in case I need them for other StreamField blocks. Are there any possible ways to implement what I am trying to achieve here? -
How i read the django log.debug() output and store in variable for display in my templates?
In logging setting i have set the output in console, and i want to read the console output for example a = log.debug("hello") print(a) But i tried this its return None -
Django ckeditor - How to create thumbnail of uploaded images by default
In settings.py I have CKEDITOR_IMAGE_BACKEND = 'pillow' but a thumbnails have not been created automatically. In docs v.6.1.0: Set CKEDITOR_IMAGE_BACKEND to one of the supported backends to enable thumbnails in ckeditor gallery. By default no thumbnails are created and full size images are used as preview. Supported backends: pillow: Uses Pillow How should I do it? Thanks! -
Django Filters NameError: name 'group' is not defined [closed]
When i am trying to render a view,i try to check by filter if the group is null or not. I already defined "group" in models as Foreignkey but it gives me the error.How can i solve it? Error File "/root/server/accounts/filters.py", line 33, in filter_queryset group == null NameError: name 'group' is not defined Views.py class GrouppArticleViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Article.objects.all().order_by('-timestamp') serializer_class = ArticleSerializer filter_backends = [GroupArticlesFilterBackend] Filters.py class GroupArticlesFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.exclude( group == null ).filter( group__groupmembers_set__author=request.user ).distinct() Models.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') group = models.ForeignKey(Group,on_delete=models.CASCADE,null=True,blank=True,related_name='grouparticle') caption = models.CharField(max_length=250) -
Django Form - How to create a custom form template with a loop for one field?
I'm creating a web app which uses Django's templating engine. Having said that, one of my models is called Order. The Order model, aside from the other models, also uses a model Food - this is a ManyToMany relationship. Food model uses model Category to define food categories (which should contain food categories like Pizza, Burgers, Wine, Beers, etc.) - this is a ManyToMany relationship, as well. Now, I'm trying to create a form where the user will be shown a form with separated categories. As of now, all of the foods from the Food model are just shown one by one, one below another one. They are not categorized in the form template. Currently, they are shown by default, as a simple list of foods where user can choose any of them. I want the user to choose any foods they want, but display them categorically (all of the pizzas under the Pizza category, all of the burgers under the Burgers category, etc.). My models.py looks like this: class Category(models.Model): """ Model for food categories """ name = models.CharField(max_length=100) description = models.TextField(max_length=300) date_created = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"{self.name} / {self.description[0 : 50]}..." class Food(models.Model): """ Model … -
How to limit number of clients in django channels' room
I wish to limit the number of users in a room to 2 because I am making a socket game were two palyers can play a tic-tack-toe or a connect-4 game so I a trying to find some way of limiting only 2 players in one room. Down below is my comsumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class GameRoom(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = 'room_%s' % self.room_name print(self.room_group_name) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() I have removed some of the less necessary methods from this question -
django database bug inccorect printing choice field
so i am trying to take data from admin panel and one field is choice field (male and female). when i registered users with female and male type in my dashboard everyone have only 1 value which is female so i need to fix it but how i dont know here is my code about views models and dashboard. models.py class Id(models.Model): first_name = models.CharField(max_length=100, null=True) CHOICES = [('Male', 'Female'), ('Female', 'Male')] gender = models.CharField(max_length=30, choices=CHOICES) def __str__(self): return self.first_name this is views def home(request): context = { 'posts': Id.objects.all(), 'title': 'Home' } return render(request, 'blog/home.html', context) def about(request): return render(request, 'blog/about.html', {'title': 'About'}) and last this is my home.html (dashboard where all my users data will showing up {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.first_name }}</a> </div> <p class="article-content">{{ post.gender}}</p> </div> </article> {% endfor %} {% endblock content %} -
How to stream pdf response as file attachment?
I have a model models.py class Dibbs(models.Model): name = models.CharField(max_length=20) views.py def index(request): dibbs_obj = Dibbs.objects.all() context ={'dibbs_obj':dibbs_obj} return render(request,"index.html",context) template: {% for i in dibbs_obj %} <td data-label="name"><a href="{% url 'display_pdf' %}">{{ i.name }}</a></td> {% endfor %} There is the exact pdf file of name in the media/uploads/ folder. So, I created another view function to stream the pdf file as file response when I click on the name in the template def display_pdf(request,id): buffer = io.BytesIO() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='') How to properly use this FileResponse function so that it opens the link of the same name? (In this case, the data that is in the name have its corresponding pdf file as name.pdf in the media/uploads/ folder) -
How to get Django MultiSelectField values
I have installed Django MultiSelectField through the library django-multiselectfield==0.1.12 and here is my code. models.py: class Job(models.Model): CONTRACT = (("1", _("Indefinido")), ("2", _("Temporal")), ("3", _("Formación o Prácticas")), ("4", _("Autónomo o Freelance"))) contract = MultiSelectField(verbose_name=_("Contract"), max_length=200, choices=CONTRACT, null=True) The Django Admin Form works well, i can select various optionsare saved and show again selected. The database store the list of option ids correctly. But when try to access attribute values on python appears None: print(self.job.contract) None, None Anybody could help me please ? Thanks in advanced. -
How to make a field editable while creating, but read only in existing objects?
I've a django Model, and want to be able to set an id while creating. But once created, the id of existing object shouldn't be editable. class Vehicle: id = models.UUIDField(primary_key=True, default=uuid.uuid4) I see that I need to turn do "editable=True" (which is the default) on the id field, but this would allow editing the id field later on as well. -
Passing POST request by AJAX, Django problem
my view is : def creating_profile(request): if request.is_ajax and request.method == "POST": array = request.POST.get('nums') print(request.POST.get('nums')) else: print('it's not ajax') my js: const RegisterForm = document.forms["RegisterForm"]; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; let nums = [1, 2, 3] RegisterForm.addEventListener('submit', () => { $.ajax({ headers: { 'X-CSRFToken': csrftoken }, url: '/account/creating-profile/', type: 'POST', data: { nums: nums }, success: function (data) { // } }); but it returns None the result of print(request.POST.get('nums')), I would be glad if someone help me about this issue -
django: Invalid block tag on line 8: 'endblock'. Did you forget to register or load this tag?
Please help with the error I am getting following along a django book.The errors states: "Invalid block tag on line 8: 'endblock'. Did you forget to register or load this tag?". Attached is the image. Thanks django webpage error {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} {% if user.is_authenticated %} Hi {{user.username}}! <p><a href="{% url 'logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> | <a href="{% url 'signup' %}">Sign Up</a> {% endif %} {% endblock content %} -
KeyError : But the key exists and getting the good result
I have an API that analyse items contained in an image url and return me a dictionnary, everything is OK until I try to count how many occurences of a key, value pair ! The problem is that Python tell me that there is a KeyError on a key that exists and moreover I'm getting the result I want ... To explain, the first for loop is here to access the first dict and then I'm using Counter to group values contained in the 'labelName' key by their key. I'm learning Python just to say. @api_view(['GET']) def send_image_to_url(request, encoded_url): analyzed_image = analyze_url(encoded_url) items_list = [] for response in analyzed_image.values(): aggregated_items = Counter(item["labelName"] for item in response) return Response(aggregated_items) Here is analyzed_image : { "response": [ { "labelId": 8722, "labelName": "Sofa", "score": 0.99225813 }, { "labelId": 8732, "labelName": "Low Table", "score": 0.9896868 }, { "labelId": 8729, "labelName": "Carpet", "score": 0.98912084 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.9777501 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.97317785 }, { "labelId": 8714, "labelName": "Chair-Armchair", "score": 0.9629707 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.91856897 }, { "labelId": 8722, "labelName": "Sofa", "score": 0.88815445 }, { "labelId": 8717, "labelName": "Cushion", "score": 0.6156193 }, { "labelId": … -
How to change `related_name` field of model after migration in Django?
Initially I created a model as shown in image here: MyModel is dummy name Notice, user as a field with ForeignKey relation with related_name as creater which is actually a spelling mistake which I made. Then I ran python manage.py makemigrations and python manage.py migrate commands. After that I realised that I need to correct the spelling and I changed it accordingly as shown in image here: Notice change Now again to incorporate these changes I ran the above two command but when I ran python manage.py makemigrations command I got following error: Error by Django -
Problems with dynamic like and dislike buttons via django templates and JS
I'm trying to dynamically create and use like and unlike buttons for my cs50w project, which should of course allow the user to like or unlike a post and switch a like button to an unlike button and so on. Now, the infuriating thing is, the like and unlike mechanics themselves work, but the buttons are screwing with me. Either I can't get the opposite button to be created after I deleted the original one via Javascript (I tried to use appendChild and CreateElement, to no avail). Or if a post has more than 1 like then more buttons show up with 2/3 of them being duds, etc. I check in a Django view if the current user has liked any posts (the likes are in their own model with 2 Foreign Keys), then if there are any posts then I send them as context to the necessary templates. Inside the templates themselves, I check if a post corresponds to the context if it does I generate an Unlike button, if not I generate a Like button. I've tinkered and googled but the situation is not improving at all... Code: index.html: {% extends "network/layout.html" %} {{ user.username|json_script:"username" }} {% block … -
Querying for GroupBy in Django
class Author(models.Model): first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10, null=True, blank=True) def __str__(self): return f'{self.first_name} {self.last_name}' class Book(models.Model): name = models.CharField(max_length=100) author = models.ManyToManyField(Author, related_name='book_author') price = models.SmallIntegerField() def __str__(self): return self.name Hello there! I've been trying to group by the cost of books in the above model according to the author (as there can be multiple authors for a single book). I know it can be done using groupby but I don't know how to query for it in Django ORM, I tried searching the web but didn't get the relevant solution. What I'm trying to do is, for e.g., if a book 'Wonder' has two authors 'A' and 'B' and they have written together with other books as well, like 'Wonder' by 'A' and 'B' and 'New' by 'A' and 'B' So, I want to query for the books with the combination of their authors + a total cost field of all the books written by the authors (many-to-many author combination). If there is a way, please help and sorry for the bad English. -
suit_form_tabs is not working in Django-Admin
I am using django-suit to create my website's admin. I want to create different tabs in a form, for that I am using suit_form_tabs property I added it in my admin but it does not working and not showing in admin form. change_form_template = 'admin/view_order.html' def customer_username(self, obj): return format_html(f'''<a href="/admin/signin/customer/{obj.username.id}/change/">{obj.username.username}</a>''') def generate_invoice(self, obj, request): print("Generating invoice......") return messages.info(request,message="generate invoice") def view_order(self, obj): return f"Order No #{obj.id}" list_display = ['view_order', 'customer_username', 'full_name', 'email','shipping_mobile_number', 'created_at', 'order_status'] suit_form_tabs = (('info', 'Info'), ('address', 'Address'),('products', 'Products'),('tracking','Tracking')) @csrf_protect_m def changeform_view(self, request, object_id=None, form_url='', extra_context=None): if not object_id: self.form = OrderForms2 self.inlines = [orderProduct,OrderTrackingAdminTabular] self.fieldsets = [ ('Info', { 'classes': ('suit-tab', 'suit-tab-info',), 'fields': ['full_name'] }), ('Address', { 'classes': ('suit-tab', 'suit-tab-address',), 'fields': []}), ('Products', { 'classes': ('suit-tab', 'suit-tab-products',), 'fields': []})] self.suit_form_tabs = (('info', 'Info'), ('address', 'Address'),('products', 'Products'),('tracking','Tracking')) extra_context = {} extra_context.update({ 'show_save': True, 'show_save_and_continue': True, 'show_save_and_add_another': False, 'show_delete': False, 'Add_Order': True,}) return admin.ModelAdmin.changeform_view( self, request, object_id=object_id, form_url=form_url, extra_context=extra_context) obj = self.get_object(request, unquote(object_id)) if request.method == 'POST' and 'generate_invoice' in request.POST: self.generate_invoice(obj, request) return redirect(f'/api/v1/order/generate_invoice/{obj.id}/') self.form = OrderForms self.inlines = [] if request.method == 'POST' and 'save_delivery_partner' in request.POST: if not len(request.POST['delivery_partner']): del_partner = None else: del_partner = request.POST['delivery_partner'] obj.delivery_partner = del_partner obj.save() return HttpResponseRedirect(request.get_full_path()) if request.method == … -
Could not determine join condition between parent/child tables on relationship Product.collections
The relationship between Product and Collection is many to many. A product can be in many collections and each collection can have many products. For such case, I want to convert the django models to sqlalchemy in fastapi. Below is a table for product and collection in django models class Product(models.Model): product_type = models.ForeignKey( ProductType, related_name="products", on_delete=models.CASCADE ) name = models.CharField(max_length=250) slug = models.SlugField(max_length=255, unique=True, allow_unicode=True) class CollectionProduct(models.Model): collection = models.ForeignKey( "Collection", related_name="collectionproduct", on_delete=models.CASCADE ) product = models.ForeignKey( Product, related_name="collectionproduct", on_delete=models.CASCADE ) class Collection(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=255, unique=True, allow_unicode=True) products = models.ManyToManyField( Product, blank=True, related_name="collections", through=CollectionProduct, through_fields=("collection", "product"), ) background_image = VersatileImageField( upload_to="collection-backgrounds", blank=True, null=True ) I tried the below way to migrate django model to sqlalchemy. However, I got following error sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Product.collections - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression. sqlalchemy class Product(Base, TimestampMixin): id = Column(Integer, primary_key=True, index=True) title = Column(String(255), nullable=False) slug = Column(String, index=True, unique=True) # referencing the parent product_type_id = Column(Integer, ForeignKey("producttype.id")) product_type = relationship("ProductType", back_populates="products") collections = relationship( "Collection", back_populates="product", ) collectionproduct … -
Django mongoengine rendring pdf file
I am trying to open my pdf file from my search result as i am using mongoengine in django. Recently i shift from sql to mongodb. how to open pdf file from frontend mongoengine django search.html for sql db.below code is for sqldb and i am looking for similar to this in mongoengine django ''' <h1>You searched for {{ searched }} </h1> <br/> {% for i in Document %} <a href="{{ i.file.url }}" class="btn btn-outline-secondary" target="_blank"> {{i.filename}}</a> <br/> ''' This is my search function ''' def search(request): if request.method == "POST": if request.POST.get('searched'): searched = request.POST.get('searched') dbname = my_client['resume'] collection_name = dbname["user_resumes"] collection_name.create_index([("num2","text")]) Document = collection_name.find({"$text": {"$search": str(searched)}},{"score": {"$meta": "textScore"}}).sort([("score",{"$meta":"textScore"})]) return render(request,'search.html'{'searched':searched,'Document':Document}) ''' if you have any reference please share it with me. -
Returning data from task Django+Celery
I'm new to Django and Celery. So what I'm trying to do is return data after it has been queried via the corresponding models object in a task. tasks.py from celery.decorators import task from .models import * from .serializers import * from .views_api_utils import * from rest_framework import status from rest_framework.response import Response @task(name="get_all") def get_all(): dummies = Dummy.objects.all() return dummies views.py @api_view(["GET"]) @authentication_classes([]) @permission_classes([]) def dummy_list_all(request): """ list all dummy objects """ if request.method == "GET": dummies = get_all.delay() serializer = DummySerializer(dummies, many=True) return Response(dummies, status=status.HTTP_200_OK) The issue at hand is that I keep getting this error TypeError: Object of type AsyncResult is not JSON serializable. Advise? -
emotion detection face-api-js models connot load in the django
''' Failed to load resource: the server responded with a status of 404 (Not Found) :8000/models/face_landmark_68_model-weights_manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found) :8000/models/face_recognition_model-weights_manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found) face-api.min.js:1 Uncaught (in promise) Error: failed to fetch: (404) Not Found, from url: http://127.0.0.1:8000/models/tiny_face_detector_model-weights_manifest.json at face-api.min.js:1 at face-api.min.js:1 at Object.next (face-api.min.js:1) at n (face-api.min.js:1) (anonymous) @ face-api.min.js:1 (anonymous) @ face-api.min.js:1 (anonymous) @ face-api.min.js:1 n @ face-api.min.js:1 :8000/models/face_expression_model-weights_manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found)''' anyone help to solve this error to load models can i give path for inside the js file? means can we used load static in js ? if yes pleas help ''' const video = document.getElementById('video') Promise.all([ faceapi.nets.tinyFaceDetector.loadFromUri({% static '/models' %}), faceapi.nets.faceLandmark68Net.loadFromUri({% static '/models' %}), faceapi.nets.faceRecognitionNet.loadFromUri({% static '/models' %}), faceapi.nets.faceExpressionNet.loadFromUri({% static '/models' %}) ]).then(startVideo) function startVideo() { navigator.getUserMedia( { video: {} }, stream => video.srcObject = stream, err => console.error(err) ) } video.addEventListener('play', () => { const canvas = faceapi.createCanvasFromMedia(video) document.body.append(canvas) const displaySize = { width: video.width, height: video.height } faceapi.matchDimensions(canvas, displaySize) setInterval(async () => { const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions() const … -
Django Help: AttributeError: module 'django.db.models' has no attribute 'BooleanFeild'
I am working on a simple chat application in Django 3.2.5, I faced an issue here when I gave python manage.py makimigrations command, the terminal showed this error File "C:\Python\Python3.9.6\Scripts\ChatApp\chat\models.py", line 8, in Message is_read = models.BooleanFeild(default=False) AttributeError: module 'django.db.models' has no attribute 'BooleanFeild' And the code of the models.py file is from django.contrib.auth.models import User from django.db import models class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=12000) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message class Meta: ordering = ('timestamp',) Please help me in resolving this error. Your kind response will really be helpfull. -
How <object> or <iframe> does not work with Nginx reverse proxy
My website has a section to display another website by using . It works fine if user access the web server directly. However, that section does not show anything if I put the web behind nginx reverse proxy. I wonder if any nginx configuration shoud be added to support this application. Thank you. HTML <div class="container-fluid"> <div id="terminal" style="height: 800px; width: 100%;"> <div> </div> JS $("#consolebutton").click(function(e) { e.preventDefault(); var device = $('#device option:selected').text(); $.ajax({ type: "POST", url: "{% url 'Generate_Console_Session' %}", headers: { "X-CSRFToken": "{{ csrf_token }}" }, data: { "device": device }, success: function(result) { var instance = JSON.parse(result); var ip_address = instance["ip_address"]; var console_string = '<object type="text/html" data="http://172.18.1.10:8888?hostname=' + ip_address + 'width="1500px" height="800px" style="overflow:auto"></object>'; $("#terminal").html(console_string); }, error: function(result) { alert('Internal Error'); } }); }); Nginx server { listen 8443 ssl; server_name 127.0.0.1 172.18.1.10 managementserver; ssl_certificate /etc/nginx/cert.crt; ssl_certificate_key /etc/nginx/cert.key; ssl_session_cache builtin:1000 shared:SSL:10m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4; ssl_prefer_server_ciphers on; access_log /var/log/nginx/app.log; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://console:8000; proxy_read_timeout 90; } } -
How to access user details in all pages in django?
After login I want to access User details when ever I want (Particularly in navigation bar). I did not use user model provided in django. I created my own model like this for authentication. My database is stored in mysql on phpmyadmin(Xampp). AdminUser Modal class adminUser(models.Model): username=models.CharField(max_length=50) firstname=models.CharField(max_length=50) department=models.CharField(max_length=50) name=models.CharField(max_length=50) mail=models.CharField(max_length=50) id=models.IntegerField(primary_key=True) password=models.CharField(max_length=200) class Meta: db_table="admin_users" admin_users.py def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username is not None and password is not None: user=adminUser.objects.get(username=username) hashed_password = user.password is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8')) print(is_check) if is_check==True: return redirect(reverse('faq_index')) else: return render(request,'AdminUsers/login.html') return render(request,'AdminUsers/login.html') During the login User Details can be only access by login function but I want to access user details in all pages for navigation bar and also want to find out whether user is authenticated or not. As I am not using User Model in django so I can not user user.is_authenticated(). So How do I do this? -
How i can to refactor code model using Built-in class-based generic views in django?
i implements Views with Built-in class-based generic views in django. i using a Listview CreateView UpdateView DeleteView like this. @method_decorator(decorators, name='dispatch') class CustomerListView(ListView) @method_decorator(decorators, name='dispatch') class CustomerCreateView (CreateView ) @method_decorator(decorators, name='dispatch') class CustomerUpdateView(UpdateView ) @method_decorator(decorators, name='dispatch') class CustomerDeleteView(DeleteView ) and this urls.py path('customer/', views.CustomerListView.as_view(), name='customer-list'), path('customer/add', views.CustomerCreateView.as_view(), name='customer-add'), path('customer/update/<id>', views.CustomerUpdateView.as_view(), name='customer-update'), path('customer/delete/<id>', views.CustomerDeleteView.as_view(), name='customer-delete'), this code work normally. but i have implement multiple model with this pattern such as Customer,Employees,Woker, ..... and more. i want to know how to refacetor code like this. in views.py ------------- class Customer(Somthing): # this include Listview CreateView UpdateView DeleteView model = CustomerModel class Employee(Somthing): # this include Listview CreateView UpdateView DeleteView model = EmployeeModel class Woker(Somthing): # this include Listview CreateView UpdateView DeleteView model = WokerModel in urls.py ------------- path('customer/', views.Customer.as_view()), path('employee/', views.Employee.as_view()), path('worker/', views.Worker.as_view()), how the best way to implements?. thank you for expert.