Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
calculate total amount from the sub total( New to JS )
when ever i change value in Quantity the sub total is calculate. but i need to calculate the total amount also by sum all the sub total values. How to achieve this. when ever i change value in Quantity the sub total is calculate. but i need to calculate the total amount also by sum all the sub total values. How to achieve this. -
Why do I get "This field is required" error from Django imageField?
I have problems with Django's image field. It says that the image field is empty even though I have selected an image This is my models.py: from django.db import models class Post(models.Model): picture = models.ImageField(upload_to="uploads") This is my forms.py: from django import forms from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = '__all__' This is my views.py: from django.shortcuts import render, redirect from .forms import PostForm def postsite(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.save() else: print(form.errors) return redirect('post') context = {'form':form} return render(request, 'post.html', context) And this is my post.html: <form action="" method="POST" enctyppe="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit Post"> </form> After I have selected an image for the imageField and submitted the form, the output of this code print(form.errors) is: <ul class="errorlist"><li>picture<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Because of other discussions about this error I tried to add this to my form: enctyppe="multipart/form-data" However, the error still persisted. -
Cause of this error: No List matches the given query
The user can add that product to the watch list by clicking on the add button, and then the add button will change to Rimo. And this time by clicking this button, the product will be removed from the list. There should be a link on the main page that by clicking on it, all the products in the watch list will be displayed, and by clicking on the detail button, you can see the details of the product, and by clicking on the remove button, you can remove them from the list. It sends me this error when I click on the button. What is wrong? Page not found (404) No List matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/add/?productid=1 Raised by: auctions.views.add Using the URLconf defined in commerce.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] product_detail/<int:product_id>/ [name='product_detail'] watchlist/<str:username> [name='watchlist'] add/ [name='add'] The current path, add/, matched the last one. views.py: @login_required(login_url="login") def watchlist(request, username): products = Watchlist.objects.filter(user = username) return render(request, 'auctions/watchlist.html', {'products': products}) @login_required(login_url="login") def add(request): product_id = request.POST.get('productid', False) watch = Watchlist.objects.filter(user = request.user.username) for items in watch: if int(items.watch_list.id) == int(product_id): return watchlist(request, request.user.username) … -
ImportError for Nonexistent File in Django's Main Branch After Working on Separate Branch
I'm encountering an ImportError in my Django project involving branch management. Here's what I did: New branch: In a branch named test-new-spider, I created and committed a file named spider_base.py, which includes a class SpiderStores and a new command to run the spiders. Switching to Main Branch: After committing these changes in the test-new-spider branch, I switched to the main branch, which does not include the spider_base.py file, as the changes were not merged. Issue in Main Branch: Now, when trying to run the spider in the main branch, I encounter the following error: ImportError: cannot import name SpiderStores This is confusing because spider_base.py does not exist in the main branch; it's only in the test-new-spider branch where it has been committed. I deleted some files that were generated as eggs and logs, thinking they might be causing conflicts or stale references. I disconnected from the virtual environment to ensure that there were no environment-specific issues contributing to the problem. I searched for any instances of spider_base and SpiderStores in the main branch to confirm that it indeed doesn't exist there. -
Django-cors-headers not working with Django and Vue
When I try to access my Django rest framework from the frontend I get this error and the data is not passed along enter image description here I tried using django-cors-headers and every setting for it that I could find online; absolutely nothing worked. Here are the settings from my settings.py file (currently commented out) enter image description here enter image description here I also tried using custom middleware that I found here on stack overflow. enter image description here I did not try to use the custom middleware and django-cors-headers together. I must have spent at least a day on this nonsense. I'd really appreciate a working solution or at least a workaround! PS: I am following this tutorial https://www.youtube.com/watch?v=7GWKv03Osek&t=189s He doesn't have the same problems that I am though. -
Cannot get the delete button to work in my Djangochat room app
When clicking the delete button, i get this message in the console and screen:Not Found: /delete_message/125/ HTTP DELETE /delete_message/125/ 404 [0.05, 127.0.0.1:63513]. The same code works in another system, but not here. The information is in the database with the correct id.. I want the user to be able to delete a message that may have the wrong information, or wrong code. Here is the code for submissions: room.html {% extends "base.html" %} {% block title %} {{room.name}} | {% endblock title %} {% block content %} <div class="p-5 text-center"> <h3 class="lg:text-6xl text-white">Room: {{ room.name }}</h3> </div> <div class=" flex flex-wrap w-full "> <div class="w-full md:w-2/3 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id="chat-messages"> {% for message in messages %} <div id="message-{{message.id}" class="p-4 bg-gray-200 rounded-xl"> <p class="font-bold"> {{message.user.username}} {{message.date_added}} </p> <p> {{ message.content|safe }} </p> <p>{% if message.user.username == current_user %}</p> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button class="float-right d-inline" onclick="deleteMessage({{ message.id }})"> del </button> <br/> <br/> </div> {% endif %} {% endfor %} </div> </div> <div class="w-full md:w-1/3 lg:mx-auto p-4 bg-white rounded xl"> <form class=""> <div> <textarea name="content" id="editor"></textarea> </div> <button class="px-5 py-3 rounded-xl text-white bg-teal-600 hover: bg-teal-700" id="chat-message-submit"> Submit </button> </form> </div> </div> {% endblock … -
Making requests after logging in django
I want to apologise upfront for a noob level question. I am working on an e-commerce project where I am making a bunch of requests to Django from REST. These requests are as follows, GET request for fetching products POST request for onboarding new products PUT request for updating products POST request for login GET request for cart details GET/POST/PUT requests for address related queries etc. Since a lot of these requests are user specific (i.e. my onboarded products/my addresses/my cart data) I want to somehow manage identify customer from the request without actually passing the customer id. Is there a way to achieve this? -
How to run makemigrations with docker
I have a Django project running in a docker container with poetry. I'd like to change one of the existing models to add an addition JSON field. When I run the project locally and try to migrate the changes with python manage.py makemigrations python manage.py migrate While makemigrations runs fine, migrate does not. When I try to migrate I get the following error: Traceback (most recent call last): File "/Users/ENV/Desktop/inventory/manage.py", line 24, in <module> main() File "/Users/ENV/Desktop/inventory/manage.py", line 16, in main execute_from_command_line(sys.argv) File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/core/management/commands/migrate.py", line 117, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/db/migrations/recorder.py", line 57, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/ENV/Desktop/inventory/.venv/lib/python3.12/site-packages/django/db/backends/base/base.py", line 330, in cursor … -
Update Postgres ArrayField in Django
I have simple Customer model with AarrayField. Does anybody know how I can append new number to this field? (Im using Django==4.2.7) models.py from django.contrib.postgres.fields import ArrayField from django.db import models class Customer(models.Model): product_ids = ArrayField( models.IntegerField(null=True, blank=True), null=True, blank=True ) Now in Django shell >>from from customers.models import Customer >>> c1 = Customer.objects.get(pk=1) >>> c1.prduct_ids????? >>> c1.product_ids = [10] or 10 # will just overwrite not append Django documentation is very modest on this, just few sentences on how to define filed nothing about update and similar things. Someone have some idea on how to append new intiger to this field ones I insatiate individual Customer in shell? Muchas gracias! -
How can blocked IP addresses of visitors be whitelisted?
One of my clients appears to have their IP addresses blocked by PythonAnywhere. They are unable to access my application from their office IP address, although access from their home IP is successful. This application is hosted on a paid account. I have reached out to PythonAnywhere's support team with two emails a few days ago but have not yet received a response. Does anyone have any suggestions for resolving this issue? I have analysed the server logs but can't see any indication of blocked connection. -
Why are my Django form answers being saved multiple times and deleting the contents of another DB table?
I'm a complete beginner to Django and I've created a form of radio selects - each question is dynamically populated from the Questions table of my database. When the form is submitted, it should save various details of each question into the Scores table of the database. Scores has foreign keys to Questions on the id_question column and to the table Companies on id_company. Currently I can show the correct values in a print statement, but saving them as instances has mixed results. Either each instance is saved multiple times with different values or every instance will take the value of one. I've tried moving the position of my save(), modifing the loops and how my data is stored, but the same problems keep repeating themselves. On top of everything else, upon submission of the form and the saving of the scores, all of the question data is wiped from the database. The rows and id's are not deleted, but the other columns are given a null value. I feel like I've approached this completely wrong, but I couldn't make sense of the Django documentation on forms and how to apply it to my project. A new row should be … -
django form on submission redirects to wrong url
So my code is behaving weirdly, I have this; Form <form action="{% url 'button-check' %}" method="POST"> {% csrf_token %} <div class="coupon"> <input id="coupon_code" class="input-text" name="coupon" value="" placeholder="ENTER COUPON CODE" type="text"> </div> <button class="tp-btn-h1" type="submit">Apply coupon</button> </form> Url from django.urls import path from . import views from .views import AddToCart, CartItems, AddCoupon urlpatterns = [ path('add-to-cart/<int:product_id>/', AddToCart.as_view(), name="add-to-cart"), path('cart/', CartItems.as_view(), name="cart"), # path('add-coupon/', views.AddCoupon, name='add-coupon'), path('button-check/', views.ButtonClickedCheck, name='button-check'), ] View def ButtonClickedCheck(request): print("button clicked!") I think it should just print on terminal "button clicked", but it doesn't and on top of that I get [17/Nov/2023 14:57:39] "GET /cart/?csrfmiddlewaretoken=w3YQEunqvvx3420ESxj319UeazutgSdGkYEFAHorlUEmDwzbNj2obbOTbDRHJE0y&coupon=Tom HTTP/1.1" 200 46725 and I am not working on /cart anywhere there. What's the way around here? -
how to solve unresolve attribute reference objects in pyCharm
I'm new to django and I was following a certain tutorial on it using the community Edition of pyCharm but I got this error that says unresolved attribute reference objects for class Product. I haven't missed any steps from the tutorial I followed but I don't really know why I'm getting the error. Please I need help on how to solve it. The error is actually from that place that I have Product.objects().all views.py from django.shortcuts import render from django.http import HttpResponse from products.models import Product def index(request): products = Product.objects().all return render(request,'index.html',{'products':products}) def new(request): return HttpResponse('New Products') models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=225) discount = models.FloatField() -
How to add custom choice to django CharField, where it takes argument as choices
I am trying to add custom choices in my Coustom List which is listed in "constanst.py" file constants.py DAYS_CHOICE = [ ('Monday - Friday', 'monday - friday'), ('Monday - Saturday', 'monday - saturday'), ('Flexible', 'flexible'),] models.py class JobPost(Timestampable, SoftDeletes): id = models.UUIDField(primary_key=True, unique=True, editable=False, default = uuid.uuid4) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=255, validators=[CustomLengthValidator(min_length=2, max_length=255, field_name='title')]) schedule_days = models.CharField(max_length=256, choices=DAYS_CHOICE) and i am importing that in the field, now the issue is when user enters the choice which is not in by default list it has to accept has add to the end of the default list.. -
Redirect from broken media library
Having updated my Python-2.7/Mezzanine-4.2.0/Django-1.8.19 server to Python-3.7/Mezzanine-6.0.0/Django-3.2 I had to move media library outside of static library as python 3.x doesn't allow media library inside static library. After that change urls like <myServer>:<myPort>/static/media/uploads/<myDocument> stopped working. I've been trying to fix them by django_redirects like: /static/media/uploads/<myDocument> -> /media/uploads/<myDocument> in psql: # select new_path from django_redirect where old_path like '/static/media/uploads%'; new_path ------------------------------------------------------------------ /media/uploads/whatever.pdf But it looks that django does not even try to check if the slug would be defined as old path of any Redirect. Would it be even possible to fix this ? -
Django QuerySet's _prefetched_objects_cache is empty when using the to_attr argument of Prefetch()
I'm writing tests to check that a Django QuerySet is prefetching what it should be. I can do this by checking the contents of an object's _prefetched_objects_cache property (via this answer). But it doesn't work if I use the to_attr argument of Prefetch(). Here's a simplified example that populates the cache, not using to_attr: books = Book.objects.prefetch_related( Prefetch( "authors", queryset=Author.objects.filter(author_type="MAIN"), ) ).all() I can then check the contents of _prefetched_objects_cache on an object in the QuerySet: >>> print(books[0]._prefetched_objects_cache) {'authors': <QuerySet [<Author: Author (ID #1)>]>} However, if I use the to_attr argument: books = Book.objects.prefetch_related( Prefetch( "authors", queryset=Author.objects.filter(author_type="MAIN"), to_attr="people" # <-- Added this ) ).all() ...then _prefetched_objects_cache is empty: >>> print(books[0]._prefetched_objects_cache) {} Is there a way to check that this has been prefetched? Where does it go? -
Mapping a view from an App directory to a URLS.py file in the project Directory for Django
On Django using VS as the Editor, I have 2 directories in the root folder. A Project Directory named Hell and an App Directory named Rango. I have already defined the Rango app Directory in the settings file of the project Directory. I have created a view in the app directory and I am trying to map this view to a urls.py file in the project Directory. However, I keep getting the error message that No Module named rango when I run the urls.py file. Can anyone help me here? The images of the code is your text is below URLS.PY CODE VIEWS.PY CODE SETTING.PY CODE` -
After edit the quantity is not increasing from stocks as well as not decreasing from the total stocks quantity, I want it should be updated in django
Now quantity of product is updating correctly but when I edit the data the quantity is not updating it is not decreasing as well as not increasing in the database, I want when I edit a data if the quantity is more than before the difference between old quantity and new quantity will be added and if the difference between old and new quantity is less than it will be decreased ... Please Help me in that models.py # models.py from collections.abc import Collection from django.contrib.auth.models import User from django.db import models from django.core.exceptions import ValidationError class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=15) address = models.CharField(max_length=255) def clean_mobile(self): mobile=self.mobile if len(str(mobile))!= 10: raise ValidationError("invalid mobile number") return mobile class Supplier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_name = models.CharField(max_length=255) product_price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products/') quantity= models.PositiveIntegerField(default=1) category=models.CharField(choices=CHOICES3,max_length=10) def __str__(self): return self.product_name CHOICES3 = [('Tshirt','Tshirt'),('Jeans','Jeans'),('Jacket','Jacket'),('Shoes','Shoes'),('Watch','Watch')] CHOICES2 = [('Polo-Tshirt','Polo-Tshirt'),('Levis-Jeans','Levis-Jeans'),('Denim-Jacket','Denim-Jacket'),('Puma-Shoes','Puma-Shoes'),('Titan-Watch','Titan-Watch')] class Stocks(models.Model): product_name = models.CharField(choices=CHOICES2,max_length=100) quantity = models.PositiveBigIntegerField(default=100) def __str__(self): return self.product_name views.py def supplier_dashboard(request): if request.method == 'POST': product_name = request.POST.get('product_name') product_price = request.POST.get('product_price') image = request.FILES.get('image') quantity = request.POST.get('quantity') category = request.POST.get('category') data = Supplier.objects.create(user=request.user, category=category, product_name=product_name, product_price=product_price, image=image, quantity=quantity) data.save() supplier = Supplier.objects.filter(user=request.user) return HttpResponseRedirect(reverse('update_stocks', args=[data.id])) else: supplier … -
How can I rewrite this SQL using the Django ORM, it uses, lag, partition and a select query as a table for the join
I have a query that works in SQL but I'm struggling to come up with the correct ORM: SELECT page, first_name, last_name, SUM(EXTRACT(EPOCH FROM (end_time - start_time))) AS total_active_time_seconds FROM ( SELECT page, "user_id", event_type, created_at AS start_time, LEAD(created_at) OVER (PARTITION BY page ORDER BY created_at) AS end_time FROM analytics_log WHERE (event_type = 'page_landed' OR event_type = 'moved_to_another_tab') ) as event_intervals left JOIN profiles_user ON user_id=profiles_user.id WHERE event_type = 'page_landed' GROUP BY page, first_name, last_name; The models in question are ` class Log(models.Model): page = models.CharField(max_length=255, null=True, db_index=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) user = models.ForeignKey('profiles.User', null=True, on_delete=models.SET_NULL) session_id = models.CharField(max_length=45, null=True, blank=True) event_type = models.CharField(max_length=50) meta_data = models.JSONField(null=True, blank=True) class User(AbstractUser): #regular user model fields ` I've looked at this example but its not quite the same: Partitioning with lag Basically I'm trying to figure out how long someone spend on a certain task from the logs, but they could leave the tab, come back, leave again etc. I've got the SQL working mostly as I want, I don't have enough data to be certain yet, but it seems close enough to real times. I'm struggling with adding the Query as a join. We can easily join the two tables … -
How to build database for an e-commerce website in development and how to deploy it in production mode? [closed]
I want to built an E-commerce website using HTML, CSS, Bootstrap, Javascript, Python and Django. How to make databases for an e-commerce website, what is virtual environment in development mode, in production, how to configure it in production mode? I have tried using Django and Sqlite3 default database. But won't have any knowledge regarding databases -
Docker (Postgres image): authentication problem
I am running a Django project at the moment and I have an error when I try to use the command python manage.py migrate. I have a docker image called explore_hub. When I run python manage.py migrate I have the followin error: System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory 'D:\2xProjects\Python\ExploreHub\explore_hub\static' in the STATICFILES_DIRS setting does not exist. Traceback (most recent call last): File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\base\base.py", line 289, in ensure_connection self.connect() File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\base\base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\postgresql\base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "suadmin" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\2xProjects\Python\ExploreHub\explore_hub\manage.py", line 22, in <module> main() File "D:\2xProjects\Python\ExploreHub\explore_hub\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DeerMe\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 458, in execute output … -
Unusual Occurrence in Django's Main Thread
I am encountering errors when attempting to execute my Django project using the command python manage.py runserver Kindly assist me in resolving these errors. Error Error Error Please help, its an emergency, its my tesis -
My django app automatically add a /static/ to any url not specified with the {% url %} tag
As stated in the title of my question my app is going on production and i configured all the static parameters, everything works fine except one thing and i can't seem to find the problem. When i make an <a href="#Description"> to get to an anchor for exemple, the link that is served is: www.example.com/static/#Description instead of www.example.com/mypage/#Description Thank you for your help ! This is my settings.py configuration: PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' # Ajout d'un dossier static non lié a une app en particulier STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] I've tried changing the configuration but i don't seem to find the problem. -
single positional indexer is out-of-bounds in django
views.py file def rpa_save(request): if request.method == 'POST': test_kodu = request.POST.get('test_kodu') test_kodu = str(test_kodu) OlcumSonucLOG, dfLimit, urun_kodu = Providers.getir(test_kodu=test_kodu,is_emri=is_emri) my providers.py file @staticmethod def getir(test_kodu,is_emri): _, cur = Connection.connect_to_btr() sfTestler = RawDataProvider.get_sftestler_db(cur, is_emri) # Buradan is emri bilgisi ile yapılan testlerin order_no larını alıyoruz # sfTestler = pd.DataFrame({'ORDERNO': [223030204106, 223030204106, 223030204106,223030204106,223030204106,223030204106,223030204106]}) #test için konuldu, silinecek firstOrder = min(sfTestler['ORDERNO'].values,default=None) lastOrder = max(sfTestler['ORDERNO'].values,default=None) df = RawDataProvider.get_pklsonuclar_db(cur, firstOrder, lastOrder) # Bu order_no'na ait bütün testler dfSpecific = df[df['TESTKODU']==str(test_kodu)] dfSpecific.loc[:, ["BATCHNO", "TESTNO"]] = dfSpecific.loc[:, ["BATCHNO", "TESTNO"]].astype('int') dfSpecific = dfSpecific.sort_values(['BATCHNO', 'TESTNO'], ascending=[True, True]) urun_kodu = dfSpecific['URUNKODU'].iloc[0].split("-")[0] when i try send test_kodu and is_emri variables to providers.py i get single positional indexer is out-of-bounds from this line urun_kodu = dfSpecific['URUNKODU'].iloc[0].split("-")[0] how can i fix it ? -
Django-Python:The user image is not displayed on the user page when logged in with user details
When a user logs in, I want to see their profile picture if they have one; if not, the default profile picture should be displayed. Here is my view.py def header(request): if request.session.has_key('id'): user_id = request.session['id'] user = registertb.objects.get(id=user_id) return render(request, 'headerfooter.html', {'user_image': user}) else: return render(request, 'headerfooter.html')` ``` HTML CODE ``` <li> <p style="width:30px; height:30px; margin-left: 200px; margin-top: 10px;color: black;">{{ i.User_name }}</p> {% if user.user_image %} <img src="{{ i.user_image.url }}" style="height: 50px; width: 50px;" alt="Default Image"> {% else %} <img src="/media/image/New folder/default-avatar-profile.jpg" style="height: 50px; width: 50px;" alt="Default Image"> {% endif %} </li>` ``` models.py ``` class registertb(models.Model): User_name=models.CharField(max_length=300) User_email=models.CharField(max_length=300) user_image=models.ImageField(upload_to='image/') password=models.CharField(max_length=400) conf_password=models.CharField(max_length=300) ` ```