Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle cors headers between a django backend and react js frontend
I am running my react js on frontend.domain.com and backend on backend.domain.com. I am trying to fetch the data from backend django api using the backend.domain.com url. But I am getting this error: Access to fetch at 'https://backend.domain.com/login/' from origin 'https://frontend.domain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. What settings should set in my django backend api like in settings.py or any other. Or in the frontend react js ? What changes should I do to access the resources of the django using frontend react js! How to handle that error and what changes should i make in backend to make access the frontend react js -
How to solve => NameError: name '_mysql' is not defined
I started a django project I made some models and migrations with sqlite3 but now want to use mysql and workbench to work with and after all installations when runing python manage.py migrate or python manage.py runserver I have that error, please help... I have properly installed mysql, mysqlclient and workbench and also this is the code on my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'storedb', 'USER': 'root', 'PASSWORD': '2E71Blue.8', 'PORT': 3306, 'HOST': '127.0.0.1', } } this is the traceback of the error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so Expected in: flat namespace in /Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/__init__.py", line 24, in setup … -
I edited css code in my django project and it did not change anyway if I dalete all my css code it is still working
I sited from my django project and it did not change and it remains same as when it has not edited css code. I do not understand why this is happening?? Then I deleted all css files to find out what is happening but I could not figure it out. -
How to get Category from Product? Django
I'm trying to create a search bar where user can choose Category and write product name. So I can display all products in that category where the name of product matches with what he wrote in text input. The problem is in subcategory. So I have Category -> Subcategory -> Product. Is there any way to get Category object from Product model?(I don't have field for category in product model) Here is my models.py file: # models.py class Category(models.Model): name = models.CharField(max_length=100, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='subcategories') name = models.CharField(max_length=200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) top5 = models.BooleanField(default=False, null=True, blank=True) featured = models.BooleanField(default=False, null=True, blank=True) class Meta: verbose_name_plural = 'Subcategories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True, blank=True) subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True, related_name='products') image = models.ImageField(null=True, blank=True, upload_to='products/') price_old = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True) price_new = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True) description = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name # @property # def category(self): # return self.subcategory.category Here as you can see I tried to create a property to get the category, but now I'm struggling to filter … -
Django and React implementation
I'm trying to make django with react run in a single server, but i got a eror: terminal messaege browser error I don't know whats heppeing. this is my setting.py: from pathlib import Path from datetime import timedelta import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-@*5zxov(m66vfs_l)9pxk8ueq5jhq2cns0g^95(az+1l$!vo9%' DEBUG = False ALLOWED_HOSTS = ['127.0.0.1','localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', 'rest_framework', "corsheaders", 'django_password_validators', 'django_password_validators.password_history', "phonenumber_field", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(days=1), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": False, "BLACKLIST_AFTER_ROTATION": False, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "JTI_CLAIM": "jti", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } CORS_ALLOWED_ORIGINS = ['http://127.0.0.1','http://localhost:3000'] CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1','http://localhost:3000'] ROOT_URLCONF = 'backend.urls' BACKEND_DIR = BASE_DIR FRONTEND_DIR = BASE_DIR.parent / 'frontend' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'frontend/build') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' DATABASES = { … -
Can I configure both ElasticSearch and ChromaDB in a single django application?
I have read the documenations https://docs.djangoproject.com/en/4.2/topics/db/multi-db/ but this page https://django-elasticsearch-dsl.readthedocs.io/en/latest/ describes how to use ElasticSearch. That doesn't seem to allow multi db with elastic search. I was also not able to find the settings for ChromaDB. I am trying to build an application that can use LLM via langchain and chroma db, but I have a data source in JSON that I want to store in elastic search. I am hoping to find a solution to use both elastic search for some models and chromadb for other models and potentially mysql for other models. Currently I am thinking two or three instances of Django applications with a shared vue application accessing the REST interfaces corresponding to the models. I would have one instance of django to handle user login and management and SSO for the other(s) -
Function of JavaScriput running on django doesn't work
I am trying to do a assignment that is provided CS50W. According to CS50W website, What I need to fix is only inbox.js file. Though I confirmed inbox.js file, I couldn't find a problem. A thing I want to do I tried to implement "send_email" function. But, the function doesn't work properly. Although accessing API Route "emails" (which is defined views.compose in urls.py) through fetchAPI, "send_email" function didn't work. The errors I got on Chrome are followings: POST http://127.0.0.1:8000/emails 500 (Internal Server Error) send_email @ inbox.js:142 VM297:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON Promise.then (async) send_email @ inbox.js:151 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON Promise.then (async) send_email @ inbox.js:151 This is a result trying following debugging method result {"error": "POST request required."} debugging method I tried Inspect the network response: In Chrome Developer Tools, go to the "Network" tab, perform the action that triggers the fetch request, and look for the corresponding request in the list. Click on the request to view its details, including the response. Check the response content, headers, and status code to identify any issues. The unexpected < character in the response … -
HTML radio button and JAVASCRIPT API
I'm trying to make an API call using the input from the user using HTML radio's. While all the other imput fields are working, the radio field is giving me some trouble. This is the Javascript <script> function get_details() { let passenger_no = document.getElementById('passengers').value; let distance = document.getElementById('distance').value; let active = document.getElementById('activity_id').value; fetch('https://beta4.api.climatiq.io/estimate', { method: 'POST', headers: { 'Authorization': 'Bearer 7SFFXXXXSRJ63T8WZ2NADN0A', 'Content-Type': 'application/x-www-form-urlencoded' }, body: `{\n\t"emission_factor": {\n\t\t"activity_id": ${active},\n\t\t"data_version": "^1"\n\t},\n\t"parameters": {\n\t\t"passengers": ${passenger_no},\n\t\t"distance": ${distance},\n\t\t"distance_unit": "km"\n\t}\n}` }) .then(response => response.json()) .then(data => { console.log(data); }); } </script> And this is the html <h2>Calculate Emissions</h2> <p></p> <div class="inputBox"> <input type="number" id="passengers"> <label>Enter Number of Passengers:</label> </div> <div class="inputBox"> <input type="number" id="distance"> <label>Enter Distancs in km:</label> </div> {%for i in q %} <div class="form-check"> <input class="form-check-input" type="radio" id="activity_id" value="{{i.attributes}}"> <label class="form-check-label" for="inlineRadio1" style="color: whitesmoke;">{{i.name}}</label> </div> {%endfor%} <p></p> <button type="submit" onclick="get_details()" class="btn btn-success">Estimate</button> I'm getting the following error 'Error parsing the request body. Your JSON syntax is invalid: expected value at line 3 column 18' Can someone help me? -
Exception handling in Django/DRF
I want to check for correctness of request.data whenever there would be a POST request to 127.0.0.1:8000/api/v1/events/ Currently, I do have Event model class Event(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=250) price = models.IntegerField(default=0) created_by = models.ForeignKey(User, related_name='created_events', on_delete=models.CASCADE) guests = models.ManyToManyField(User, default=None, blank=True) categories = models.ManyToManyField('Category', default=None) event_type = models.CharField(choices=EventType.choices, max_length=10) created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) start_time = models.DateTimeField(auto_now=True) seats = models.IntegerField(default=0) I want to check if the user is submitted the required fields in the right format. Also, whenever there would be a PATCH request 127.0.0.1:8000/api/v1/events/{pk}. Then, updated_time, event_type should not be in the request.data (meaning that they should not be updated). How can I make sure that everything is correct in the request.data? It can be done by checking request_keys = request.data.keys() actual_keys = self.serializer_class().get_fields().keys() result = [x for x in request_keys if x not in actual_keys] if result: return Response({'error': 'Invalid data'}, status=400) But the problem is that, I do need to check for different fields whenever the request.method is different, like, POST and PATCH, .get_fields() will return just all the fields in serializer. However, for PATCH I should not have updated_time, event_type fields. Also, I need to make sure that all the request.data fields … -
How to translate url in Django?
This is my django-project below to translate from English to French. *I use Django 4.2.1: django-project |-core | |-settings.py | └-urls.py |-my_app1 | |-views.py | └-urls.py |-my_app2 └-locale └-fr └-LC_MESSAGES |-django.po └-django.mo And, this is core/settings.py below: # "core/settings.py" MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('fr', _('French')) ) And, gettext() is used to translate Test to Examen in my_app1/views.py as shown below: # "my_app1/views.py" from django.shortcuts import render from django.utils.translation import gettext as _ def test(request): # ↓ Here ↓ return HttpResponse(_("Test")) And, hello/world/ path for test() is set to urlpatterns in my_app1/urls.py as shown below: # "my_app1/urls.py" from django.urls import path from . import views app_name = "my_app1" urlpatterns = [ # ↓ ↓ Here ↓ ↓ path("hello/world/", views.test, name="test") ] And, my_app1/ path for my_app1 is set to urlpatterns with i18n_patterns() as shown below: # "core/urls.py" from django.urls import path, include from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( # ↓ Here ↓ path("my_app1/", include('my_app1.urls')) ) And, "Anglais", "Français" and "Examen" are set for "English", "French" and "Test" respectively in locale/fr/LC_MESSAGES/django.po as shown … -
DJANGO: combobox doesn't print in textarea
I'm new to Django. I have a combobox and a textarea. I would like to achieve that if I click on an item in the combobox, using a condition (if), I get the printout in the textarea. Very simple. But there is something wrong in my code. Problem: The combobox (independent and not attached to a database) correctly browses items from the list, but the condition doesn't apply. When I click the button, nothing happens. How can I execute the condition correctly and print in the textarea when I select the combobox item? Thank you home.html <form method="post"> {% csrf_token %} {{ combobox }} </form> <form method="post"> {% csrf_token %} {{ textarea }} <button type="submit">submit</button> </form> views.py colours = ["Red", "Blue", "Black", "Orange"] @login_required def home(request): #Combobox if request.method == "POST": combobox = SimpleCombobox(request.POST) if combobox.is_valid(): print(combobox.cleaned_data) return redirect("home") else: combobox = SimpleCombobox() #TextArea if request.method == "POST": textarea = SimpleTextbox(request.POST) if textarea.is_valid(): print(textarea.cleaned_data) return redirect("home") else: textarea = SimpleTextbox() message = "" picked = "" if request.method == 'POST': picked = request.form['colours'] if picked == 'Red': message = "<<< You chose red" elif picked == 'Blue': message = "<<< You chose blue" elif picked == 'Black': message = "<<< … -
djnago project showing source code instead of products
`When i am trying to diplay product via clicking on list instead of showing products it shows source code. This is following view.py which is i wrote but it is not working. but i think this code is perfect even i watch a tutorial and this code is from him but it is inch to inch copied from other guy but it is not working from me.... even im frustrated. View product = Product.objects.filter(title=val) title = Product.objects.filter(category=product[0].category).values('title') return render(request, 'app/category.html', context, locals()) This is url page even this url is just fine i checked all of item . URL path('category_title/<val>', category_title, name="category_title"), html {% block start %} <div class="container my-5"> <div class="row"> <div class="col-sm-3"> <div class="list-group"> {% for val in title %} <a href="{% url 'category_title' val.title %}" class="list-group-item list-group-item-action" aria-current="true">{{val.title}}</a> {% endfor %} </div> </div> <div class="col-sm-9"> <div class="row"> {% for prod in product %} <div class="col text-center mb-4"> <a href="{% url 'product_detail' prod.id %}" class="btn"> <div> <img src="{{prod.product_image.url}}" width="300px" height="200px"> <div class="fw-bold">{{prod.title}}</div> <div class="fw-bold text-danger"> RS. {{prod.discounted_price}}/- <small class="fw-light text-decoration-line-through">{{prod.selling_price}}</small> </div> </div> </a> </div> {% endfor %} </div> </div> </div> </div> {% endblock %}```` -
SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'localhost'. (_ssl.c:997)
Exception Location: /usr/lib/python3.10/ssl.py, line 1342, in do_handshake I am new webi. I get this error when sending email from my django website. I have two domains on the host and am using postfix to send emails i have checked ssl certificates and are working properly. can anyone help please i tried to pip install -upgrade certifi to update the certificates. renewed the certificates with sudo certbot renew --dry-run the site is also active with https -
While testing routes of my django prodject, i got Type error: expected sting or bites like object. How i can fix this error?
The page of the published news on my blog, is available to any user. I use pytest to check if the page is accessible to an anonymous user. Url is formed by using the id of the news, which I pass in the address parameters (as a tuple). In the result I got this Type error. test_pages_availability[news:detail-news] - TypeError: expected string or bytes-like object I had tried to format args to str, puted a coma after arg for tuple format, it didn't helped code of test @pytest.mark.django_db @pytest.mark.parametrize( 'name, args', ( ('news:detail', pytest.lazy_fixture('news')), ('news:home', None), ('users:login', None), ('users:logout', None), ('users:signup', None), ) ) def test_pages_availability(client, name, args): if args is not None: url = reverse(name, args=(news.id,)) else: url = reverse(name) response = client.get(url) assert response.status_code == HTTPStatus.OK ` fixture @pytest.fixture def news(): news = News.objects.create( title='Новость', text='Невероятное событие', date=datetime.today, ) return news class NewsDetail(generic.DetailView): model = News template_name = 'news/detail.html' def get_object(self, queryset=None): obj = get_object_or_404( self.model.objects.prefetch_related('comment_set__author'), pk=self.kwargs['pk'] ) return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_authenticated: context['form'] = CommentForm() return context Traceback: request = <FixtureRequest for <Function test_pages_availability[news:detail-news]>> def fill(request): item = request._pyfuncitem fixturenames = getattr(item, "fixturenames", None) if fixturenames is None: fixturenames = request.fixturenames if hasattr(item, … -
Upgrading Redis on Heroku causing SSL errors in Celery
I've recently upgraded our Heroku Redis from version 5.0 to 7.0.11 and I'm now receiving the following error when running Celery Traceback (most recent call last): File "/app/.heroku/python/bin/celery", line 8, in <module> sys.exit(main()) File "/app/.heroku/python/lib/python3.8/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/app/.heroku/python/lib/python3.8/site-packages/celery/bin/celery.py", line 235, in main return celery(auto_envvar_prefix="CELERY") File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/celery/bin/base.py", line 134, in caller return f(ctx, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/celery/bin/worker.py", line 348, in worker worker = app.Worker( File "/app/.heroku/python/lib/python3.8/site-packages/celery/worker/worker.py", line 98, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/app/.heroku/python/lib/python3.8/site-packages/celery/worker/worker.py", line 119, in setup_instance self._conninfo = self.app.connection_for_read() File "/app/.heroku/python/lib/python3.8/site-packages/celery/app/base.py", line 818, in connection_for_read return self._connection(url or self.conf.broker_read_url, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/celery/app/base.py", line 877, in _connection return self.amqp.Connection( File "/app/.heroku/python/lib/python3.8/site-packages/kombu/connection.py", line 203, in __init__ url_params = parse_url(hostname) File "/app/.heroku/python/lib/python3.8/site-packages/kombu/utils/url.py", line 50, in parse_url query['ssl'][key] = query[key] TypeError: 'str' object does not support item assignment celery.py from celery import Celery app = Celery('endpoints') # namespace='CELERY' means all celery-related configuration keys should have a … -
How can I load SECRET_KEY from .env file in Django?
This is how my settings.py looks like: import os import dotenv dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # UPDATE secret key SECRET_KEY = os.environ['SECRET_KEY'] This is how my .env file looks like: SECRET_KEY="TOPSECRETKEY" When running python manage.py migrate, it returns KeyError: 'SECRET_KEY' -
Template is not saving Image to database
I am developing a website that allows users to upload projects with various details such as name, description, image, and deadline. However, I am facing an issue where, upon clicking the "Save Project" button, i get redirected to the homepage, but the image does not get saved in the database while everything else does. No error message is displayed. The problem may lie in the form and script sections since it has been able to save image, but after making adjustments to the form and adding script code, to make it look nicer, it stopped working. Screenshot of input form: (https://i.stack.imgur.com/ZUVrC.png) Screenshot of homepage after saving a project: (https://i.stack.imgur.com/wrb0o.png) Here is my code: form that was able to save images: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="{{ project_form.project_name.id_for_label }}">Project name:</label> {{ project_form.project_name }} <br> <label for="{{ project_form.project_description.id_for_label }}">Project description:</label> {{ project_form.project_description }} <br> {{ formset.management_form }} {% for form in formset %} <div class="formset-row"> {{ form.id }} {{ form.image }} </div> {% endfor %} <br> <label for="{{ project_form.deadline.id_for_label }}">Deadline:</label> {{ project_form.deadline }} <br> <button type="submit">Save Project</button> </form> In models.py: from django.db import models class Project(models.Model): project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=2000) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True,) deadline = models.DateTimeField(null=True, … -
How to show/hide a django form field based on the stored value while editing?
models.py: cv_choices = ( ('One Time', 'One Time'), ('Renewal', 'Renewal'), ) class Certification(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) certName = models.CharField(_('Certification Name'), max_length=100, null=True) certId = models.CharField(_('Certification ID'), max_length=100, null=True) certUrl = models.URLField(_('Certification URL'), max_length=500, null=True) certStartDate = models.DateField(_('Certification Start Date'), null=True) certEndDate = models.DateField(_('Certification End Date'), null=True, blank=True) certValidity = models.CharField(_('Certification Validity'), max_length=10, choices=cv_choices, default='Renewal', null=True) createdDate = models.DateTimeField(_('Created Date'), auto_now_add=True, editable=False) modifiedDate = models.DateTimeField(_('Modified Date'), auto_now=True, editable=False) def __str__(self): return self.certName forms.py: class CertificationForm(forms.ModelForm): certValidity = forms.ChoiceField(choices=[('One Time', 'One Time'),('Renewal', 'Renewal')]) class Meta: model = empCertification fields = ('user', 'certName', 'certId', 'certUrl', 'certStartDate', 'certEndDate', 'certValidity') def __init__(self, *args, **kwargs): super(empCertificationForm, self).__init__(*args, **kwargs) self.fields['user'].widget.attrs['class'] = 'form-select' self.fields['certName'].widget.attrs['class'] = 'form-control' self.fields['certId'].widget.attrs['class'] = 'form-control' self.fields['certUrl'].widget.attrs['class'] = 'form-control' self.fields['certStartDate'].widget.attrs['class'] = 'form-control' self.fields['certEndDate'].widget.attrs['class'] = 'form-control' self.fields['certValidity'].widget.attrs['class'] = 'form-select' for field in self.fields: self.fields[field].widget.attrs['placeholder'] = 'Provide Details' Edit Template File: <form action="{% url 'certificationEdit' certification.pk %}" method="post" class="form" enctype="multipart/form-data" novalidate> {% csrf_token %} <div class="card-body border-top p-9"> {% if certificaitonForm.errors %} {% for field in certificaitonForm %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{field.name|title}} - {{error|escape}}</strong> </div> {% endfor %} {% endfor %} {% for error in certificaitonForm.non_field_errors %} <div class="alert alert-danger"> <strong>{{error|escape}}</strong> </div> {% endfor %} {% endif %} <div … -
Django: Problem with urlpatterns for a page after login
After login, i can't access the redirect page (home.html). The page is not found, because I misspelled the urlpatterns of the home page. I'm new to Django. In urlpatterns work fine correctly: index page, login page and logout page. But the home page doesn't. I believe the problem is the urlpatterns of the home. The page is located at templates/app1/home.html Project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls')) App/urls.py from django.urls import path, include from . import views from app1.views import index from app1 import views urlpatterns = [ path('', index, name='index'), path('login/', views.sign_in, name='login'), path('logout/', views.sign_out, name='logout'), path('home/', views, name='home'), #ERROR HERE??? ] In views.py I don't have any home related functions. I only have the login/logout functions working correctly. How can I display the home correctly? -
Django models anotate Count always return 1
Hello I have Django model like this: class Order(models.Model): order_id = models.CharField(max_length=100) title = models.TextField(max_length=600) title_2 = models.TextField(max_length=100) attempts = models.ForeignKey('self', blank=True, null=True, on_delete=models.PROTECT) driver = models.ForeignKey(Driver, blank=True, null=True, on_delete=models.SET_NULL) The main flow I have orders attempts=None and I want to Count of all objects which consist pk in attempts by specific instance. And I use smth like that: order = Order.objects.filter(driver_id=pk).annotate(re_exec=Count('attempts')) And It always returned 1 but it isn't correct. How I can correctly Count this objects ? -
Cannot resolve expression type, unknown output_field - Return model instances in Django's Coalesce?
I have an endpoint that will display results from a model. There's going to be a image illustrating each result, and if none of the posts of this category has a media associated, I'll get the writers avatar to display it. I can get the media url value using the .values('media_source') method in the subqueries, but the problem is that the serializer expects a complex model with other fields and properties. I've tried to use the code below to in order to get the instances, but I receive the following error: Cannot resolve expression type, unknown output_field I understand that I'd need to specify a field type (such as CharField, etc) but I can't figure out if there's a type that is actually interpreted as a Django model instance. def get_queryset(self): annotation = Coalesce( Subquery(PostMedia.objects.filter(categories=OuterRef('pk'))), Subquery(UserMedia.objects.filter(posts__categories=OuterRef('pk'))) ) return Categories.objects.filter(is_public=True).annotate(media_source=annotation) -
Can run the django and react js app on same ec2 instace and point them to a domain separately for each?
I have a django app running on http://public ip of ec2:8000 on ec2 and then i have created a nginx server and its sever is like this server listen 80; server_name public ip of ec2; location proxy_pass http://public ip of ec2:8000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; And then i have pointed it to the a domain like server.domain.com in dns by adding a A record pointing to ec2 public ip. Now i have also created the react js and deployed it on same ec2 and started running it using pm2 on http://public ip ec2:3000/. Django:8000 and react js:3000 are running on different ports. "Now how can i point it to another domain like frontend.domain.com in the dns ? As i won't have another public ip for that ec2" which if there i can create another nginx and point it to the domain in dns. I have a django app running on http://public ip of ec2:8000 on ec2 and then i have created a nginx server and its sever is like this server listen 80; server_name public ip of ec2; location proxy_pass http://public ip of ec2:8000/ And then i have pointed it to the a domain like server.domain.com in dns … -
D3.js linechart (v3) shows line and tooltip coordinates but the coordinate text sticks to screen even when moving mouse
I have code written in js d3. I have a functioning line chart and tooltip but the text sticks on the screen when moving the mouse and only large moves of the mouse remove the text. How do I fix it so that only the current coordinates show and when the mouse moves the old coordinates disappear? code: ` ` var foWidth = 300; var anchor = {'w': width/3, 'h': height/3}; var t = 50, k = 15; var tip = {'w': (3/4 * t), 'h': k}; var fix_resize = 200; // Set the color scale, if multi chart lines var color = d3.scale.category10(); var margin = {top: 30, right: 20, bottom: 30, left: 50}, width = 600 - margin.left - margin.right + fix_resize, height = 270 - margin.top - margin.bottom + fix_resize; //var parseDate = d3.time.format("%Y-%m-%d").parse; function getDate(d) { return new Date(d.date); } var minDate = getDate(data[0]), maxDate = getDate(data[data.length-1]); var x = d3.time.scale().domain([minDate, maxDate]).range([0, width]); var y = d3.scale.linear().range([height, 0]); var xAxis = d3.svg.axis().ticks(d3.time.months, 1).tickFormat(d3.time.format("%b %Y")).scale(x) .orient("bottom").ticks(6); var yAxis = d3.svg.axis().scale(y) .orient("left").ticks(6); // def the area under the line var area = d3.svg.area() .interpolate("basis") .x(function(d) { return x(d.date); }) .y1(function(d) { return y(d.target_downside_base); }) .y0(function(d) { return y(0); … -
Django view won't save image uploaded through AJAX using .fetch
I'm having a problem with my tweet image not saving to my model when my tweet form is submitted. The other content of the tweet such as the tweet itself has no problem saving but the image is where the issue lies. I am submitting my form using AJAX, and making the appropriate call to the view to save the tweet content to the Tweet model. When I print the values of request.FILES and request.POST, this is what I get ('test' is what I have inputted for my tweet field for demonstration): <MultiValueDict: {}> <QueryDict: {'tweet': ['test']}> views.py def post_tweet(request): if request.method == "POST": print(request.FILES, request.POST) # Get contents of form tweet = request.POST.get("tweet", "").strip() # This doesn't capture the image passed. image = request.FILES.get("tweet-picture") # Save the tweet to the model new_tweet = Tweet.objects.create(tweet=tweet, user=request.user, image=image) new_tweet.save() return JsonResponse({"message": "Tweet created successfully."}, status=201) else: return JsonResponse({"error": "POST request required."}, status=400) JS code that handles request (Within my DOMContentLoaded Listener) const tweetForm = document.querySelector("#tweet-form"); tweetForm.addEventListener('submit', function(event) { event.preventDefault(); // Stops other event listeners of the same type of being called event.stopImmediatePropagation(); const tweetInput = document.getElementById("post-content"); const tweet = tweetInput.value; let tweetImage = ""; try { const tweetImageElement = document.querySelector("#tweet-picture-preview img"); … -
Django api and react axios post dont work
am trying to make a simple api where a user writes something in a field, presses a button and a new instance is added in the database. To do this I am using react and django rest framework. App.js const [name,setName] = useState('') const handleChange = (e) => { setName(e.target.value) } function handleClick(e) { fetch('127.0.0.1:8000/post/', { method: 'POST', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ name:'a', title:'b' }) }) } return ( <> <form> <input type='text' value={name} onChange={handleChange} /> <button onClick={handleClick}>OK</button> </form> </> ); views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) urls.py from django.urls import path from . import views urlpatterns = [ path('api/',views.home,name='home'), path('post/',views.home2,name='home2'), path('a/',views.home3,name='home3') ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'main', 'corsheaders' ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True But when I press the button I get manifest.json:1 GET http://127.0.0.1:8000/manifest.json 404 (Not Found) and manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. in javascript. In django I get "POST /post/ HTTP/1.1" 200 0 Also I am using npm run build for javascript and manifest.json is in public folder. React is inside django and the structure looks like this: mysite frontend main mysite db.sqlite3 manage.py Also when I …