Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why this class in my views.py not working
class UserLoginView(View): form_class = UserLoginForm template_name = 'accounts/login.html' def get(self,request): form = self.form_class context = {'form':form} return render(request,self.template_name,context) def post(self,request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request,username=cd['username'],password=cd['password']) if user is not None: login(request,user) messages.success(request,'Your login successfully','success') return redirect('home:home') messages.error(request,'username or password is wrong','warning') return render(request,self.template_name,{'form':form}) my pc does not know if form.is_valid -
Doesn't call python print function?
My urls is : from django.contrib.auth.views import LoginView path('login/', LoginView.as_view(),name='login') class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/login.html' redirect_authenticated_user = False extra_context = None @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): print('new dispatch')#Does not call if self.redirect_authenticated_user and self.request.user.is_authenticated: redirect_to = self.get_success_url() if redirect_to == self.request.path: raise ValueError( "Redirection loop for authenticated user detected. Check that " "your LOGIN_REDIRECT_URL doesn't point to a login page." ) return HttpResponseRedirect(redirect_to) return super().dispatch(request, *args, **kwargs) def get_success_url(self): url = self.get_redirect_url() print(url)#Does not call print('ok')#Does not call return url or resolve_url(settings.LOGIN_REDIRECT_URL) Send request to view doesn't print print() methods...? -
User Interface is not working with apache2 for django project but working on local server
I have created a django project that is working fine on the local server(127.0.0.1). I was trying to push the code to amazon aws. The code and the migrations are working but the ui is missing. I'm attaching the screenshot of the working page along with the 000-default.conf. Working page on localhost Page working on apache on aws 000-default.conf file I tried to change the staticfiles path but the result was the same. -
Best practice for validators in Django serializers?
I am currently new to DRF, working on validators for a "Book Edition" serializer. They seem to be working as intended, but as I am looking into documentation it seems most people override the validate() or include them in the Meta class. I am wondering if I am going about this completely wrong now! My main questions are: Is it appropriate to add these validators through the serializers.IntegerField()s? Will both these validators for the ISBN be called when the data is serialized? Here is my code: class EditionSerializer(serializers.ModelSerializer): ISBN = serializers.IntegerField( validators=[ UniqueValidator( queryset=Edition.objects.all(), message="ISBN must be unique." ), ], ) def validate_ISBN(self, value): errors = {} if len(str(value)) != 10 and len(str(value)) != 13: errors[ "digits" ] = "A valid ISBN number must contain either 10 or 13 digits." if errors: raise ValidationError(errors) return value year_published = serializers.IntegerField( validators=[MaxValueValidator(limit_value=timezone.now().year)] ) -
How to Solve Not Compatible Python Libraries on Google Kubernetes Engine?
During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 135, in handle self.handle_request`enter code here`(listener, req, client, addr) File "/env/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 178, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/env/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 130, in get_response response = self._middleware_chain(request) File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 152, in handle_uncaught_exception callback = resolver.resolve_error_handler(500) File "/env/lib/python3.7/site-packages/django/urls/resolvers.py", line 615, in resolve_error_handler callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) File "/env/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/env/lib/python3.7/site-packages/django/urls/resolvers.py", line 595, in urlconf_module return import_module(self.urlconf_name) File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/vmagent/app/mysite/urls.py", line 38, in <module> re_path(r'^rosetta/', include('rosetta.urls')) File "/env/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, … -
Django - confused about naming class and parameters (when to use uppercase / plural form)?
Such confusion reflects unclear understanding about class and framework. I'm learning database in Django models. I get confused about naming class. When to use uppercase / lowercase, when to use singular and plural? I'm following the lecture from freecodecamp with this example: In models.py, I assign a class called Feature(models.Model). Then, in views.py, I assign features for templates: features = def index(request): Features.objects.all() return render (request, "index.html", ({"features": features}) In index.html, there exists a for loop, therefore I run the syntax for feature in features: with the variable {{feature.name}} and {{feature.details}} At this moment I just memorize without understanding when deciding when to use Feature vs feature, features vs feature. I find it rather difficult in memorizing the code views.py. I need a real understanding about naming. Below is the flow of some of the code. Thank you so much for your help. models.py class Feature(models.Model): name = models.CharField(max_length = 100) details = models.CharField(max_length = 500) ------ settings.py python manage.py makemigrations python manage.py migrate python manage.py createsuperuser ---- admin.py from .models import Feature admin.site.register(Feature) ---- views.py def index(req): features = Feature.objects.all() return render(req, "index.html", ({'features': features}) ---- index.html for feature in features: ....{feature.name} ....{feature.details} -
Would like to build a dynamic website on AWS with files in S3 backend
Here is a requirement: We would like to have a dynamic website hosted in AWS through which we will be able to edit/update few text files. More elaborately, I know how to code in Python and Flask and I prefer to use that (or maybe Django) and the files will need to be stored in S3 in some bucket. I had used my own EC2 Server to host a dynamic website. But I never used that to change/edit/update any file etc. in S3. So that part is new to me - I need to figure it out. I thought if there are other approaches I do not know of (and my AWS knowledge is limited). Please suggest some alternatives or rather the best way (best AWS features to use) to solve this. Thank you all AWS experts! Appreciate your help, in advance. -SDN -
Django storages adding “;amp” to staticfiles query string parameter only for Django-jet files resulting in unauthorized access
Some staticfiles links have wrong params, what i noticed that they are only related to "django-jet" package. Normal Django staticfiles URL: https://daal.nyc3.digitaloceanspaces.com/static/css/admin.css?AWSAccessKeyId=****&Signature=***&Expires=1694226003 Django JET staticfiles URL: https://daal.nyc3.digitaloceanspaces.com/static/jet/css/icons/style.css?AWSAccessKeyId=*****&amp;Signature=*****&amp;Expires=1694226003&v=1.3.3 This is causing request headers to have invalid names: Note sure what is causing this? I couldn't find out why -
Command run 'pylint' on github action does not recognize Django setup
I have been trying to refactor my pylint workflow to comply with results of my local machine. After some wrestling, I am unable to make it understand the Django structure and apply environment installation. Source code: https://github.com/trouchet/tarzan/blob/main/.github/workflows/pylint.yml name: Pylint on: [push] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.8", "3.9", "3.10"] steps: - name: Checkout Code uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Set DJANGO_SETTINGS_MODULE run: export DJANGO_SETTINGS_MODULE=src.settings - name: Set up Poetry and pylint run: | # Install Poetry if not already installed curl -sSL https://install.python-poetry.org | python - # Configure Poetry to use the correct Python version poetry env use ${{ matrix.python-version }} - name: Set up Poetry and pylint run: | pip install pylint-django - name: Install project dependencies run: | # Install dependencies using Poetry poetry install - name: Analyze the code with pylint run: | # Run Pylint on Python files pylint $(git ls-files '*.py') -
Merging dictionaries in Django's views.py creates \n in JSON output
Merging dictionaries in django's views.py creates \n in Rest API json output @api_view(['GET']) def json_test(request): dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged_dict = {**dict1, **dict2} result = json.dumps(merged_dict, indent=4) return Response(result) Result in postman " {\n "a":1,\n. "b":2,\n "c":3,\n "d":4,\n}" I am expecting \n to not show up in api results and should look like below **{ "a":1, "b":2, "c":3 }" ** -
Django + opcua, background gateway
I am currently updating a web application based on Django framework. Im currently building a new json RestApi to manage our remote station. Our current api use Modbus tcp to talk with plc controller but for improving the security we want to switch to OPC-UA. I did few test and the solution is clearly functional but here is the problem: Django execute code in view once and then return the result. We need to open a session, browser to the node and get the value and before returning the result, we should close the session. That is take huge amount of Time. Usually OPC-UA keep session active as long as the connection between both device exist. I need to have an service or something similar that act as a gateway for django where django just request node data and the gateway manage to keep connection with device and fill django request. Any idea? Mais -
pytest-django test case doesn't see objects created with migrations
I have an odd problem with a test case like: pytestmark = pytest.mark.django_db def test_foo_bar(): root_page = Site.objects.first().root_page The issue is that the Site object, that by default should be created by Wagtail's migration, is not always (but sometimes, oddly, it is) accessible in the above test. The strange thing is, that when the test is ran with a specified path (pytest <path_to_file>.py::test_foo_bar) then the site is fetched correctly. I use these plugins: mock-3.11.1, randomly-3.12.0, django-4.5.2, Faker-18.11.2, sugar-0.9.7, snapshottest-0.6.0 -
Issue Configuring SSL/TLS with Let's Encrypt on Nginx for Python Django Website
I'm facing difficulties while configuring SSL/TLS for my Nginx server, which is hosting a Python Django website, using Let's Encrypt. I created an Nginx configuration file at /etc/nginx/sites-available/blog with the following configuration: server { listen 80; server_name my.domain.test; # Redirect HTTP to HTTPS return 301 https://$host$request_uri; } server { listen 443 ssl; server_name my.domain.test; # Paths to the Let's Encrypt SSL/TLS certificate ssl_certificate /etc/letsencrypt/archive/my.domain.test/fullchain1.pem; ssl_certificate_key /etc/letsencrypt/archive/my.domain.test/privkey1.pem; # SSL/TLS settings ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers off; ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'; # Additional SSL/TLS settings (hsts, OCSP, etc.) # To avoid any errors when fetching favicon location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/blog; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I received the following error when trying to test Nginx: ubuntu@ip-172-31-18-60:~/blog$ sudo nginx -t nginx: [warn] conflicting server name "my.domain.test" on 0.0.0.0:80, ignored nginx: [warn] conflicting server name "my.domain.test" on 0.0.0.0:443, ignored nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful When I run `sudo ls -l /etc/letsencrypt/archive/my.domain.test/fullchain1.pem`, I get: -rw-r--r-- 1 root root 5518 Sep 8 19:04 /etc/letsencrypt/archive/my.domain.test/fullchain1.pem Could someone please help me understand what's causing this error and how to fix it? -
Django, how to get count of cities of a country in two seperate models
I have 2 related models like this: class Countries(models.Model): country= models.CharField(max_length=50, blank=True, verbose_name='country') def __str__(self): return self.country class Cities(models.Model): Name = models.CharField(max_length=60,blank=True, null=True, verbose_name='name of the city' ) Rightful_owner = models.ManyToManyField(Countries, verbose_name='the country name', related_name='Rightful') Now I want to make an html table and write how many cities each country has? like this enter image description here what should I do in view.py and the html pages? I need the cod which I have to write in view.py and the html pages -
how to extract more elements from a list into a route?
I need to extract all elements from the list 'types' and display the content when 'typez' is accessed. I was only able to show the fire, but everyone else couldn't. views.py: types = { 'fire': ['aries', 'leo', 'sagittarius'], 'earth': ['taurus', 'virgo', 'capricorn'], 'air': ['gemini', 'libra', 'aquarius'], 'water': ['cancer', 'scorpio', 'pisces'], } zodiac_dic = { 'aries': 'Овен - первый знак зодиака, планета Марс (с 21 марта по 20 апреля).', 'taurus': 'Телец - второй знак зодиака, планета Венера (с 21 апреля по 21 мая).', 'gemini': 'Близнецы - третий знак зодиака, планета Меркурий (с 22 мая по 21 июня).', 'cancer': 'Рак - четвёртый знак зодиака, Луна (с 22 июня по 22 июля).', 'leo': 'Лев - пятый знак зодиака, солнце (с 23 июля по 21 августа).', 'virgo': 'Дева - шестой знак зодиака, планета Меркурий (с 22 августа по 23 сентября).', 'libra': 'Весы - седьмой знак зодиака, планета Венера (с 24 сентября по 23 октября).', 'scorpio': 'Скорпион - восьмой знак зодиака, планета Марс (с 24 октября по 22 ноября).', 'sagittarius': 'Стрелец - девятый знак зодиака, планета Юпитер (с 23 ноября по 22 декабря).', 'capricorn': 'Козерог - десятый знак зодиака, планета Сатурн (с 23 декабря по 20 января).', 'aquarius': 'Водолей - одиннадцатый знак зодиака, планеты Уран … -
openssl not connecting to gmail server
I'm using ubuntu 22.04 and openssl 1.1.1 This started when I tried to send an email to myself with Django's send_mail() function. The function executed fine, but the email never arrived. Checking the Postfix log revealed this error: connect to alt2.gmail-smtp-in.l.google.com[2607:f8b0:4023:1::1a]:25: Connection timed out Trying to diagnose this led to me to running command-line experiments with openssl. The following command fails with a timeout: # openssl s_client -connect smtp.google.com:587 -starttls smtp 4047B9AF807F0000:error:10000067:BIO routines:BIO_connect:connect error:../crypto/bio/bio_sock2.c:127: 4047B9AF807F0000:error:8000006E:system library:BIO_connect:Connection timed out:../crypto/bio/bio_sock2.c:125:calling connect() ... (several repeats of the error above) ... 403747797B7F0000:error:10000067:BIO routines:BIO_connect:connect error:../crypto/bio/bio_sock2.c:127: connect:errno=110 (The result was the same using "alt2.gmail-smtp-in.l.google.com", which was the domain from the postfix log) I don't think the problem is just my computer or network because trying with "strawberry.active-ns.com" (a domain used by an online example of openssl) works: $ openssl s_client -starttls smtp -connect strawberry.active-ns.com:587 CONNECTED(00000003) ... I have used send_mail() from my laptop in the past, and it has worked fine. Did Google change something? Any help would be greatly appreciated. -
Django - Forms ccreation and handling issue
I'm writing a Django website and I don't actually know which is the best way to organize my Models/Forms fields... I basicall have the following strtuccture (the names are invented): Model CarCompany: name = CharField .... Model Car: name = CharField .... company_name = ForeignKey .... Model Customer: name = CharField .... surname = CharField .... I need to save my model instances making sure there is an assosciation between the customer and all of his cars (and so also related cars.company_names) in the following way: Model CarDealer: name = CharField .... custoom_field = [a list of all the possible assosciations between Car and Customer. The way I thought it is to have a page that renders with the help of Ajax calls a series of rows and in each row I have three select element in which i can select in order: Customer, CarCompany, and (using AJAX), Car. How can I handle at best this situation using Django Forms? -
Testing django haystack integrated with solr backend
I am using Django Haystack which uses Solr for searching and was trying to write tests for this. views.py class CategorySearchAPIView(generics.GenericAPIView): def get(self, request): query = request.query_params.get('q', '') search_results = SearchQuerySet().filter(text__contains = query) results = [] for result in search_results: # my logic return Response(results, status = status.HTTP_200_OK) test.py class SearchCategoriesTest(APITestCase): def setUp(self): self.category1 = Category.objects.create(name="category1") self.category2 = Category.objects.create(name="category2") self.rebuild_index() def rebuild_index(self): call_command('rebuild_index', verbosity=0, interactive=False) def test_search(self): url = # my url response = client.get(url) The problem i am facing here is that, without running the rebuild_index(), my index won't have my newly created categories i.e category1 and category2 and result will be an empty list. But if I run rebuild_index(), my existing index will be overwritten by these two categories and older data is lost. Is there any tips/way I can fix this ? -
Template behavior depends on actual class of an instance in a class hierarchy
In django I have a model A and 3 derived models D1, D2, D3. I also have a ManyToManyField in another model B that references instances of A that can be instances of D1s, D2s or D3s. In the template, if I loop over the instances of A referenced by the ManyToManyField of B. How can I distinguish the display according to whether the actual model of my As is D1, D2 or D3? And how can I access a field which is in D1, but not in A, D2 or D3 when the actual class of my instance is D1? -
Django Allauth - How to Automatically Link Google OAuth Login to Existing User Account Created with Email?
I'm working on a Django project where I've implemented user registration and login functionality using Django Allauth. Users can sign up with their email and password, and I've also added "Login with Google" using OAuth2. The issue I'm facing is that when a user signs up with their email and later tries to log in using "Login with Google," it creates a new account instead of linking to the existing one associated with their email. Is there a way to automatically link the Google OAuth login to the existing user account if the email matches? I want users to be able to seamlessly switch between email-based login and Google OAuth login without creating duplicate accounts. Any guidance or code examples on how to achieve this integration would be greatly appreciated. Thank you! -
file not found during django collectstatic
In my django project collectstatic raises this exception: ValueError: The file 'my_path/exporting.js.map' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x7f3ee1a444c0>. I recently update to django 4. How can I fix it? Until yesterday it worked, I don't understand, sorry for the ignorance. -
Get group of user in ReactJS for role based permissions on a sidebar
I am creating a role-based permissions for a sidebar in a Django-React using rest_framework project. I have users that belong to different groups. Each groups have different permissions and should have different sidebar menu. In the frontend, how can I get the group of the user that is currently logged in? -
Django admin filter for inline model rows
I have a parent model (Author) & inline models (Book) class Author(models.Model): age = models.IntegerField() class Book(models.Model): name = models.CharField(max_length=250) price = models.CharField(max_length=250) author = models.ForeignKey(Author, on_delete=models.CASCADE) Book model has 3 rows to convey my issue I'm giving UI results in readable dict format {id:1, name:'book1', price: 50, author_id: 1} {id:2, name:'book2', price: 75, author_id: 1} {id:3, name:'book1', price: 65, author_id: 2} in admin.py, i have AuthorAdmin that has a list filter, list_filter = ['age', 'book__name', 'book__price'] in django admin list view page, if i filter /admin/?book__name=book1&book__price=75 it gives Author(id=1), Author(id=2) as result but it should only return the id:1 row alone. kindly help how to use list_filter in m2m relations (inlines) in django admin. i have used __ to filter the inlines, but the results are not accurate. my understanding is that django is returning the parent if atleast 1 of the inline item matches the query. i want the filters to be chained. -
Django form not saving form entries
I am trying to let users enter their own data to a form, but it is not being saved to my database and I can't figure out why. I can add new form entries from the admin, so I'm not sure if I've written things one level too high or something?test entry from admin page I define my submission sheet in models.py: from django.db import models import datetime class Submission(models.Model): project_name = models.CharField(max_length=240) location = models.CharField(max_length=240) # TODO: night be multiple times, try to get working with one for now time = models.DateTimeField() notes = models.CharField(max_length=1000) collector_name = models.CharField(max_length=240) collector_equipment = models.CharField(max_length=240) sample_id = models.CharField(max_length=240) class Meta: # fields = ('project_name', 'location', 'time', 'weather', 'collector_name', 'sample_id') verbose_name_plural = 'submissions' def __str__(self): return self.sample_id and the form itself in forms.py is from django import forms from django_form_builder.forms import BaseDynamicForm from .models import Submission class SubmissionForm(forms.ModelForm): class Meta: model = Submission fields = ( 'project_name', 'location', 'time', 'notes', 'collector_name', 'collector_equipment', 'sample_id', ) labels = { 'project_name': 'Project Name', 'location': 'Location', 'time': 'Time', 'notes': 'Notes', 'collector_name': 'Collector Name', 'collector_equipment': 'Collector Equipment', 'sample_id': 'Sample ID', } help_texts = { 'project_name': 'The project name', 'location': 'Lat/long or comment', 'time': 'Time (on/off) in UTC', 'notes': 'Notes', … -
Most efficient way of triggering DoesNotExist Exception for pk
I want to see if an id exists in the db without getting the instance from the db. And I want to trigger a DoesNotExist exception if it does not exist. This is what I'm currently doing: MyModel.objects.get(pk=my_model_id) but is there a more efficient but clear alternative?