Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What can I do to accept only one image in the image field in the django admin panel
class Image(models.Model): title = models.CharField(("title"), max_length=50,blank=True) image = models.FileField(("image"), upload_to=generate_filename, max_length=100) def __str__(self): return self.title In the admin panel, images can be added to this section more than once, what I want is to enter an image only once and then remove the add image button. accept only one image How can I do this? -
Loop through list of tupples and return matching tupple value in Django
I have been struggling with this for hours, I have a variable : numbered_objects = [(index + 1, obj) for index, obj in enumerate(carts)] that makes me a list like this from my Model : [(1, <CalculatedNumbers: one>), (2, <CalculatedNumbers: two>), (3, <CalculatedNumbers: three>), (4, <CalculatedNumbers: four>), ...] and I have another variable : 'usernobat' that returns me a number How can I go through my list of tupples, find the matching tupple index that is matching 'usernobat' and return its data ? I have tried for loops like this : matching_object = None for obj in range(len(numbered_objects)): for key in numbered_objects[obj]: if key == usernobat: matching_object = key break but they all return None -
error in validating if validation true it store in cart_id
adject error in vs codeError line on self.validated_data if validation true it will store data in cart_id error does't cost me any problem in web page class CreateOrderSerializer(serializers.Serializer): cart_id = serializers.UUIDField() def save(self,**kwargs): print(self.validated_data['cart_id']) print(self.context['user_id']) (customer,created )= Customer.objects.get_or_create(user_id=self.context['user_id']) Order.objects.create(customer=customer) tried multiple method cart_id = self.validated_data print(cart_id) but nothing work -
Inventory Tracking Web Application
What are some innovative or cutting-edge technologies that could enhance the development of a Inventory Tracking Web Application)? Any recommended technology that I could use to enhance and improve the web application? Any tools help to build a wonderful UI? Technologies used: Python (Object oriented programming) Html, JavaScript, Css Django (Web framework) Ajax Js Mysql (Database) -
django static files are not loading on production server nginx
when I don't specify my port number in my url, static files are not loaded in that case. It works fine for xyz.com:8000 all the static files are loaded But when i use xyz.com, it doesn't load any static files. I'm using nginx server. this is my nginx configuration server { listen 80; server_name santhals.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/santhals/myapp/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
django-dynamic-formsets not working in one template - the same structure works in other template
I have this simple django template which only displays formset, allows user to add and remove instances of formset, and submittes the data by clicking the button. This templete is fine, it displays all the buttos etc. Here is the code: {% load static %} <script type="text/javascript" src="{% static 'jquery-3.7.1.min.js' %}"></script> <form id="myForm" method="post"> {% csrf_token %} {{profile_form.management_form}} <div id="formsets-container"> {% for form in profile_form %} {{form.as_p}} {% endfor %} </div> <button type="submit">Submit</button> </form> <script type="text/javascript" src="{% static 'jquery.formset.js' %}"></script> <script type="text/javascript"> $(function () { $('#formsets-container').formset({ addText: 'Add strategy', deleteText: 'Remove strategy' }); }); </script> I also have another template, from another project, which is more complex, but the structure of formset is the same, but it doesn't show buttons of adding and removing forms. Here is the code: {% extends "mainapp/base.html" %} {% block content %} {% load static %} {% load widget_tweaks %} <script type="text/javascript" src="{% static 'jquery-3.7.1.min.js' %}"></script> <div id="input-div1"></div> <div class="input-div2"> <form method="post"> {% csrf_token %} {{ simulation_form.initial_amount.label_tag }} {{ simulation_form.initial_amount|add_class:"form-control"}} {{ simulation_form.number_of_simulations.label_tag }} {{ simulation_form.number_of_simulations|add_class:"form-control" }} {{ simulation_form.number_of_trades.label_tag }} {{ simulation_form.number_of_trades|add_class:"form-control" }} <br> <button type="submit" name="save" class="btn btn-primary">Submit</button> </form> <form method="post" id="myForm"> {% csrf_token %} {{strategy_formset.management_form}} <div class="strategy-formset"> {% for form in strategy_formset %} {{form.as_p}} … -
django, smtp write that password or name incorrect, but name and password correct
i have djnago app when i try to start it smtp write error in console, that name and password are incorrect, but name and password is correct! this is my views.py last function "SendEmailView" use function from utils.py from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.messages.views import SuccessMessageMixin from django.views.generic.edit import CreateView from django.urls import reverse_lazy from django.http import HttpResponse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .models import Contact from django.urls import reverse from django.core.validators import validate_email from django.core.exceptions import ValidationError from django.core.mail import send_mail from django.http import JsonResponse from django.contrib.auth.mixins import LoginRequiredMixin from .utils import SendEmail #################################################### class MainView(TemplateView): template_name = 'emnosys/main.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context ################################################### def RegistrationView(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] myuser = User.objects.create_user(username, email, password1) myuser.save() return redirect('signin') return render(request, "emnosys/registration.html") ############################################### def SigninView(request): if request.method == 'POST': username = request.POST['username'] password1 = request.POST['pass1'] user = authenticate(username=username, password=password1) if user is not None: login(request, user) return render(request, "emnosys/main.html") else: return redirect('signin') return render(request, "emnosys/signin.html") ################################################ def SignoutView(request): logout(request) return redirect('home') … -
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 …