Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem changing format in django project
I have a problem with frontend development. Let me bring you up to date: I have a table on the site that imports data from the database, I need this data to be changed by an operator, I created a Change button after which a popup appears, in the Date field I was able to change the format and screw the date selection through the calendar, but I changed the format in the Estimated time field It doesn’t work in any way, it always says Invalid date.I'm new to programming, so don't judge too harshly :) Thanks for your time Here's the code: </thead> <tbody> {% for order in orders %} <tr> <td>{{ order.status }}</td> <td>{{ order.date|date:"Y-m-d"}}</td> <td>{{ order.preferred_time|time:"H:i" }}</td> <td>{{ order.cargo_type }}</td> <td>{{ order.cargo_quantity }}</td> <td>{{ order.order_number }}</td> <td>{{ order.cargo_weight }}</td> <td>{{ order.driver_name }}</td> <td>{{ order.vehicle_license_plate }}</td> <td>{{ order.vehicle_type }}</td> <td>{{ order.shipper }}</td> <td>{{ order.transport_company_name }}</td> <td> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editOrderModal" onclick="openEditModal('{{ order.id }}', '{{ order.status }}', '{{ order.date }}', '{{ order.preferred_time }}', '{{ order.cargo_type }}', '{{ order.cargo_quantity }}', '{{ order.order_number }}', '{{ order.cargo_weight }}', '{{ order.driver_name }}', '{{ order.vehicle_license_plate }}', '{{ order.vehicle_type }}', '{{ order.shipper }}', '{{ order.transport_company_name }}')">Edit</button> </td> </tr> {% endfor %} </tbody> </table> … -
Как достать Id запроса у юкассы [closed]
Короче суть вопроса.У меня есть админка и туда приходят новые заказы,но они туда приходят в любом случае,успешно ли либо не успешно оформлен заказ,в чем суть мне нужно проверять статус заказа после его оплаты и добавлять данные в админку,но чтобы проверить статус заказа нужно запомнить id самого заказа,во первых даже если я пытаюсь его запомнить таким образом payment_id = request.POST.get('payment_id'),то ничего не выходит(payment_id = request.POST.get('id') так тоже).Так Payment.find_one(payment_id) он выводит такую ошибку ValueError at /orders/create/ Invalid payment_id value payment_id = request.POST.get('payment_id') payment = Payment.find_one(payment_id) if payment_id.status == 'succeeded': то есть по сути я хочу вот так сделать,но каждый раз выходит ошибка.Помогите пожалуйста,уже очень долго мучаюсь с этим,если что это Юкасса -
Web scraping from cardboard.market and want to pull the cheapest price value for any given search
I am developing a website using Django for sports cards and my goal is to be able to display the lowest price of any given card using Selenium with ChromeDriver. For example I am using the soccer player David Seaman from the card set 1990 Pro Set. I created a function that should go to https://cardboard.market/, search for the card, sort by the lowest price first, then pull the value of the first card in the results (this is the cheapest card). It currently is not working, it is returning a blank error message that looks like this: Error: Message: Any ideas of what the problem could be or if there are any other ideas of accomplishing this goal please let me know! This is what I currently have: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def get_lowest_card_price(card_name): base_url = "https://cardboard.market/" search_url = f"{base_url}search?q={card_name}" try: # Set up ChromeDriver driver_path = "C:/Webdrivers/chromedriver.exe" service = ChromeService(driver_path) driver = webdriver.Chrome(service=service) # Navigate to the search URL driver.get(search_url) # Wait for the sorting button to be clickable sorting_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CLASS_NAME, … -
How to install django specific version?
how To install specific Django Version i am getting only latest django version and i want an older version for my project work and that specific version is required for my working enviornment want to downlod Django older version -
Should I use chunks() or save() to save files in Django?
I'm a little confused. When saving an uploaded file in Django should I save it using FileSystemStorage( fs.save() ) or should I use chunks? I just want to ensure that I use chunking to save files that are large so that they don't impact performance. But I'm also reading here that files over 2.5MB are streamed to memory by default so does that make chunking obsolete? -
Why is my Multiple Select Field only returning one value?
I am a beginner in Django and web development in general. I have this page in which the user will choose which tags they'd like to search for and the program will search for images which contain that tag. Here's the form page: <form action="{% url 'search' %}" method="post"> {% csrf_token %} <select name="psearch" id="psearch" multiple> {% for tag in tags %} <option value="{{tag.name}}">{{tag.name}}</option> {% endfor %} </select> <button type="submit">Search</button> </form> Which produces this: However, when I try to obtain the choices for the actual search it seems to only return one value. Here's the actual view which will require this information. def search_view(request): if request.method == 'POST': psearch = request.POST['psearch'] images = Image.objects.filter(tags__name = psearch) return render(request, 'search.html', {'psearch':psearch, 'images': images}) else: return render(request, 'search.html', {}) I have tried printing the actual result of psearch, for testing, here's an example: I selected 'Praia' and 'Barco', however the according to the terminal outcome was just Barco: How can I make this return as a list of all selected objects? -
NoReverseMatch at /seller_page/2/
by clicking the close button only the seller should be able to close the auction, but here the keys are displayed for everyone and when you click on them, this error occurs. What's wrong? File "C:\Users\Desktop\work on it\commerce\auctions\views.py", line 195, in seller_page return render(request, 'auctions/product_detail.html', {'seller_offers': seller_offers}) Thanks in advance for taking the time to respond:) views.py: def seller_page(request, product_id): seller_offers = get_object_or_404(Bid, pk=product_id) if request.method == 'POST': offer_id = request.POST.get('offer_id') offer = get_object_or_404(Bid, pk=offer_id) offer.is_closed = True offer.save() return render(request, 'auctions/product_detail.html', {'seller_offers': seller_offers}) product_detail.html: <ul> {% for offer in offers %} <li>{{ offer.user.username }} offered ${{ offer.offered_price }}</li> <form method="post" action="{% url 'seller_page' offer.id %}"> {% csrf_token %} <input type="hidden" name="offer_id" value="{{ offer.id }}"> <button type="submit">Close Offer</button> </form> {% endfor %} </ul> urls.py: path('seller_page/<int:product_id>/', views.seller_page, name='seller_page'), -
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