Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) ` ``` -
Websocket not receiving messages from Django Channels server websocket
I'm currently working on a project using Django Channels for WebSocket communication. However, I'm facing an issue where the WebSocket connection is established successfully, but messages are not being received on the client side. WebSocket connection is established without errors. I've verified that the Django Channels server is sending messages. However, the client-side WebSocket does not seem to receive any messages. my asgi.py is import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator import transposys_main.routing import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'transposys_main.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( URLRouter( transposys_main.routing.websocket_urlpatterns ) ), }) my consumer.py is import json from channels.generic.websocket import AsyncWebsocketConsumer import logging logger = logging.getLogger(_name_) logger.setLevel(logging.DEBUG) class DepartmentCreatedConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info(f"WebSocket connected: {self.channel_name}") await self.accept() async def disconnect(self, close_code): logger.info(f"WebSocket disconnected: {self.channel_name}") async def receive(self, text_data): logger.info(f"WebSocket message received: {text_data}") try: text_data_json = json.loads(text_data) message_type = text_data_json.get('type') message = text_data_json.get('message') if message_type == 'department.created': logger.info(f"New Department: {message}") except json.JSONDecodeError as e: logger.error(f"Error decoding JSON: {e}") async def department_created(self, event): try: logger.info(f"Department created event received: {event['message']}") await self.send(text_data=json.dumps({ 'type': 'department.created', 'message': event['message'], })) except Exception as e: logger.error(f"Error sending WebSocket message: {e}") routing is from django.urls import re_path from … -
Error While Deploying a Django App on Railway.app
#10 33.61 return hook(config_settings) #10 33.61 ^^^^^^^^^^^^^^^^^^^^^ #10 33.61 File "/tmp/pip-build-env-rwy43j7i/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 355, in get_requires_for_build_wheel #10 33.61 return self._get_build_requires(config_settings, requirements=['wheel']) #10 33.61 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #10 33.61 File "/tmp/pip-build-env-rwy43j7i/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 325, in _get_build_requires #10 33.61 self.run_setup() #10 33.61 File "/tmp/pip-build-env-rwy43j7i/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 507, in run_setup #10 33.61 super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script) #10 33.61 File "/tmp/pip-build-env-rwy43j7i/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 341, in run_setup #10 33.61 exec(code, locals()) #10 33.61 File "", line 7, in #10 33.61 File "/root/.nix-profile/lib/python3.11/tkinter/init.py", line 38, in #10 33.61 import _tkinter # If this fails your Python may not be configured for Tk #10 33.61 ^^^^^^^^^^^^^^^ #10 33.61 ModuleNotFoundError: No module named '_tkinter' #10 33.61 [end of output] #10 33.61 #10 33.61 note: This error originates from a subprocess, and is likely not a problem with pip. #10 33.61 error: subprocess-exited-with-error #10 33.61 #10 33.61 × Getting requirements to build wheel did not run successfully. #10 33.61 │ exit code: 1 #10 33.61 ╰─> See above for output. #10 33.61 #10 33.61 note: This error originates from a subprocess, and is likely not a problem with pip. #10 33.63 #10 33.63 [notice] A new release of pip is available: 23.1.2 -> 23.3.1 #10 33.63 [notice] To update, run: pip install --upgrade pip #10 ERROR: process … -
Creating a table to display rows from a database
I'm trying to create a table that will display the rows of a database called patients and I have created this using Django as the back-end and react as the Front-End. When I try to implement the code I have created thus far the only thing I'm seeing on the webpage is my table header. It should be noted that I have checked sqlite studio and there is data stored in the table. I've checked on PostMan and my Get, POST,PUT, and DELETE methods are all working fine and do what I intend them to do. I'm using Firefox as my browser and I've checked the network tab under inspection, but nothing is being sent to the back-end. I will attach my initial attempt at the front-end webpage import React, {Component} from 'react' export class ViewPatients extends Component{ constructor(props){ super(props); this.state = { patient: [], }; } fetchPatients = () => { fetch('http://127.0.0.1:8000/patient') .then(response => response.json()) .then(data=> { this.setState({patient:data}); }) .catch(error => { console.error("Error Fetching Patients") }); }; componentDidMounted(){ this.fetchPatients(); // this.refreshList(); } render(){ const { patient } = this.state; return( <div> <table> <thead> <tr> <th>ssn</th> <th>address</th> <th>age</th> <th>gender</th> <th>race</th> <th> medical history </th> <th>occupation</th> <th>phone number</th> <th>username</th> </tr> </thead> … -
How to update Django url (to include data/param) after POST
I have a search form (place names) on my home page with an auto-complete dropdown on the search input field. When the user presses enter after selecting an item in the search box the form does a post. When the results return I still have the same url (https://mywebsite.com). How do I get the selected search entry (a location name) to appear in the url so users can book mark it for later use? eg https://mywebsite.com/mylocation I have got the GET code working to get the location in the url - just don't know how to update the url to add the location string after the search form post. I am new to Django so really winging it. Have searched but found no discussion on this even in the Django docs. -
Removing user tags in django
I have been using taggit feature in django for hobbies . Each user can add his hobbies in his profile and tags will be created like tennis or watching movies. I have created a cloud to show him the tags that he has already added : <div class="rounded-tag-container"> {% tag_edit person_id=person.id %} </div> this is also html for this cloud: {% for tag in tags %} <span class="rounded-tag"> <a href="#" style="color:blue;"> {{ tag.name }} </a> <span class="close-button" onclick="removeTag(this, '{{ tag.name }}')"> <strong>×</strong></span> </span> {% endfor %} <script> function removeTag(element, tag_name) { element.parentNode.remove(); $.ajax({ type: 'POST', url: '/hobbies/' + person_id + '/', data: { tag_name: tag_name, csrfmiddlewaretoken: csrftoken }, success: function(response) { console.log(response); }, error: function(error) { console.error('Error deleting tag:', error); } }); } also In my hobbies view I defined tag_name: tag_name = request.POST.get('tag_name') if tag_name : try: person.tags.remove( tag_name) messages.success(request, 'Tag deleted successfully') except Tag.DoesNotExist: messages.error(request, 'Tag not found') else: messages.error(request, 'Tag name not provided') when the user clicks on the close button of each tags,it will be removed from the client side and then clicks on submit,it must remove the tag in post request from db, but it does not remove it from database! -
Django webapp creating 2 profiles when a user signs up
I am building a django webapp after creating a view for the signup page, if i go ahead and signup two profiles are created instead of one. i have tried redirecting to different pages but the problem still persists. this is the view i created def signup(request): if request.method == "POST": print("Signup view called") username = request.POST["username"] email = request.POST["email"] password = request.POST["password"] password2 = request.POST["password2"] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, "Email Taken") return redirect("signup") elif User.objects.filter(username=username).exists(): messages.info(request, "Username Taken") return redirect("signup") else: user = User.objects.create_user(username=username, email=email, password=password) user.save() #log user in and redirect to settings page #create Profile object for the new user user_model = User.objects.get(username=username) new_profile = Profile.objects.create(user=user_model) new_profile.save() return redirect("signup") else: messages.info(request, "Password Not Matching") return redirect("signup") else: return render(request, "signup.html") -
Apache error Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state:'
Have been trying to get an apache server running for a project but have hit this roadblock Getting a 403 forbidden error Ive tried tutorials and other stack overflow questions but can't seem to figure it out, apache should have permission to access this all and the paths should be correct. Completely stumped. apache error log: is in build tree = 0 stdlib dir = '/home/unitpi/mysite/venv/lib/python3.11' sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/unitpi/mysite/venv' sys.base_exec_prefix = '/home/unitpi/mysite/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/unitpi/mysite/venv' sys.exec_prefix = '/home/unitpi/mysite/venv' sys.path = [ '/home/unitpi/mysite/venv/lib/python311.zip', '/home/unitpi/mysite/venv/lib/python3.11', '/home/unitpi/mysite/venv/lib/python3.11/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x0000007faa743040 (most recent call first): <no Python frame> [Fri Nov 17 06:52:02.803390 2023] [wsgi:warn] [pid 38411:tid 548320587840] (13)Permission denied: mod_wsgi (pid=38411): Unable to stat Python home /home/unitpi/mysite/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/unitpi/mysite/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 …