Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to add video as assets in Django project? And calling it's path in view file? I'm trying to add it static files but it not working
I want to add some videos about 200 short video to my project django to proccess them with moviepy package When I call my view with request URL ...and this view contain script to process these video as at first it call the path of each video but this step does not work.... I add videos to static files but not working Also adding it in separate file not working I need way to add these videos as assets and processing them -
How to make login in django via login/pass from database?
There is a table 'user' in db which has an attributes 'login', 'password' 'name' and others. How should i make login page? Passwords stored in non-encrypted type (just '1234') (1) I tried this: def check_login_password(request): args = {} args.update(csrf(request)) if request.POST: login = request.POST.get('login','') password = request.POST.get('password', '') user = auth.authenticate(username=login, password=password) if user is not None: auth.login(request, user) return redirect('/test') else: args['login_error']="User not found!" return render(request, 'registration/login.html', args) else: return render(request, 'registration/login.html', args) But this function does not see users in db (user is always none), i only could login via superuser login/pass. (2) I tried use included Django authentication method with abstract user model: path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), - urls.py But it doesn't work too. Hope, you will help me make login page. -
Barcode Image is not being displayed on my html webpage
I have a django project which i'm using to create an inventory management system. I have a html website which shows the product description. It should also show the barcode image which is generated by the code. You can see the barcode image being generated by the program but you cannot view it in the webpage unless you open in manually by going to the file where the image is being saved. <!-- inventory/product_detail.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ product.name }}</title> </head> <body> <h1>{{ product.name }}</h1> <p>Barcode:</p> <img src="{{ product.barcode_image.url|default:'#' }}" alt="Barcode Image"> <!-- Use product.barcode_image.url to get the URL of the barcode image --> <p>Barcode Image URL: {{ product.barcode_image.url }}</p> <p>Quantity: {{ product.quantity }}</p> <p>Price: ${{ product.price }}</p> <a href="{% url 'product_list' %}">Back to Product List</a> </body> </html> This is the product_detail page. I would like the page to show me the barcode image being generated by my django code. -
django admin How do I change the order of the admin that came into the inlines?
How do I change the order of the admin that came into the inlines? I want to move that inlines admin field to under fields how to do that?? move inlines admin objects here is my code type here inlines = [SpekaerSNSInline] list_display = ('id', 'name', 'display_sns_info', 'affiliation', 'speaker_image', 'order', 'pub_start_date', 'pub_end_date', 'created_at', 'updated_at') I want to move inline block next to name how can I do that please help -
Dealing with NoReverseMatch error in Django
I'm working with Django right now. I have the line of code path('articles/<int:pk>', views.Article_List_View.as_view(), name='article-detail'). Whenever I run the server, I'm thrown the error NoReverseMatch at /catalog/articles/ Reverse for 'article-detail' with arguments '('828073a5-f232-46f2-aa35-25206b95a18f',)' not found. 1 pattern(s) tried: ['catalog/(?P<pk>[0-9]+)\\Z']. I understand that the article with that ID is not in that folder, but I can't figure out how to get it to save to that folder. -
Intercepting Django fields access
I understand that Django fields are Python descriptors. Is it possible that I do something extra when I access the field of a Django model? For example, articleInstsnce.author normally returns an Author object, can I also make Django print a log during the access? -
NoReverseMatch at /student/meals-attended/
``My template looks like {% extends "student/dashboard.html" %} {% load custom_filters %} {% block content %} <h4>Click on the meal and select the item you want to rate from that meal*</h4> {% if attended %} <div class="accordion" id="accordionExample"> {% for meal_name, items in meals_attended_items.items %} <div class="accordion-item"> <h3 class="accordion-header"> <button class="accordion-button collapsed bg-secondary text-white" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{ forloop.counter }}" aria-expanded="false" aria-controls="collapse{{ forloop.counter }}"> {{meal_name}} </button> </h3> <div id="collapse{{ forloop.counter }}" class="accordion-collapse collapse" data-bs-parent="#accordionExample"> <div class="accordion-body"> <ul class="list-group"> {% for item in items %} <a **href="{% url 'rate-an-item' meal_name|custom_meal_slice|add:item %}"** class="list-group-item list-group-item-secondary list-group-item-action">{{item}}</a> {% endfor %} </ul> </div> </div> </div> {% endfor %} </div> {% else %} <h6>You have not attended any meals yet.</h6> {% endif %} <footer class="footer fixed-bottom bg-light"> <div class="content-section text-center"> <p>* I am sorry but it only seemed fair that a student was allowed to rate an item from the last 5 meals he/she has attended </p> </div> </footer> {% endblock content %}` My View to handle to url in bold is : def rate_an_item(request, item_tag): space_positions=[] for index,char in enumerate(item_tag): if char==" ": space_positions.append(index) date_part = item_tag[:(space_positions[0])] meal_part = item_tag[space_positions[0] + 1:space_positions[1]] item_name_part = item_tag[space_positions[1] + 1:] instance = MenuItems.objects.get( date_to_be_served=date_part, meal=meal_part, item_name=item_name_part ) if request.method … -
PGvector Django SQL query not registering vector datatype
I am using PGvector with Django. While I usually leverage the PGvector ORM functionality, this usecase requires a complex query which I am running in raw sql as shown below. from .embed_utils import oaiembed from .models import Embedding from pgvector.django import HnswIndex from django.db import connection # TODO add performance metrics from time library test_vector = [0.1] * 1536 def queryModel(k, query): response = Embedding.objects.order_by(HnswIndex('embedding', query))[:k] print('response: ', response) return response def djankQueryModel(qvector, k, project_id): ''' Query the database for the k nearest neighbors to a given vector Parameters ---------- ref_vector : list The vector to query for nearest neighbors k : int The number of nearest neighbors to return project_id : str The project ID to filter the query by Returns ------- rows : list A list of tuples containing the product data and embedding data for the k nearest neighbors ''' print(type(qvector)) raw_query = ''' SELECT e.*, p.* FROM embeddings e JOIN products p ON e.product_id = p.product_id WHERE e.embedding_id IN ( SELECT e1.embedding_id FROM embeddings e1 JOIN ( SELECT product_id, MIN(embedding <#> %s) as min_distance FROM embeddings GROUP BY product_id ORDER BY min_distance ASC LIMIT %s ) as unique_products ON e1.product_id = unique_products.product_id ) ORDER BY e.embedding … -
How to make a post write the current user as the author?
I have some problems with my blog I appreciate it if you'd help me with them if I need to add any other codes please let me know 1- when I login as different users and write a post it always mentions only one of my accounts as the author it doesn't write the current user's username as the author and I can see and delete all the other users posts when I login with only one of the accounts and when I add an author part to my forms the box let me choose from all my accounts I want the current logged in user to be mentioned as the author also when I write a post the spaces between the lines and all that is correct but when I post it it all just displays beneath each other with no space between the lines detail.html {% extends "base.html" %} {% block content %} <html> <div style="margin-top: 20px"></div> <body class="text-center" style="line-height: 2;"> <article> <h1>{{post.title}}</h1> <p style="margin-top: 15px;">{{post.body}}</p> </article> </body> </html> {% endblock %} post.html <div class="container"> <div style="margin-top: 25px"></div> <div class="card-deck mb-3 text-center"> <div class="card mb-4 box-shadow"> <div class="card-header"> <h4 class="my-0 font-weight-normal">{{post.title}}</h4> </div> <div class="card-body"> {{ post.body|truncatewords_html:30 }} <hr> … -
How to add/edit/modify Django permissions on the frontend?
I am working on a Django/Python application that allows users to add employees but I am not sure how to go about adding custom permissions to different employees. For example: Employee one is a manager and needs the manager permission, this gives the manager access to all permissions. A new employee only needs viewing access. An employee needs permissions to edit/update forms, etc. If I am trying to create custom permissions to allow for managers to add those custom permissions to other employees, how do I go about that, from the front end? I know I can do it all in the back end, but I am just simply trying to allow for front end users to manage and add/edit permissions for other users/employees. I have it set up to where they can add new users, but how can I allow for adding custom permissions to individual users, all from the front end? Thank you for your help. -
how to get volley cookies and set it on next request - android
I use Django, when the user logs in through the API, the response that is sent to Android contains a cookie that includes CSRF and session, and I need to receive its values and send them in the header in the next request. I tried a lot, but the way I did not find a solution private void test() { RequestQueue requestQueue; requestQueue = Volley.newRequestQueue(this); String url_ = "https://xxxx.com/api/BF"; Map<String, String> params = new HashMap<>(); params.put("Email", UEmail); params.put("Password", UPassword); JSONObject JOParams = new JSONObject(params); JsonObjectRequest JORequest = new JsonObjectRequest(Request.Method.POST, url_, JOParams, response -> { try { String status_ = response.getString("Status"); if (status_.equals("OK_")) { Toast.makeText(this, "Login", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Login failed", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { Toast.makeText(this, "Data error", Toast.LENGTH_SHORT).show(); } }, error -> { Toast.makeText(this, "Connection failed", Toast.LENGTH_LONG).show(); }); requestQueue.add(JORequest); } } Please complete the code. I went through all the previous answers and didn't get any results -
Pass a query by Django to Javascript to work with it
I have a view which responsible for showing all recieved messages. @authenticated_user def home(request): employee = Employee.objects.get(user = request.user) #This Used to show Profile of the User in Navbar try: allMessages = Messages.objects.filter(reciever = request.user) arabic_messages_ids = [] for message in allMessages: if re.search(r'[\u0600-\u06FF]', message.message): arabic_messages_ids.append(message.id) unread_messages = Messages.objects.filter(reciever = request.user, is_read = False).values_list('id',flat=True) except Messages.DoesNotExist: allMessages = 0 unread_messages = 0 return render(request, "CSM/home.html", {'employee' : employee, 'messages' : allMessages, 'unreaded' : unread_messages, 'ar_messages_ids':arabic_messages_ids}) I have in my template a div in the left which responsible for showing User or The Senders of the Messages, and in the Right div show all the messages. What I want is : My sender are in tags. I want when I click on a sender the right div show only the correspondant message of that sender. Message model has fields : sender(user), reciever(user), message(textfield), date_created(datetime), is_read(boolean) I'm expecting a code by Javascript or some trick by html and css -
I want to make a points system in my application, but for some reason some kind of database problem pops up
I want to make sure that if the user answers the question correctly, then points are added to him, and the total number of points is saved in the db, but the problem is that the wrong type is constantly or something else is wrong It's a model, but it's probably not needed. class Task(models.Model): title_task = models.CharField(verbose_name="Заголовок", max_length=128) description_task = models.TextField(verbose_name="Задание") created_at_task = models.DateTimeField(auto_now_add=True) update_at_task = models.DateTimeField(auto_now=True) user = models.ForeignKey(to=User, verbose_name="Пользователь", on_delete=models.CASCADE) image_task = models.ImageField(verbose_name="Обложка", upload_to="advertisements/", blank=True, null=True) right_answer = models.CharField(verbose_name="Верный ответ",default=1, max_length=128) class Meta: db_table = 'tasks' def __str__(self): return f"task(id = {self.id}, title = {self.title_task})" @admin.display(description="дата создания") def created_date_task(self): if self.created_at_task.date() == timezone.now().date(): created_time_task = self.created_at_task.time().strftime("%H:%M") return format_html("<span style = 'color:blue;'>Сегодня в {} </span>",created_time_task) else: return self.created_at_task.strftime("%d:%m%y в %H:%M") @admin.display(description="дата обновления") def update_date_task(self): if self.update_at_task.date() == timezone.now().date(): update_time_task = self.update_at_task.time().strftime("%H:%M") return format_html("<span style = 'color:blue;'>Сегодня в {} </span>", update_time_task) else: return self.update_at_task.strftime("%d:%m%y в %H:%M") @admin.display(description="Изображение") def image_mini_task(self): if self.image_task: return format_html("<img src='{}' style = 'width:40px;'>", self.image_task.url) def get_absolute_url(self): return reverse('task', kwargs={"pk": self.pk}) another model, but it is already available to users class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(verbose_name="Баллы", default=0) views.py @login_required(login_url=reverse_lazy("login")) def task(request, pk): answer = request.POST.get("answer") tasks = Task.objects.get(id=pk) if answer: if answer == … -
Can't start django project in docker
At startup Redis does not work, therefore caching does not work, as I realized there is no connection to the database. I can't make loaddata fixtures and Celery can't connect to Redis either. In general, nothing works. No matter how many examples I found on how to create these files, everywhere it is done like this. Dockerfile: FROM python:3.11 WORKDIR /app COPY . . RUN pip install -r requirements.txt CMD python manage.py migrate \ && python manage.py loaddata site_blog/fixtures/posts.json \ && python manage.py loaddata site_blog/fixtures/post_category.json \ && python manage.py loaddata site_blog/fixtures/comments.json \ && python manage.py loaddata users/fixtures/users.json \ && python manage.py makemigrations \ && python manage.py migrate \ && python manage.py runserver 0.0.0.0:8000 docker-compose.yml: version: '3' services: postgres-db: image: postgres environment: POSTGRES_USER: db_mp_blog_username POSTGRES_PASSWORD: db_mp_blog_password POSTGRES_DB: db_mp_blog ports: - "5432:5432" restart: always redis: image: redis restart: always ports: - "6379:6379" site: build: context: . dockerfile: Dockerfile ports: - "8000:8000" depends_on: - postgres-db - redis environment: DB_NAME: "db_mp_blog" DB_USER: "db_mp_blog_username" DB_PASSWORD: "db_mp_blog_password" DB_HOST: "postgres-db" DB_PORT: 5432 CELERY_BROKER_URL: 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND: 'redis://127.0.0.1:6379' SECRET_KEY: 'django-insecure-c467_p2n3g4ni%yq_ebaqe1j2=!ozmn=zvgh8i23uzos&9p3pc' restart: always celery: build: . command: celery -A blog worker --loglevel=info depends_on: - site - redis - postgres-db environment: DB_NAME: "db_mp_blog" DB_USER: "db_mp_blog_username" DB_PASSWORD: "db_mp_blog_password" DB_HOST: "postgres-db" DB_PORT: 5432 … -
How to change data for form in CreateView, GET method Django
I'm new in django and trying create todo project and have some problems with categories. User shouldn'd see another user's categories in the createview for create this categories. User can create sub_category How can i do this? Thanks for help and advice my view: class CategoryCreate(CreateView): model = TaskCategory template_name = 'category_create.html' success_url = reverse_lazy('task_list') fields = ['title', 'sub_category'] context_object_name = 'categories' def form_valid(self, form): if self.request.POST['sub_category'] != '': sub_category = TaskCategory.objects.get(pk=self.request.POST['sub_category']) form.instance.depth = sub_category.depth + 1 form.instance.user = self.request.user return super(CategoryCreate, self).form_valid(form) my model: class TaskCategory(models.Model): title = models.CharField(max_length=200) sub_category = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) depth = models.IntegerField(default=0, blank=True) creater = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title -
python django broken pipe from 127.0.0.1 (cmd) [duplicate]
iI am currently following the Django website tutorial, but I keep encountering 'broken pipe from 127.0.0.1' errors, and I'm unsure why. Whenever this occurs, my website stops functioning. You can view the logs here. I've noticed that this issue is quite common, especially when I attempt to use the admin panel. I'm not sure why this is happening. -
Mocking does not work as expected (Django)
I have this code: // app1.service.py database = { 1: "Alice", 2: "Bob", 3: "Charlie" } def get_user_from_db(user_id): return database.get(user_id) // app1.tests.test_service.py import pytest from unittest import mock from app1.service import get_user_from_db @mock.patch("app1.service.get_user_from_db") def test_get_user_from_db(mock_get_user_from_db): mock_get_user_from_db.return_value = "Mocked Alice" username = get_user_from_db(1) # If I change it to mock_get_user_from_db(1) everything works fine assert username == "Mocked Alice" When i run 'pytest' in the command line, I get this: E AssertionError: assert 'Alice' == 'Mocked Alice' E - Mocked Alice E + Alice In the tutorial I am watching, get_user_from_db(1) returns "Mocked Alice", but in my local machine it returns just "Alice". It works fine when I use username = mock_get_user_from_db(1) instead of the username = get_user_from_db(1) Question: It this the expected behaviour that username = get_user_from*db(1) returns "Alice" in my case? (in the youtube video it returns "Mocked Alice") or am I just doing something wrong? -
In django rest famework serializer, how to change unique validator queryset dynamically
I'm using multiple databases. And every database has the same models. for example there is a concrete model A class AModel(models.Model): name = models.CharField("A name", max_length=10, unique=True) and a drf ModelSerializer class AModelSerializer(serilaizers.ModelSerializer): class Meta: model = AModel # from above fields = ['name'] And a proxy model which has a custom manager which uses a specific database class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().using("test") class ProxyModel(AModel): objects = CustomManager() class Meta: proxy = True and even if I dynamically change ModelSerializer's Meta.model to ProxyModel in init, name field's UniqueValidator queryset still refers to A.objects.all() not A.objects.using('test') What I figured out is ModelSerializer only refers concrete model fields, the model it is defined and their model's default manager, which in turn AModel.name, AModel and AModel's default manager in this case. Actually I solved it before using defining concrete models from an abstract model for each databases. and then set ModelSerializer model to abstract class, and then change ModelSerializer's Meta.model to a concrete model. So as I told it refers correct concrete model. but it seems error prone cause some of the code should be hard coded. and I hope to solve this problem more generically. Give me any idea. and if … -
Django Performance improvisation with async views
I am relatively new to django! In my django project i had lot of views and every view had database I/O operation and also had chat application in the same project using django channels (it don't had any database I/O). Now i am using wsgi application with gunicorn and only django channels part( web socket requests) with asgi using daphne. I referred lot of documentations and I realized that Database I/O operations should be performed in async for effective utilization of resources and django had added async support recently. So should I change all the views to async views, remove gunicorn and use only asgi server like daphne or uvicorn for the complete project? I don't have any idea about async implementation for ORM and views, If this sync to async migration make a lot of difference then i will learn and migrate, if not then i will leave as it is, So can someone please suggest me what shall i do now? -
I have an error when migrating manager.py on Hostmidia
File "/home/interlog/virtualenv/sistema_interlogrs/3.9/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "/home/interlog/virtualenv/sistema_interlogrs/3.9/lib64/python3.9/site-packages/psycopg2/init.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: no pg_hba.conf entry for host "::1", user "interlog_user", database "interlog_site", SSL off -
How to handle authentication with Telegram Bot in Django-rest-framework
I've reviewed all related questions, but I'm currently facing a problem for which I'm uncertain about the best approach. I have a web application built with Django and django-allauth. Telegram Bot login has been successfully implemented, and everything is functioning well. In addition, I have a Django Rest API within the same project. Here are my Authentication Backends: AUTHENTICATION_BACKENDS = ( 'registration.authenticate_backend.EmailOrUsernameModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', "rest_framework_simplejwt.authentication.JWTAuthentication",]} What I aim to achieve is as follows: Users join my TelegramBot, and through it, they should be able to manage their accounts and retrieve information via my Django Rest API. However, I'm unsure about how to handle authentication for these requests. Currently, I've implemented a solution by extracting the user_id from the messages that Telegram sends to me and directly using Django ORM. Nonetheless, I would prefer to leverage my API for this purpose. Thank you! -
I want to validate my Google Map Address Before submission in Django
I have a JavaScript code that autoload the address in my HTML and everything is working fine but whenever the person type the address which is not in google API my application shows error because it was able to calculate the distance I set. $(document).ready(function () { google.maps.event.addDomListener(window, 'load', initialize); }); // This example displays an address form, using the autocomplete feature // of the Google Places API to help users fill in the information. var placeSearch, autocomplete; var componentForm = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' }; function initAutocomplete() { // Create the autocomplete object, restricting the search to geographical // location types. autocomplete = new google.maps.places.Autocomplete( /** @type {!HTMLInputElement} */ (document.getElementById('id_shipping_address'))); // When the user selects an address from the dropdown, populate the address // fields in the form. autocomplete.addListener('place_changed', function() { fillInAddress(autocomplete, ""); }); } function fillInAddress(autocomplete, unique) { // Get the place details from the autocomplete object. var place = autocomplete.getPlace(); for (var component in componentForm) { if (!!document.getElementById(component + unique)) { document.getElementById(component + unique).value = ''; document.getElementById(component + unique).disabled = false; } } // Get each component of the address from the place details // and fill the … -
django form.modelchoicefield get selected value
How to display the "PS1 Failure" instead of value "4" in html template ? with below code form: class FailureCodeForm(forms.ModelForm): failure_name = forms.ModelChoiceField(queryset=FailureCodeModel.objects.all().order_by('failure_name'), label='Failure Code') class Meta: model = FailureCodeModel fields = ['failure_name'] view: if request.method == 'POST': TarFormField1 = FailureCodeForm(request.POST) if TarFormField1.is_valid(): FailureCode = TarFormField1.cleaned_data['failure_name'] template: {{ TarFormField1.failure_name.label_tag }} : {{ failure_name.value }} output: Failure Code: 4 -----> how to output the selected "PS1 failure" and not the value? printed html code: --------- No Boot PS1 Failure PrbsTest TrafficTest -
Table artifacts from django forms.Charfield
I'm using a CharField in a forms.Form subclass: search_term = forms.CharField(widget=forms.CharField()) It seems to render and work fine but I see table artifacts <tr>,<th>,<td> in the resulting html: <form method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="xxxx"> <tr> <th><label for="id_search_term">Search term:</label></th> <td> <input type="text" name="search_term" value="" required id="id_search_term"> </td> </tr> I'm hoping to clean the html up a bit. All ideas welcome! -
How to connect my mysql and mongoDB database in my django using web-scraping to populate my databases as a part of my backend?
Background: I'm working on a Django project where I need to populate my database with information about clubs, such as names, addresses, and contact information. The database models are already set up in Django. Models: I have models for City, Club, Event, UserProfile, Review, and Booking. The Club model includes fields for city (ForeignKey), name, address, contact info, and type. Objective: I want to scrape club data from a website (e.g., Goya Social Club) and populate my MySQL database using Django's ORM. Problem: I'm unsure how to effectively scrape the required data and map it to my Django models. I need advice on parsing HTML content and inserting the data into MySQL.