Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my images disappear in heroku app how can i solve it
I hosted a web app, where a user can post images, but when user posted an image, the image disappear after 30 minutes or 1 hour and I don't what is happening I installed whitenoise correctly. help me solve this problem please. this is my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] this is my models.py class Category(models.Model): name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name class Photo(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False,) description = models.TextField(null=True) def __str__(self): return self.description this is my installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', 'itouch', #allauth 'allauth', 'allauth.account', 'allauth.socialaccount', #providers 'allauth.socialaccount.providers.facebook', 'bootstrap5', ] this my static settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIR = (os.path.join(BASE_DIR, 'static'),) STATICFILES_STORAGE = 'whitenoise.storage.CompressedMenifestStaticFilesStorage' STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'),) STATIC_URL = '/static/' MEDIA_URL ='/images/' STATICFILES_DIR = [ BASE_DIR / 'static' ] MEDIA_ROOT = BASE_DIR / 'static/images' STATIC_ROOT = BASE_DIR / 'staticfiles' this is my templates <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbail" src="{{photo.image.url}}" alt="Card image cap"> -
how to set django setting path in docker container app?
i'm inside docker container. and getting following error: File "./source/asgi.py", line 14, in <module> from notifications.sockets import routing File "./notifications/sockets/routing.py", line 3, in <module> from . import consumers File "./notifications/sockets/consumers.py", line 7, in <module> from projects.models import Project File "./projects/models.py", line 6, in <module> User = get_user_model() File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. where my asgi file code is here below: import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from notifications.sockets import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'source.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns, ) ), }) i don't get it whats wrong here.. please help me out in solving this issue... thank you. -
Problem to use @extend_schema over an @actoin in DRF
hi I have a @extend_schema of drf_spectacular library in my code I need to use it over my @action to customize the detail in OpenAPI, but I get errors like that Internal Server Error: /api/schema/ Traceback (most recent call last): File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/asgiref/sync.py", line 482, in thread_handler raise exc_info[1] File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/django/core/handlers/base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/asgiref/sync.py", line 444, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/lib/python3.9/asyncio/tasks.py", line 442, in wait_for return await fut File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run result = self.fn(*self.args, **self.kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/asgiref/sync.py", line 486, in thread_handler return func(*args, **kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/drf_spectacular/views.py", line 69, in get return self._get_schema_response(request) File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/drf_spectacular/views.py", line 77, in _get_schema_response data=generator.get_schema(request=request, public=self.serve_public), File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/drf_spectacular/generators.py", line 262, in get_schema paths=self.parse(request, public), File "/mnt/62EE2B18EE2AE44F/NEW/django/webserver/django-env/lib/python3.9/site-packages/drf_spectacular/generators.py", line 227, in parse assert isinstance(view.schema, AutoSchema), ( AssertionError: Incompatible AutoSchema … -
background_task are not activated every 30 seconds as requested
I have a background task that should run every 30 seconds. The way I set it up is like this: from background_task import background from datetime import datetime import pytz @background() def notify_users(**kwargs): my_datetime = datetime.now(pytz.timezone('US/Eastern')) print ("at the moment its",my_datetime) and the activation: notify_users(repeat=30, repeat_until=None) The output is this: at the moment its 2022-01-02 15:08:25.571196-05:00 at the moment its 2022-01-02 15:08:55.896407-05:00 at the moment its 2022-01-02 15:09:56.408215-05:00 at the moment its 2022-01-02 15:10:56.871663-05:00 at the moment its 2022-01-02 15:11:57.327631-05:00 at the moment its 2022-01-02 15:12:57.857382-05:00 at the moment its 2022-01-02 15:13:28.135571-05:00 at the moment its 2022-01-02 15:14:28.551105-05:00 Note that its not 30 seconds, only the second round, why? what am I missing here? -
Django sending emails and response to Vue/Axios
I am struggling to send emails from Vue3/Axios frontend through Django. in Vue3 I send my form fields using axios: <script lang="ts"> import axios from 'axios'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; export default { name: "Contact", data() { return { name: '', email: '', phone: '', message: '' }; }, methods: { sendEmail() { axios .post("send_email/", { name: this.name, email: this.email, phone: this.phone, message: this.message, xstfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', headers: { 'X-CSRFToken': 'csrftoken', } }) .then((response) => { console.log(response); }) } } }; </script> I can see my fields in the request header without any problems. I could not manage to write a correct view sending email and response the request. def contactView(request): if (request.POST): try: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] name = form.cleaned_data['name'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] print(subject) try: send_mail(subject, message, from_email, ['admin@example.com']) return HttpResponse(json.dumps({'response': 'Ok'}), content_type = "application/json") except BadHeaderError: return HttpResponse(json.dumps({'response': 'Ko', 'message': 'invalid header found'}), content_type = "application/json") except: return HttpResponse(json.dumps({'response': 'Ko', 'message': 'Cannot be sent'}), content_type = "application/json") else: return HttpResponse(json.dumps({'response': 'Ko', 'message': 'Cannot be sent'}), content_type = "application/json") Can you help me to fix this ? Thanks -
my Procfile to deploy django-heroku isn't wrong but errors keep occured
django-admin startproject minblog python manange.py startapp index and only one template used to test-deploy with Heroku working-tree MINBLOG minblog index minblog setting.py Pipfile requirements.txt git.init //minblog>Progfile web: gunicorn minblog.wsgi --log-file - //minblog>minblog>setting.py import os import django_heroku DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ...] # Activate Django-Heroku. django_heroku.settings(locals()) and install gunicorn in virtual entirment ~/Desktop/minblog $pipenv shell $pip install gunicorn whitenoise django-heroku and i still stuck in this error $ heroku ps:scale web=1 Scaling dynos... ! ! Couldn't find that process type (web). which part did i miss? -
Django Python how to implement my custom birth date function in views?
I write this python function for calculate age. def age(birthdate): today = date.today() age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day)) return age result: >>> print(age(date(1980, 1, 1))) 42 here is my code: models.py class CalculateAge(models.Model): age = models.IntegerField(max_length=100) date_of_birth = models.DateField() user only pick the date of birth and I want age will be automatically calculate when submitting forms. views.py def CalculateAge(request): if request.method == "POST": patient_from = AddPatientFrom(request.POST or None) if patient_from.is_valid(): patient_from.save() how to implement this age function in my views.py and models.py? I tried this in my views.py but didn't work. if patient_from.is_valid(): pick_date = request.POST['date_of_birth'] find_age = age(date(pick_date)) print(find_age) getting this error: TypeError at /add-patient/ an integer is required (got type str) -
Same AJAX call for multiple button on clicks on the same page
I'm working on a project with django. I have multiple buttons on a page that I want to, upon clicking, be able to get the value of without the page refreshing. With the below code, it does want I want except that it will only return the value of the first button on the page regardless of which button I click. Please note that I have 0 experience with JS which is why I'm struggling. I've looked at many, many threads and I can't figure it out. $(document).on('click', '.testing', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "select" %}', data: { value: $('.testing').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), // action: 'post', success : function(json) { console.log("success"); // another sanity check console.log($('.testing').val()) }, }})}) {% extends "recipe_site/base.html" %} {% load static %} {% block content %} {% block extrascripts %} <script type="text/javascript" src="{% static 'ingredients/ingredients.js' %}"></script> {% endblock extrascripts %} {% for ingredient in ingredients %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <h2>{{ ingredient.group }}</h2> </div> <button id="{{ ingredient.pk }}" class="testing" value="{{ ingredient.food_name }}">{{ ingredient.food_name }}</button> </div> </article> {% endfor %} -
How to configure django-channels to make docker container?
I have a django app which works with django channels. Now the problem is everything was working fine without docker containerizing thing. Now I have made the docker container of the app but sockets are not working.. but django CRUD with apis working fine. or we can say gunicorn service is running but daphne service isn't. In entrypoint.sh : #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn source.wsgi:application --bind 0.0.0.0:8000 daphne source.asgi:application --bind 0.0.0.0:8001 settings.py : CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('redis-notif2', 6379)], }, }, } on browser i'm getting the following error: Firefox can’t establish a connection to the server at ws://xx.xx.xxx.xxx:8001/ws/project/admin/. reconnecting-websocket-mjs.js:516 -
Error deleting AWS S3 objects from Django Web App
I'm having the following error when I try to delete S3 files from my Python/Django Webapp. ClientError at /eq83/deletephoto An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied I have no problem viewing or uploading files. Some details on the bucket permissions All block public access boxes are unchecked. Bucket policy is empty and says No policy to display. Access control List(ACL) has all the boxes checked for bucket owner and the rest are unchecked. This is the Cross-origin resource sharing (CORS) [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "POST", "PUT", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Some details on my application Below is an excerpt from my settings.py file. I have blocked out the secret key and omitted TEMPLATES, MIDDLEWARE, and some INSTALLED_APPS import os import dotenv dotenv.read_dotenv() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXX' DEBUG = True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'tracker.apps.TrackerConfig', ... 'storages' ] WSGI_APPLICATION = 'tracker_django.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'tracker', 'static')] DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY', '') AWS_SECRET_ACCESS_KEY … -
Show all record in Django
I have SQL Server database and I have a table, I've created a stored procedure to retrieve all records from the table and tested it. The stored procedure works properly. However, when I called it in my Django program and tried to write all records on an html page, but it shows the last record only. Here is the loginsdata.html {% block content %} {% for row in rows %} <p> <h3>Name: {{row.name}}</h3> <h3>Email: {{row.email}}</h3> <h3>Username: {{row.userName}}</h3> <h3>Password: {{row.password}}</h3> </p> </br> {% endfor %} {% endblock content %} And here is the views.py from django.shortcuts import render from django.http import HttpResponse from django.db import connection import pyodbc def readLogin(request): command = 'EXEC GetLogin \'\'' cursor = connection.cursor() cursor.execute(command) strHtml = '' while True: row = cursor.fetchone() if not row: break userName = row[0] password = row[1] name = row[2] email = row[3] rows = [] rows.append({'userName': userName, 'password': password, 'name': name, 'email': email}) cursor.close() return render(request, 'login/loginsdata.html', {'rows': rows}) -
Djago how to prevent to accept future date?
I added this validation in my froms.py for prevent to accept future date. But I am not undersating why it's not working and forms still now submitting with future date. here is my code: import datetime class AddPatientFrom(forms.ModelForm): date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control','type':'date'}),required=True) class Meta: model = Patient fields = ['date_of_birth'] def clean_date(self): date = self.cleaned_data['date_of_birth'] if date < datetime.date.today(): raise forms.ValidationError("The date cannot be in the past!") return date I also want to know how to disable to pick future date from Django default html calendar? -
Model def recepiestatus get error in django shell
im trying to solve a problem related to this eror message i get when i call a function in Django shell. The error i get in Django shell is TypeError: can't compare datetime.datetime to datetime.date. But when i look at the code variables status and created are date objects still in django shell its interperted as a datetime filed. In [91]: print(one.recepie_status()) ------------------------------------------------------ --------------------- TypeError Traceback (most recent call last) <ipython-input-91-47aeca6a3105> in <module> ----> 1 print(one.recepie_status()) E:\Projekt\Fooders\fooders\recepies\models.py in recepie_status(self) 18 status=(date.today()-timedelta(days=15)) 19 created = datetime.date(self.created_at) ---> 20 if created > status: 21 return "New" 22 else: TypeError: can't compare datetime.datetime to datetime.date -
Django + mongodb generates float ids for the users model
I have a Django project integrated with MongoDB through Djongo, I have all mongo related packages updated at the latest release. The issue is Django spits back the id as a float for the user object in different places as I'm highlighting in the following pictures: The issue in the first image occurs when I try to click on any user object from the user's table in the Django admin dashboard. If I try to type the link manually without the ".0" part of it. it opens the page to edit the user object no problem. Here I show how each object link looks like, there's a weird ".0" attached to each id in the link... This issue is generating some problems at other places such as when I try to login this occurs: ['“582.0” value must be an integer.'] I believe all of these issues are caused by the same problem. which is what I'm still not sure about... My users model schema: { "_id" : ObjectId("618d3b0766fa111338fd379e"), "name" : "lab_customuser", "auto" : { "field_names" : [ "id" ], "seq" : 589 }, "fields" : { "date_joined" : { "type_code" : "date" }, "email" : { "type_code" : "string" }, … -
REST API return child
I am a learning student and I am trying to return a piece of data with REST API. However, I just can't get it the way I want it. Below you can see a part of what is happening now. "receipt": { "id": 1, "name": "First item", }, { "id": 2, "name": "Second item", }, But I want it like the code down below, without the "receipt": { first. { "id": 1, "name": "First item", }, { "id": 2, "name": "Second item", }, I can't really figure out how to do it.. I spend 2 days of my life trying to get this. Below you will see my View and Serializer. class FavoritesSerializer(serializers.ModelSerializer): class Meta: model = Favorite fields = ['receipt'] depth = 2 class FavoritesViewSet(viewsets.ModelViewSet): queryset = Favorite.objects.all() serializer_class = FavoritesSerializer def getUser(self): queryset = Favorite.objects.filter(user=self.request.user) serializer = FavoritesSerializer(queryset, many=True) return Response(serializer.data) If someone can help me, I will really appreciate it. -
Django How to create form with one field for images or documents
I need to add a form that has a field that will allow users to upload either documents (.pdf, etc) or images (.png, .jpeg, etc). I know Django has the model fields FileField and ImageField. How would I create a form that detects the type of upload and uses the correct field type? -
Running standalone Django runserver
I have set up a VPS and installed Django on it. I've installed Django within the virtual environment i created using python3 -m venv env and activated via source env/bin/activate. In order to run the Django built-in webserver i need to run python3 manage.py runserver. The webserver runs until i close the SSH session, so how can i run a standalone webserver without being dependent on the SSH session. (Running inside the virtual environment)? -
I can't change Django admin login URL
I will change django login panel URL. I change admin url in urls.py file. URL changed but i can't login. general urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('testadminlogin/', admin.site.urls), ] in settings.py: ... LOGIN_URL = '/testadminlogin/' LOGIN_REDIRECT_URL ='/testadminlogin/' ... I will login by this URL: "mysite.com/testadminlogin/" -
Deployment Failed with Error: Package deployment using ZIP Deploy failed
I am trying to deploy a django project in azure from GitHub repository but I am getting error during the deployment. I am getting this error: Failed to deploy web package to App Service. 2022-01-02T15:32:52.2053869Z ##[error]Deployment Failed with Error: Package deployment using ZIP Deploy failed. Refer logs for more details. How can I resolve it? 2022-01-02T15:07:42.4101966Z with: 2022-01-02T15:07:42.4102399Z app-name: stockprojection 2022-01-02T15:07:42.4102889Z slot-name: Production 2022-01-02T15:07:42.4115035Z publish-profile: *** 2022-01-02T15:07:42.4115476Z package: . 2022-01-02T15:07:42.4116058Z ##[endgroup] 2022-01-02T15:07:43.9633760Z Package deployment using ZIP Deploy initiated. 2022-01-02T15:32:51.1581899Z Updating submodules. 2022-01-02T15:32:51.1583435Z Preparing deployment for commit id 'f47d703f2a'. 2022-01-02T15:32:51.1584587Z Repository path is /tmp/zipdeploy/extracted 2022-01-02T15:32:51.1585520Z Running oryx build... 2022-01-02T15:32:52.1954843Z Command: oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform python --platform-version 3.9 -i /tmp/8d9ce01a48e2911 --compress-destination-dir -p virtualenv_name=antenv --log-file /tmp/build-debug.log 2022-01-02T15:32:52.1957351Z Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx 2022-01-02T15:32:52.1958337Z You can report issues at https://github.com/Microsoft/Oryx/issues 2022-01-02T15:32:52.1992563Z 2022-01-02T15:32:52.1993572Z Oryx Version: 0.2.20210826.1, Commit: f8651349d0c78259bb199593b526450568c2f94a, ReleaseTagName: 20210826.1 2022-01-02T15:32:52.1994721Z 2022-01-02T15:32:52.1995241Z Build Operation ID: |da22zDrMO/Q=.cac2beba_ 2022-01-02T15:32:52.1996043Z Repository Commit : f47d703f2a594452a83ae4301b5d6ce8 2022-01-02T15:32:52.1996497Z 2022-01-02T15:32:52.1997051Z Detecting platforms... 2022-01-02T15:32:52.1997609Z Detected following platforms: 2022-01-02T15:32:52.1998100Z python: 3.9.7 2022-01-02T15:32:52.1999279Z Version '3.9.7' of platform 'python' is not installed. Generating script to install it... 2022-01-02T15:32:52.1999807Z 2022-01-02T15:32:52.2000549Z Using intermediate directory '/tmp/8d9ce01a48e2911'. 2022-01-02T15:32:52.2001012Z 2022-01-02T15:32:52.2001533Z Copying files to the intermediate directory... 2022-01-02T15:32:52.2002087Z Done in 0 sec(s). 2022-01-02T15:32:52.2002345Z 2022-01-02T15:32:52.2002782Z Source directory : /tmp/8d9ce01a48e2911 2022-01-02T15:32:52.2003367Z … -
Django - Get highest value from each user
I have this models: Models: class User(models.Model): name = models.CharField(max_length=255, null=True, blank=True, verbose_name='Name') class Grad(models.Model): grad = models.CharField(max_length=255, null=True, blank=True, verbose_name='Grad') order = models.PositiveIntegerField(max_length=255, null=True, blank=True, verbose_name='Order') class Number(models.Model): user = models.ForeignKey(User, null=True, blank=True, verbose_name='User', on_delete=models.CASCADE) grad = models.ForeignKey(Grad, null=True, blank=True, verbose_name='Grad', on_delete=models.CASCADE) View: user_numbers = Number.objects.all() Get example: But i want only get the highest order grad value to each user: Thank you in advance! -
Django Rest Framework give me validation error that shouldn't be raised when using Unit Tests
I am creating this API and in determined point of my tests (contract creation endpoint) I am receiving an invalid error. The error says that I am not passing some required attribute to the API when creating a contract, but I am. The weirdest thing is that when I tried to create from the Web browser by hand, the issue wasn't raised and the contract was created I am puting here a lot of codes just for replication purposes, but the code that is really important to see it is the ContractSerializer and the test_contract_creation function Here is my code: models.py from django.core.exceptions import ValidationError from django.db import models from django.core.validators import ( MaxValueValidator, MinValueValidator, RegexValidator, ) from core.validators import GreaterThanValidator, luhn_validator class Planet(models.Model): name = models.CharField( max_length=50, unique=True, null=False, blank=False ) def __str__(self) -> str: return self.name class Route(models.Model): origin_planet = models.ForeignKey( Planet, on_delete=models.CASCADE, related_name="origin", ) destination_planet = models.ForeignKey( Planet, on_delete=models.CASCADE, related_name="destination", ) fuel_cost = models.IntegerField(validators=[GreaterThanValidator(0)]) class Meta: unique_together = (("origin_planet", "destination_planet"),) def clean(self) -> None: # super().full_clean() if self.origin_planet == self.destination_planet: raise ValidationError( "Origin and destination planets must be different." ) def save(self, *args, **kwargs): self.full_clean() super().save(*args, **kwargs) def __str__(self) -> str: return f"{self.origin_planet} - {self.destination_planet}" class Ship(models.Model): … -
Managing django secrets
I am creating a Django web application that will be hosted in AWS. I'm developing on my laptop (Mac) and using docker compose to run a postgres database in AWS as well. Accordingly, sometimes I am using a development database from my Mac in PyCharm, and other times I need to compile and run the docker to test that the functionality works in the container. The challenge I am facing is the management of secrets across all of these locations. It would be ideal to have one "secret vault" which could be accessed at run-time from either within the docker or within PyCharm to keep life simpler. I am familiar with .env files and the manner by which these can be imported, but this also requires me to copy them into the docker container at build time. Is there some "simple yet robust" way to manage this more easily? It feels like having copies of different .env files in different environments presents its own risks. -
SL connection has been closed unexpectedly server closed the connection unexpectedly This probably means the server terminated abnormally
i want run python manage.py runserver but got this error !! django.db.utils.OperationalError: connection to server at "172.16.11.139", port 5432 failed: FATAL: password authentication failed for user "some_name" connection to server at "172.16.10.139", port 5432 failed: FATAL: password authentication failed for user "some_name" i use this article for postgres remote connection https://www.bigbinary.com/blog/configure-postgresql-to-allow-remote-connection what i miss?! setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('NAME'), 'USER': os.getenv('USER'), 'PASSWORD': os.getenv('PASSWORD'), 'HOST': os.getenv('HOST'), 'PORT': int(os.getenv('PORT')), } } -
Django manage.py runserver command not working
image I am using Python 3.10 and Django version 4.0. When I try to run manage.py runserver, the terminal doesn't give me localhost address. I tried restarting my pc, but still not working. Please help me. -
Django ModelForm never passes is_valid()
I'm new to Django and I am currently trying to store data entered from a form into a model/database. The bit which I think is causing the issue is that I don't want all the model fields accessible on the form. The model I have has the fields as follows: description = models.TextField() date_referred = models.DateTimeField(default=timezone.now) full_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone_number = models.CharField(max_length=17, blank=True) column_number = models.IntegerField() notes = models.TextField() colour = models.CharField(max_length=6) user = models.ForeignKey(User, on_delete=models.CASCADE) The ModelForm I am using is as follows: class ReferralForm(ModelForm): class Meta: model = kanban_item fields = ["item_name", "description", "full_name", "email", "phone_number"] The code inside of the views.py file is this: def submit_referrals(request): form = ReferralForm() if request.method == "POST": form = ReferralForm() print(request.POST) if form.is_valid(): print("VALID") referral = form.save(commit=False) referral.user = request.user referral.column_number = 0 referral.colour = "ffffff" referral.save() else : print ("NOT VALID") As you can see, I am trying to create a model from the form then add the extra fields and then save the model to the database. This is not working as whenever I submit the form my code never gets past the is_valid method on the form. Any suggestions or answers are appreciated as I …