Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I save data from a field of a form which is linked to another form?
I have two model forms. I want to save data from a field in one form and use it to link it to another form. I have provided one to one relationship b/w the two models. It should be such that when I click submit it should get redirected to second form page but at the same time data of first form should be stored if user does not fill the second form in second page and close the browser. How do I effectively solve this problem? -
Is Django AuthenticationForm authenticating with is_valid()?
When I use AuthenticationForm in my login view, I find that when I check form.is_valid(), it returns False if the user creds are incorrect. I thought that is_valid() checks validity based on the form class's validation criteria and not by actually doing a database query. Am I incorrect? For examples here's a simple login view: def login_form(request): if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): email = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=email, password=password) if user is not None: login(request, user) messages.info(request, f"Welcome back {request.user.first_name}.") return redirect('home') else: messages.error(request, "Why is this not returned for invalid creds?") else: messages.error(request, "This is returned for invalid creds.") else: form = AuthenticationForm() return render(request, 'login.html', {'form': form}) form.is_valid() returns False if I enter a proper email and password for a non-existent account. I would think that it would return True, and user would be None when we authenticate(). Is is_valid() authenticating the user credentials? Please provide a reference. -
How to Implement custom validators on multiple fields with different field names in Django == 2.0
Here I am implementing a custom validator on LanguageForm class where the value of slug and mime shouldn't be same. Please help me to defining a function which satisfies the above criteria. forms.py : from django import forms class LanguageForm(forms.Form): name = forms.CharField(max_length=100) lang_code = forms.CharField() slug = forms.SlugField() mime = forms.CharField() created_on = forms.DateTimeField() updated_on = forms.DateTimeField() Python version: 3.8.2 Django version: 2.0 OS: Windows 8.1(32 bit) -
How to authenticate user with JWT and HttpOnly cookies
I'm currently developing a Django-React web app and using django-rest-framework-simplejwt and dj-rest-auth for authentication. At first I was storing JWT in frontend cookies (js-cookie) and sending tokens in the headers to get access for restricted endpoints. Since local client cookies are not HttpOnly and after some research I found out that it was not a safe method to store it on the frontend. So I decided not to store them in the client cookies. It seems like best solution to use HttpOnly cookies, in django settings I declared cookie name as JWT_AUTH_COOKIE = 'myHttpOnlyCookie', so when I make a request from client with username and password to log-in server responses with the cookie that has the access_token. For the login part, I didn't write any code since dj-rest-auth handles it well so I use their standart loginserializer and view.(https://github.com/jazzband/dj-rest-auth/blob/master/dj_rest_auth/serializers.py). Well maybe I should modify it. However the problem is I can't add the token in the header of client requests since I'm not storing the token on the client and it is HttpOnly. Well I really don't know how to authenticate the user if I can't send the token in requests. -
How validate to staff_user to add upto maximum 10 products : Django Restframework
I want only staff_user can add product and can add maximum up to 10 products. How validate to staff_user to add upto maximum 10 products? models.py class Cuboid(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=80) length = models.ForeignKey('FilterLength', on_delete=models.CASCADE) serializers.py class CuboidCreateSerializers(serializers.ModelSerializer): class Meta: model = Cuboid fields = "__all__" views.py class CuboidCreateAPIView(generics.CreateAPIView): model = Cuboid queryset = Cuboid.objects.all() serializer_class = CuboidCreateSerializers permission_classes = [IsStaff] -
Logging configuration for gunicorn
I am having trouble setting logging configuration for gunicorn server. I want in to log WARNING level with DEBUG=FALSE but it keeps logging all get and post requests from stdout. How do i filter stdout to WARNING level. Basically i want the server to log exectly as runserver minus get/post requests. I tried changing all handler and logger levels to WARNING, but it didn't help. My settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s', } }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'console_on_not_debug': { 'level': 'WARNING', 'filters': ['require_debug_false'], 'class': 'logging.StreamHandler', }, 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['console', 'mail_admins', 'console_on_not_debug'], 'level': 'INFO', }, 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, } } My server config: [Unit] Description=gunicorn daemon After=network.target [Service] User=mtn Group=www-data EnvironmentFile=/home/mtn/rhc-mtn/envvar WorkingDirectory=/home/mtn/rhc-mtn/rahco ExecStart=/home/mtn/rhc-mtn/ve/bin/gunicorn \ --log-level=warning \ --capture-output \ --log-file /var/log/gunicorn-errors.log \ --access-logfile - \ --preload \ --workers 3 \ --disable-redirect-access-to-syslog \ --bind unix:/home/mtn/run/erp.sock erp.wsgi:application [Install] WantedBy=multi-user.target -
Morris.js with Django as backend - Get the right data through
Goal I wanna make a chart looking like below, where you on Y got income and on X you got years. Lets say the user in this case joined in 2019 and are yet active here in 2020. The user earned 6.000 as well one time. The chart would then be like: I basically wants the years to be when the user joined till now, and then it should on Y start from 0, and round up with 5000 till the largest number. In this case the user invoices a single invoice on 6.000, so the largest number is here 10.000. If the user made an invoice on 12.000, the largest number should be 15.000 then. How would I achieve this? I got the code as shown here: teplates.html <div id="morris-area-chart" style="height: 340px;"></div> <script> $(function () { "use strict"; Morris.Area({ element: 'morris-area-chart', data: [ {% for obj in invoice %} { period: '{{ obj.created_at|date:"Y" }}', income: 32 }{% if not forloop.last %},{% endif %} {% endfor %} ], lineColors: ['#fb9678', '#01c0c8', '#8698b7'], xkey: 'period', ykeys: ['income'], labels: ['Income'], pointSize: 0, lineWidth: 0, resize: true, fillOpacity: 0.8, behaveLikeLine: true, gridLineColor: 'rgba(255, 255, 255, 0.1)', hideHover: 'auto' }); }); </script> views.py class … -
Django | 2 foreignkey to oneself model shows error | Just one foreignkey to oneself works fine
In a model.py named Station, i have 2 index with fireignkey to the same models.py (station). If i use only one index with this relation, this works ok. But if i have a second index relation to the same models.py(Station) it works bad with error message: Error: station.Station.comunication_point: (fields.E304) Reverse accessor for 'Station.comunication_point' clashes with reverse accessor for 'Station.origin_watertank'. HINT: Add or change a related_name argument to the definition for 'Station.comunication_point' or 'Station.origin_watertank'. station.Station.origin_watertank: (fields.E304) Reverse accessor for 'Station.origin_watertank' clashes with reverse accessor for 'Station.comunication_point'. HINT: Add or change a related_name argument to the definition for 'Station.origin_watertank' or 'Station.comunication_point'. System check identified 2 issues (0 silenced). How can i do 2 foreignkey to oneself model without error? Thanks! 2 index with foreignkey to Station models.py origin_watertank = models.ForeignKey ('self', null=True, on_delete=models.CASCADE, blank=True) comunication_point = models.ForeignKey ('self', null=True, on_delete=models.CASCADE, blank=True) File models.py: class Station(models.Model): timestamp_station = models.DateTimeField ('Fecha edición',null=True, blank=True) code_station = models.CharField('Código',max_length=50,null=True, blank=True) name_station = models.CharField('Nombre',max_length=50,null=True, blank=True) origin_watertank = models.ForeignKey ('self', null=True, on_delete=models.CASCADE, blank=True) comunication_point = models.ForeignKey ('self', null=True, on_delete=models.CASCADE, blank=True) objects = StationManager() class Meta: verbose_name = 'Station' verbose_name_plural = 'Stations' def __str__(self): #return [self.name,self.area,self.codigo] return str(self.id) + '-' + str(self.name_station) -
Unable to import 'plotly.graph_objects' pylint(import-error)
i am trying to create a guage chart using plotly and that is indeed possible using the following code snippet fig = go.Figure(go.Indicator( mode = "gauge+number", value = 270, domain = {'x': [0, 1], 'y': [0, 1]}, title = {'text': "Speed"})) fig.show() well that's not the problem, the problem is that i can't import plotly although it is installed pip install --upgrade plotly Requirement already up-to-date: plotly in c:\users\nader\desktop\guage\env\lib\site-packages (4.9.0) Requirement already satisfied, skipping upgrade: retrying>=1.3.3 in c:\users\nader\desktop\guage\env\lib\site-packages (from plotly) (1.3.3) Requirement already satisfied, skipping upgrade: six in c:\users\nader\desktop\guage\env\lib\site-packages (from plotly) (1.15.0) well the error occurs here import plotly.graph_objects as go the error i get is the following Unable to import 'plotly.graph_objects'pylint(import-error) Any Help is appreciated, Thank You! -
why the elements of the list is not in the same structure?
I have this queryset ranges = AgeRange.objects.all().order_by("id") ranges_list = [{item.id, item.frm_to } for item in ranges] and I got this result: [{1, '1-6'}, {2, '1-18'}, {3, '1-40'}, {'40-60', 4}, {5, '60-100'}] I cannot figure out why the elements of 4th item {'40-60', 4} is reversed. How can ensure that the id comes left? -
How to determine if an axios request has no response data
I am trying to test if the IP address provided by a user is the expected IP, so i send a request to that IP address which is expected to be running the API service, if the IP is correct it return success but if the IP is wrong it returns no response data, in the front-end of the application which is vue.js i want to be able to know what happend and fire an alert to the user, if its successful i'm able to do that but if its not nothing happens, how do i get that error message? this is my code PublisherUrl().get('/api/publish-lv/').then(()=>{ Toast.fire({ icon: 'success', title: 'Publisher Connected Successfully' }) }).catch((error)=>{ console.log(error) Toast.fire({ icon: 'error', title: 'Publisher Device Unreachable' }) }) } -
Django testing Http404 exception causes further NoReverseMatch
I have the following block in my DetaiView def get_object(self): post = get_object_or_404( Post.objects \ .select_related('author') \ .prefetch_related('comments'), \ slug=self.kwargs['post_slug']) if post.status == Post.PUBLIC: return post elif post.author == self.request.user: return post else: raise Http404 This works as expected. But how do I test this? When I tried the following test case. It raises Http404 exception but then causes further exception for NoReverseMatch. test code: def test_private_post_detail_as_anonymous(self): """ Show 404 for anonymous users who visit private post. """ self.client.logout() print(post2.slug) # This works! response = self.client.get( reverse('posts:post-detail', kwargs={'post_slug': self.post2.slug}), follow=True) # Fails here, saying post_slug is ''. Why? self.assertEqual(response.status_code, status_code=404) Here is the full traceback: Traceback (most recent call last): File "myproject\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "myproject\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "myproject\venv\lib\site-packages\django\views\generic\base.py", line 73, in view return self.dispatch(request, *args, **kwargs) File "myproject\venv\lib\site-packages\django\views\generic\base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "myproject\venv\lib\site-packages\django\views\generic\detail.py", line 106, in get self.object = self.get_object() File "myproject\myproject\posts\views.py", line 75, in get_object raise Http404 django.http.response.Http404 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "myproject\myproject\posts\tests\test_views.py", line 263, in test_private_post_detail_as_anonymous response = self.client.get( File "myproject\venv\lib\site-packages\django\test\client.py", line 732, in get response = super().get(path, … -
Django: bootstrap.min.css which is found in the same directory as my custom style.css works, but my style.css does nothing
I changed a lot of things and nothing worked. I dont understand why my bootstrap works, but when I try to style something with my own css, nothing happens. Settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' base.html(head) {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <!-- Bootstrap css --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"/> <!-- custom css file --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> directory -my_app --static ----my_app ------css -------bootstrap.min.css -------style.css --templates ----my_app ------home.html ------new_search.html ----base.html --urls.py --etc. Please keep in mind I followed the django documentation and used urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) inside my urls.py -
Pipenv: Activate virtual environment on new computer after git clone
I copied a repo containing a Python Django project from my old computer to my new one via git clone. I manage my dependecies in the project via pipenv. After successfully cloning my repo I wanted to start working on the new computer and tried to select the relevant python interpreter for my project in VS Code . However, the path was not on the list. So first I tried the command pipenv --venv which gave me the feedback: No virtualenv has been created for this project So I thought I might need to activate the virtual environment first, before being able to select it in VS Studio code. So i ran pipenv shell in the root directory of my project. However this seem to have created a new virtual environment: Creating a virtualenv for this project… Pipfile: C:\path\to\my\cloned\project\Pipfile My questions: 1.) Is this the correct way to activate a pipenv virtualenvironment on a new computer after copying the project via git clone? And if not,... 2.1) Does the way I did it cause any problems, which I should be aware of? 2.2) What would be the correct procedure to activate my virtual enviroment on a new computer? -
Django - How to load js file from admin.py as type="module"?
I need to load a javascript file as type="module" from within the admin.py, but I can't find a way to achieve that in the official documentation. Is there an easy trick to do that ? My code looks like this so far : class ArticleAdmin(admin.ModelAdmin): list_display = ('image_thumbnail', 'title', 'category', 'created_at', 'updated_at', 'action') class Media: css = { 'all': ('css/admin/admin_custom.css',) } js = ('js/admin.js',) And I need the admin.js file to look like this after being loaded : <script src="/static/js/admin.js" type="module"></script> -
How to do token-based authentication to a Django web server via Apache?
I want to use Apache providing HTTPS security in front of a Django web server but the Django server has to support receiving GitLab webhook requests, and the only additional authentication this provides is tokens. https://docs.djangoproject.com/en/3.1/topics/auth/customizing/ seems to explain how to authenticate the token inside Django, but how do I either: Pass the token straight through Apache or better Get Apache authentication to hook Django to check the token. Do I have to make the Apache part of my webhook "page" take no authentication and leave everything up to Django or have I missed another hook similar to the check_password hook described in https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/apache-auth/ ? -
Using order_by in django based on the parameter passed in the url
I am working on a basic ecommerce django website and on my category page I have several options to sort the items. This is my urls.py: path("category/<str:sort>",views.category,name="category"), and this is my views.py: def category(request,sort): context = { 'types' : Category.objects.all(), 'prods': Product.objects.filter().order_by(), 'cartItems':[], } return render(request,"category.html",context) Now my concern is that when a user chooses to sort the products , my field names of product model are quite big for eg. if a user chooses to sort by date then the name in my product model for date is "productaddedtimedate" and passing this in the url would look pretty inappropriate (category/productaddedtimedate). Also if he want to sort by reverse date then passing "-productaddedtimedate" (minus sign) will also not look good . So is there any fix to this like I can grab the parameter from the url and change it in views.py before using it in the context. For example I take parameter "date" in url and in views.py change it to productaddedtimedate then pass it in context. -
Heroku: How to connect django local postgres to heroku postgres database
In my Django/react app, I have deployed it but the problem i'm having is I can't run the deployed app successfully until i run the Django server locally. When i try to login on the deployed app, nothing happens, i.e the credentials seems not to work. I suspect the problem is with the database. In development mode, i'm using local postgresql. I want to switch that to postgresql in heroku . settings.py for the deployed app. import os from datetime import timedelta ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'djoser', 'accounts', 'product', 'clients', ] 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', ] ROOT_URLCONF = 'crm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', ], }, }, ] WSGI_APPLICATION = 'crm.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { <==== local postgres 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'crm', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost' } } ... -
How can i fix the importing module in python 3?
here I have a django project(videoservices) with tow apps(memberships,courses).in courses\models.py I >can't import a class from memberships\models.py ,here is the error when I makemigrations courses: >ModuleNotFoundError: No module named 'videoservices.memberships' part of the code of courses\models.py: from django.db import models from django.urls import reverse from videoservices.memberships.models import Membership from django.core.validators import MaxLengthValidator class Course(models.Model): slug = models.SlugField() title = models.CharField(max_length=120, validators=[MaxLengthValidator(120)]) description = models.TextField() allowd_memberships = models.ManyToManyField(Membership) def __str__(self): return self.title def get_absolute_url(self): return reverse("courses:detail", kwargs={"slug": self.slug}) @property def lessons(self): return self.lesson_set.all().order_by('position') part of memberships\models.py from django.db import models from django.conf import settings from django.db.models.signals import post_save import stripe stripe.api_key = settings.STRPE_SECRET_KEY # Create your models here. MEMBERSHIP_CHOICES = ( ('Enterprise', 'ent'), ('Professional', 'pro'), ('Free', 'free'), ) class Membership(models.Model): slug = models.SlugField() membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=40) price = models.IntegerField(default=15) stipe_plan_id = models.CharField(max_length=40) def __str__(self): return self.membership_type i added all of my apps into installed apps and also did try from memberships.models import Membership -
Django Rest Framework With Only Function Response
I just want to make a simple API with DRF. The API going to get a "keyword" from URL, and that "keyword" will go to a function. And function response is going to be API response. Simple Example: def returnSomething(word): test_string = "This is a example sentence. " add_string = word test_string += add_string return test_string http://127.0.0.1:8000/api/langdetect/helloworld/ RESULT: { response: This is a example sentence. helloworld } It's all easy. How can I make this? I read the doc but every example is making with Models, serializers etc. I don't have any models. I have only a function and the response data. Thanks. -
In MySQL 8, is there an index I can create to speed up LIKE searches?
I'm using Django 3, Python 3.8 and MySql 8. I have the following Django model in which I create a search based on a partial name ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() ... # Look up coops by a partial name (case insensitive) def find_by_name(self, partial_name): queryset = Coop.objects.filter(name__icontains=partial_name, enabled=True) print(queryset.query) return queryset The code above produces this query ... SELECT `directory_coop`.`id`, `directory_coop`.`name`, `directory_coop`.`enabled`, `directory_coop`.`phone_id`, `directory_coop`.`email_id`, `directory_coop`.`web_site` FROM `directory_coop` WHERE (`directory_coop`.`enabled` = True AND `directory_coop`.`name` LIKE %Credit%) Below is the table that Django migrations produced. Is there any kind of index or other adjustment I can make to speed up these queries -- specifically, the "name LIKE %Credit%" part? CREATE TABLE `directory_coop` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL, `enabled` tinyint(1) NOT NULL, `phone_id` int DEFAULT NULL, `email_id` int DEFAULT NULL, `web_site` longtext COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`), KEY `directory_coop_email_id_c20abcd2` (`email_id`), KEY `directory_coop_phone_id_4c7e2178` (`phone_id`), CONSTRAINT `directory_coop_email_id_c20abcd2_fk_directory_contactmethod_id` FOREIGN KEY (`email_id`) REFERENCES `directory_contactmethod` (`id`), CONSTRAINT `directory_coop_phone_id_4c7e2178_fk_directory_contactmethod_id` FOREIGN KEY (`phone_id`) REFERENCES `directory_contactmethod` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=993 … -
UTF-8 encode error when configuring Sentry Addon to Heroku app
I am trying to configure Sentry addon on Heroku and I get an error Encoding error. Please ensure that all data in the request can be interpreted as UTF-8. I tried both command line and using the dashboard in the browser. I have checked my account settings and don't use any non - English characters. -
Impossible to connect to my postgreSQL Database
I'm using docker and I have started a new project. I have a backend in Django and I want to use a postgreSQL Database. I can't connect to my database with Django or with PGAdmin. This is what I Got when I try to connect to my database (with Django or with PGAdmin) He is a part of my docker-compose file: services: db: image: postgres container_name: db_wishlist restart: always volumes: - ./postgres-data-wishlist:/var/lib/postgresql/data env_file: - env/base/db.env - env/dev/db.env ports: - "5432:5432" networks: wishlist: aliases: - db pgadmin: image: dpage/pgadmin4 container_name: pgadmin depends_on: - db ports: - "5051:80" env_file: - env/base/db.env - env/dev/db.env environment: PGADMIN_DEFAULT_EMAIL: pgadmin4@pgadmin.org PGADMIN_DEFAULT_PASSWORD: root restart: always networks: wishlist: aliases: - pgadmin api: container_name: backend build: context: .. dockerfile: Docker/Dockerfiles/Django command: python manage.py runserver 0.0.0.0:8000 volumes: - ../Django/:/api ports: - "8000:8000" env_file: - env/base/db.env - env/dev/db.env depends_on: - db links: - db:db networks: wishlist: aliases: - api Here is my db.env: POSTGRES_DB=wishlist POSTGRES_USER=maxdal1 POSTGRES_PASSWORD=demo Here is my settings.py in Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'wishlist', 'USER': 'maxdal1', 'PASSWORD': 'demo', 'HOST': 'db', 'PORT': 5432, } } Here is an additional screenshot when I try to connect to my db with PGAdmin: Error with PGAdmin I checked … -
Cannot iterate a queryset in Django
I have this model class AgeRange(models.Model): frm = models.CharField(max_length=20, blank=False) to = models.CharField(max_length=20, blank=False) Now, when I try to fill a dropdown list by values contracted from frm+to fileds. So, I run this queryset: class ReportForm(forms.ModelForm): ranges = AgeRange.objects.all().values() print(ranges) for item in ranges: print(item.frm) It prints ranges as following: <QuerySet [{'id': 2, 'frm': '1', 'to': '18'} ..... so on. Then, I get this error : print(item.frm) AttributeError: 'dict' object has no attribute 'frm' I'm confused why it could not recogniez "frm" when I try to iterate the queryset : for item in ranges: print(item.frm) -
Django form returns 404 Page not found if input type file included
I am using Django==2.1 and Pillow==7.1.2 When I include <input type="file"> in django form and post it, 404 page not found is the error i get. My template consists of this form: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if success %} <p>Success</p> {% endif %} <input type="file" name="file"> <input type="submit"> </form> views.py is: from django.shortcuts import render from myapp.models import Upload def upload(request): if request.method == "POST": myfile = request.FILES.get('file') upload = Upload(myfile=myfile) upload.save() data = { 'success': "Success" } return render(request, 'file.html', data) else: return render(request, 'file.html') urls.py is: from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.upload, name="upload"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py: MEDIA_ROOT = '/my/path/to/media' MEDIA_URL = '/media/' The code works fine on localhost but I get error when I host it on CPanel shared hosting. If I remove the <input type="file"> and try <input type="text"> it works properly. Also my media files are being served properly only the upload is causing issue