Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Error: Forbidden (CSRF cookie not set.) when trying to make a post request to Django view
I am trying to create a (chrome extension + Django) password manager that will read input boxes from forms and on clicking submit it will make a POST request to the Django view with the data which will then get stored on to the postgresql database. (Keep in mind, this is only a personal project.) But on every request, I get the error: Forbidden (CSRF cookie not set.). Even though I see csrftoken cookie under the Applications tab in inspect. I am passing the csrf token along with the request so I can't figure out what the error is. I have tried getting the csrf token from cookies using Cookies.get('csrftoken') and also setting the csrf token cookie after fetching it from Django as well. This is what my view looks like in Django : @ensure_csrf_cookie def add(request): if request.method == "POST": website = request.POST['website'] username = request.POST['username'] password = request.POST['password'] user = request.user encryptedPass = cryptography.crypto(password) credentials = Credentials.objects.create(email=username, password=encryptedPass) if Website.objects.filter(user = user.id).filter(name=website).exists(): website_obj = Website.objects.filter(user = user.id).filter(name=website) # print(website_obj[0].credentials) website_obj[0].credentials.add(credentials) else: website_obj = Website.objects.create(user=user, name=website) website_obj.credentials.add(credentials) if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return JsonResponse({'message':'Credentials Add'}) return redirect('add') return render(request,'add.html') This is the view where I pass the csrf token to … -
Permission Denied and Python Module Issues when Deploying Django with Apache on Ubuntu
I'm encountering difficulties while trying to deploy my Django website using Apache on an Ubuntu server. Here are the details of the problem: Error Messages: Current thread 0x00007e9faacab780 (most recent call first): <no Python frame> [Thu Jun 27 02:58:10.538441 2024] [wsgi:warn] [pid 16762:tid 139224230311808] (13)Permission denied: mod_wsgi (pid=16762): Unable to stat Python home /home/robch/TestSite/django_env. 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/robch/TestSite/django_env' PYTHONPATH = (not set) 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' and when i go to my page i see and error 403: here is some more information about my files: (django_env) robch@django-server:~$ ls -la total 44 drwxr-x--- 6 robch robch 4096 Jun 27 01:44 . drwxr-xr-x 3 root root 4096 Jun 26 21:58 .. -rw------- 1 robch robch 1102 Jun 27 00:08 .bash_history -rw-r--r-- 1 robch robch 220 Jun 26 21:58 .bash_logout -rw-r--r-- 1 robch robch 3771 Jun 26 21:58 .bashrc drwx------ 3 robch robch 4096 Jun 26 23:45 .cache -rw------- 1 robch robch 20 Jun 27 01:44 .lesshst drwxrwxr-x … -
Integrate semgrep into reNgine
reNgine is your go-to web application reconnaissance suite that's designed to simplify and streamline the reconnaissance process for security professionals, penetration testers, and bug bounty hunters. And semgrep is a sast tool. I want to integrate semgrep into reNgine, here is the source code on github of both: https://github.com/semgrep/semgrep https://github.com/yogeshojha/rengine Does anyone have any ideas? I don't have any idea for this problem -
Django models - How to Aggregate Many-to-Many Related Objects into Arrays?
so I started working with Django recently, I'm having a case of many-to-many relationship between Book and Author -as simple example- a book could have multiple authors. class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField('Author', related_name='books') def __str__(self): return self.title class Author(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name My goal is to fetch the data of Book, but the problem is when a book has multiple authors, I get the same book row for each of its authors, the question is can I have a book row with all its authors stored in a list ? instead of a row for each author. Example of data fetching as JSON: [ { "id": 1, "title": "Good Omens", "authors__name": "Neil Gaiman" }, { "id": 1, "title": "Good Omens", "authors__name": "Terry Pratchett" }, { "id": 2, "title": "The Lord of the Rings", "authors__name": "J.R.R. Tolkien" } ] So I want something like this instead: { "id": 1, "title": "Good Omens", "authors__name": ["Neil Gaiman", "Terry Pratchett"] }, While it's easy to implement this via python code, I want a solution using model queries or ORM methods, to gain some performance and time since the data will be so big. The following code shows … -
How do I create an 'Update Profile Picture' function in django
Okay, so basically I created a function in django where you can change the profile picture but the issue is that It's doing something else instead. Have a look below to understand what's happening I have added these codes into my settings.py file settings.py STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') and also added these to the urls.py urls.py from django.contrib import admin from django.urls import path , include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('user/',include('members.urls')), path('',include('blogposts.urls')), # MAIN URL ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) This is the model that I created for the User models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE, null = True , blank = True ) bio = models.TextField() profile_pic = models.ImageField(upload_to = 'images',default= '/../media/images/image.png') def __str__(self): return str(self.user) This is the form that I created to change the Profile Pic forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['profile_pic'] This is the urls.py inside the app urls.py (app) from django.urls import path , include from . import views urlpatterns = [ path('',views.homepage,name = 'home-page'), path('view_post/<int:pk>',views.view_post,name='view-post'), path('blogcreation',views.create_blog,name='blog-form'), path('aboutme',views.about_user,name = 'show-user'), # this is the one that takes to the page … -
How to Properly Transform Backend Datafrom Django to Frontend Models in Angular
I am a beginner working on an Angular frontend with a Django backend. I have tried to formulate my question as precisely as possible. Please avoid downvoting; if anything is unclear, feel free to ask for clarification, and I will gladly provide more details. I have three models: Task, Subtask, and User. A Task can have multiple Subtasks. A Subtask belongs to exactly one Task. A Task can be handled by multiple Users. I receive the data tasks, subtasks, and users from the backend. A Subtask can only be created after the corresponding Task is created, as a Subtask must always have a taskId. Here are the most important data models: Backend: // Users { "id": 1, "email": "bob@bob.com", "name": "bob" } // Tasks { "id": 1, "title": "Task 1", "description": "Task 1", "due_to": "2024-06-26T13:18:08Z", "created": "2024-06-26T13:18:36.238944Z", "updated": "2024-06-26T13:18:36.239951Z", "priority": "LOW", "category": "TECHNICAL_TASK", "status": "TO_DO", "subtasks": [1], "users": [1] } // Subtasks { "id": 1, "task_id": 1, "description": "Subtask 1", "is_done": false } Frontend: In the frontend, I have a Task data structure which includes Subtasks and Users. export interface Task { id: number, title: string, description: string, dueTo: Date, created: Date, updated: Date, priority: Priority, category: Category, subtasks: Subtask[], … -
"manage.py runserver" now does not run with "py", only "python" overnight
Beginning with web development, using VSCode, Python 3.12.3 in a virtual environment, and Django 5.0.6. When running: py manage.py runserver I get: Unable to create process using 'c:\Users\MyUserName\Documents\GitHub\Coding Practice\Python\DjangoLearningMongo\.venv\Scripts\python.exe manage.py runserver' Another post suggested using just manage.py runserver, but that yields: Unable to create process using 'c:\Users\MyUserName\Documents\GitHub\Coding Practice\Python\DjangoLearningMongo\.venv\Scripts\python.exe "C:\Users\MyUserName\Documents\GitHub\Coding Practice\Python\DjangoLearningMongo\grocery_prices_mongo\manage.py" runserver' I have used py manage.py runserver for the entirety of the project just fine until this morning. Now, py fails to work with anything, yielding the above, and instead I must use python. These are the changes I made to the project yesterday: added static files to the project (static folder, settings.py to have STATIC_ROOT, py manage.py collectstatic, etc...) pip installed whitenoise to handle static CSS in production set DEBUG to FALSE Added 127.0.0.1 to ALLOWED_HOSTS I was still able to use py manage.py runserver (or other py manage.py commands) each step of the way as I made these changes, it was only this morning when I returned to the project that py stopped working and had to use python instead, which I had not needed to do at any point prior in the project. I even went to another project I have not run or edited in a … -
Django - Middleware losing connection with database on multi-tenant app
On my Django app I use a multi-tenant approach with isolated databases. It works well but because it relies on subdomains for each tenant, which is not scalable, I'm trying to change that. To achieve this functionality I'm trying to use middlewares and sessions to retrieve the tenant from the username and use it to set a local variable for the database routers. The logic is this: If the user is not logged, the BeforeLoginMiddleware activates and retrieves the tenant name from the user. So username@tenant1 will set tenant1 to the session. Here's the code: import threading from users.forms import LoginForm Thread_Local = threading.local() class BeforeLoginMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path == '/login/': form = LoginForm(request.POST) if form.is_valid(): complete_username = form.cleaned_data.get('username') current_db = complete_username.split('@')[1] request.session['current_db'] = current_db request.session.modified = True response = self.get_response(request) return response If the user is already logged, a second middleware will retrieve the tenant data from the session and use it to define the Thread_Local variable that is called on a function used on the database routers: class AppMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): current_db = request.session.get('current_db') setattr(Thread_Local, 'current_db', current_db) response = self.get_response(request) return response def … -
Tox+Django can't find package after Django upgrade
I recently upgraded my Django dependency to 4.2, and now running tests via Tox fails with: ModuleNotFoundError: No module named 'mypackage' I haven't changed anything else and running Tox for Django 3.2 works fine. My tox.ini looks like: [tox] envlist = py{38}-django{32,42} recreate = True [testenv] basepython = py38: python3.8 deps = -r{toxinidir}/requirements.txt -r{toxinidir}/requirements-test.txt django32: Django>=3.2,<3.3 django42: Django>=4.2,<5.0 -e . # Install the current package in editable mode commands = django-admin.py test --traceback --settings=mypackage.tests.settings mypackage.tests.tests.TestCase and my project structure looks like: myproject/ ├── myproject/ │ ├── __init__.py │ ├── tests/ │ │ ├── __init__.py │ │ ├── settings.py │ │ └── tests.py │ └── ... ├── .tox/ ├── .env/ ├── .git/ ├── setup.py ├── requirements.txt ├── requirements-test.txt ├── tox.ini └── ... and my test settings look like: import os PROJECT_DIR = os.path.dirname(__file__) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } ROOT_URLCONF = 'mypackage.tests.urls' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'mypackage', 'mypackage.tests', 'admin_steroids', ] MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') USE_TZ = True TIME_ZONE = 'America/New_York' USE_DEPRECATED_PYTZ = True AUTH_USER_MODEL = 'auth.User' SECRET_KEY = 'abc123' SITE_ID = 1 BASE_SECURE_URL = 'https://localhost' BASE_URL = 'http://localhost' MIDDLEWARE_CLASSES = MIDDLEWARE = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', ) TEMPLATES … -
Django Ninja Unit test an end point with File Upload
I have a simple django model: class Invoices(TKSModel): invoice = models.FileField(upload_to="invoices/", null=False, blank=False, validators=[document_file_validator]) institution = models.CharField(max_length=64, null=False, blank=False) invoice_date = models.DateField(null=False, blank=False) description = models.TextField(null=True, blank=True) Then I created an endpoint using django ninja: @router.post('/add', response={201: InvoiceShema}, tags=["Invoice"]) def add_invoice(request, invoice: InvoiceAddShema): instance = Invoices.objects.create( created_by=request.auth, **invoice.dict(), ) return 201, instance Not: the InvoiceAddShema is: class InvoiceAddShema(Schema): invoice_file: UploadedFile institution: str invoice_date: date description: Optional[str] = None Last but not least I am trying to test the endpoint using: def test_add(self): fake = Faker() file_stream = BytesIO() c = canvas.Canvas(file_stream) c.drawString(100, 750, "Invoice") c.save() file_stream.seek(0) file_stream.name = "invoice.pdf" # uploaded_pdf = SimpleUploadedFile("invoice.pdf", file_stream.read(), content_type="application/pdf") # <- You see I event tried this... data = { "institution": "".join(choices(ascii_letters, k=20)), "invoice_date": str(fake.date_between(start_date='today', end_date='+30y')), "description": "".join(choices(ascii_letters, k=120)), "invoice_file": open(r"C:\Users\mshem\PycharmProjects\tks\media\consume\coloombia.pdf", "rb") } self.superuser_header["Content-Type"] = "multipart/form-data" respond = self.client.post( f"{self.url}/add", **self.superuser_header, data=data ) But I get: TypeError: Object of type BufferedReader is not JSON serializable I remember and I see in my older projects I did it this way. But now the data is not serializable. -
I can't figure out what the error is, when applying migration on the django server, I'm trying to connect a PostgreSQL database
the error looks like this, Unable to connect to PostgreSQL: Traceback (most recent call last):your text File "manage.py", line 22, in main()your text File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_line utility.execute() File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\core\management_init_.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\core\management\commands\migrate.py", line 117, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\db\migrations\loader.py", line 58, in init self.build_graph() File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\db\backends\base\base.py", line 330, in cursor return self._cursor() File "C:\python\SkillFactory\Sprint\env\lib\site-packages\django\db\backends\dummy\base.py", line 20, in complain raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. the settings file with a fragment of the database settings looks like this load_dotenv() print("Database Name:", os.getenv('FSTR_DB_NAME')) print("Database User:", os.getenv('FSTR_DB_USER')) print("Database Password:", os.getenv('FSTR_DB_PASSWORD')) print("Database Host:", os.getenv('FSTR_DB_HOST')) print("Database Port:", os.getenv('FSTR_DB_PORT')) BASE_DIR = Path(file).resolve().parent.parent # Настройки … -
Django is too slow when processing exception
The view where the exception happens is processing a big dictionary with about ~350K entries. The exception is a KeyError. From what I can see from the CProfile logs, Django is trying to iterate the dictionary to get traceback data. This is simplified code from the view: @login_required def export_plan_data(request): try: form = PortfolioPlanningForm(request.GET, user=request.user) file = get_export_file(user=request.user, form.get_params()) # This is where the exception happens filename = f"Plan {timezone.now().strftime('%Y-%m-%d %H:%M:%S')}.xlsx" response = HttpResponse(file, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response["Content-Disposition"] = f"attachment; filename={filename}" return response except Exception as e: return JsonResponse({"error": "An error occurred while exporting the data"}, status=500) If I surround the entire view in a try/except block and return my custom response when an exception occurs it returns in about 10 seconds, but if I remove the try/except block and let Django handle the exception it takes about 5 minutes. Here's the Cprofile dump: 292357310 function calls (260422005 primitive calls) in 247.585 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 247.585 247.585 /usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py:44(inner) 1 0.000 0.000 241.196 241.196 /usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py:54(response_for_exception) 1 0.000 0.000 241.194 241.194 /usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py:140(handle_uncaught_exception) 1 0.000 0.000 241.194 241.194 /usr/local/lib/python3.9/site-packages/django/views/debug.py:50(technical_500_response) 1 0.000 0.000 241.192 241.192 /usr/local/lib/python3.9/site-packages/django/views/debug.py:341(get_traceback_html) 429 0.001 0.000 241.047 0.562 /usr/local/lib/python3.9/site-packages/django/template/defaultfilters.py:916(pprint) 429 0.001 0.000 … -
Why does Django require javascript to be linked in the head instead of the end of the body?
I had to do a few extended templates in django. For simplicity let's call them base.html, blog_base.html, and blog.html. (blog extends blog_base, blog_base extends base). I have a few javascript files in base.html, which worked fine in blog_base.html, but when blog.html was loaded, no GET request was ever sent to retrieve the files. I found that the only location for the tags that worked were in the section of base.html. This is odd to me because not a single other location I put these (even in blog.html) was able to load the static files. Is this a django problem or a javascript? -
Weblate Import initial data via database or rest api
Does anybody have an idea how to import translation units into Weblate? I wanted to add them via the database, but I can't create the id_hash. Using the REST API is too slow for my amount of data. It's for a single import just the initial data. -
Migrating from python 2.7 and Django 1.9 to the latest
What are the best ways to migrate from python2.7 and Django 1.9. The project is hosted in AWS and it uses the s3 for content delivery so a lot of packages for that also exists. Did create an env for python3 and installed the latest version of Django and try to start the project which went from 1 problem to another while solving each. -
ModuleNotFoundError: No module named , for python django
What's the problem ? enter image description here enter image description here It must be correct according to the folder path. It sees the path when completing it automatically, but it gives an error.Whats the problem completely. -
issue with django show image tried many ways to solve
template doest not show images i use <img src="/static/logo_coorg.png" width="60" height="40"> and settings like : BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__)) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = 'static/' by this way one of my django website does not have any issue. but another new django website is really a desparate one with this error. i am trying to fix this since last 24+ hours. help is sought. -
django strange behavior with url with slug and /
I am encountering a strange django behavior that I don't see where it could go wrong. I have the start of an app that returns dynamic pages whose url is created through the slug. Everything works well. With any slug I try it works perfectly and the urls find their path without problem. They all go through the same path. But there is ONLY one slug that does not find the path. The peculiarity of the behavior is that in the browser's url it is the only <a href> that adds the / to the url, even though in the html code it does not have the / in the href. I don't understand when the / is added, since all the pages are generated dynamically and go through the same process. This is the page sended to the browser with all links. The url is made dinamically with the slug of the model of each post. <h2><a href="/posts/first-post"> my post first </a></h2> <h2><a href="/posts/fourth-post"> my 4th post </a></h2> <h2><a href="/posts/ready-for-summer"> Ready for Summer Fun! </a></h2> <h2><a href="/posts/third-post"> my 3th post </a></h2> When you click to each links, everything goes fine and the page with the post is sended. the … -
add unit test in label-studio django project to azure storage
I am trying to add a new unit test to label-studio project I am not able to successfully create the storage upload below - name: stage request: data: container: pytest-azure-images project: '{project_pk}' title: Testing Azure SPI storage (bucket from conftest.py) use_blob_urls: true method: POST url: '{django_live_url}/api/storages/azure_spi' response: save: json: storage_pk: id status_code: 201 since I get last_sync_count: 0 in the results. How is the bucket from "conftest.py" being uploaded? - name: stage request: method: POST url: '{django_live_url}/api/storages/azure_spi/{storage_pk}/sync' response: json: last_sync_count: 0 status_code: 200 Here is my branch and PR if you can help: https://github.com/HumanSignal/label-studio/pull/5926/files -
Django allauth facebook login redirects to signup page
I have problem with logging to my app via Facebook. When I'm passing through facebook login form it redirect me to /accounts/social/signup/#= page in my app. My settings: ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" SOCIALACCOUNT_EMAIL_VERIFICATION = "none" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_CONFIRM_EMAIL_ON_GET = True SOCIALACCOUNT_AUTO_SIGNUP = True ACCOUNT_ADAPTER = "apps.users.adapter.MyAccountAdapter" SOCIALACCOUNT_ADAPTER = "apps.users.adapter.MySocialAccountAdapter" ACCOUNT_UNIQUE_EMAIL = False django-allauth version is 0.41.0 (it's old because it's legacy code) Interestingly, on test environment django-allauth does not redirect me (the same facebook client and secret and the same config) to signup page. What may cause the same configuration to work differently in different environments? I've tried with different config but still problem is the same. I don't want to be redirected to signup page. -
pyinstaller django :modules not found
i have turned my django application into exe file and i cant runserver , because some modules are not found django version 3.2.25 pyinstaller 5.12 at firrst runserver didnt work also so i used --noreload then it showed me another error about rest_framework C:\Users\GAMING\Documents\pythonexe1\project\dist>manage runserver --noreload Performing system checks... Traceback (most recent call last): File "rest_framework\settings.py", line 179, in import_from_string File "django\utils\module_loading.py", line 17, in import_string File "importlib\__init__.py", line 127, in import_module File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework.authentication' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 19, in <module> File "manage.py", line 16, in main File "django\core\management\__init__.py", line 419, in execute_from_command_line File "django\core\management\__init__.py", line 413, in execute File "django\core\management\base.py", line 354, in run_from_argv File "django\core\management\commands\runserver.py", line 61, in execute File "django\core\management\base.py", line 398, in execute File "django\core\management\commands\runserver.py", line 96, in handle File "django\core\management\commands\runserver.py", line 105, in run File "django\core\management\commands\runserver.py", line 118, in inner_run File "django\core\management\base.py", line 423, in check File "django\core\checks\registry.py", line 76, in run_checks File "django\core\checks\urls.py", line 13, in check_url_config File "django\core\checks\urls.py", line 23, in check_resolver File "django\urls\resolvers.py", line 416, … -
How can solve Target SWGI script '/aa/bb/wsgi.py' does not contain WSGI application 'application'?
When I change sqlite3 to postgresql, I receave error, this error I have only then I run apache2, if I start "manage.py runserver 0.0.0.0:8000" its work fine. I tried so many things, but I couldn't find the answer. psycopg2 is installed. Part of error: file "/../...postgresql/base.py", line 25.. import psycopg as Database ModuleNotFoundError: No module namged 'psycopg' file "/../...postgresql/base.py", line 27.. import psycopg2 as Database ModuleNotFoundError: No module namged 'psycopg2' .. .. Traceback (..): file /../../wsgi.py application =get_wsgi_application() .. .. .. .. mod_wsgi (pid-1111): Target SWGI script '/aa/bb/wsgi.py' does not contain WSGI application 'application' remove libraries and renew install, restart apache2, correct wsgi.py, 000-default.conf -
How to determine that the 'QuerySet' object does not have the 'comment' attribute in objects.filter(). Django
I am trying to display comments on the post page Comments Models.py from django.db import models from product.models import Product class Comment(models.Model): comment = models.TextField(name="comment") write = models.ForeignKey('product.Product', on_delete=models.CASCADE, null=True, blank=True, name="write") Product Models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=256, name="name") Product View.py def card(request, slug): product = Product.objects.get(id = slug) get_comments = Comment.objects.filter(write=product).distinct() print(get_comments.comment) context = {'product': product, 'comments': get_comments} return render(request, "product/card.html", context) In get_comments.comment I get the error 'QuerySet' object has no attribute 'comment' -
How to get the each unique data from one column
I have table like this below, ID value 1 test 2 test 3 trouble 4 trouble 5 test 6 ok 5 trouble This value column has three genres test trouble ok Now I want to get the unique array such as ['test','trouble','ok'] (any order is fine) How can I do this? -
Django Email Sending
I have a django project but when i try to use send_email() i get the following error: PS> daphne -p 8000 Server.asgi:application 2024-06-26 11:36:00,313 INFO Starting server at tcp:port=8000:interface=127.0.0.1 2024-06-26 11:36:00,313 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2024-06-26 11:36:00,313 INFO Configuring endpoint tcp:port=8000:interface=127.0.0.1 2024-06-26 11:36:00,314 INFO Listening on TCP address 127.0.0.1:8000 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Internal Server Error: /Http/createUser Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = await get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 253, in _get_response_async response = await wrapped_callback( ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 479, in __call__ ret: _R = await loop.run_in_executor( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ TimeoutError: [WinError 10060] The connected person does not respond within a certain period of time or the established connection could not be established because the connecting host was not responding 2024-06-26 11:37:01,353 ERROR Internal Server Error: /Http/createUser Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = await get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 253, in _get_response_async response = await wrapped_callback( ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python311\Lib\site-packages\asgiref\sync.py", line …