Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache Reverse Proxy using mod_proxy
0 Introduction I'm trying to setup a server with a main website hosted on ports 80 and 443 (let's call it example.com) and a section on this website that serves umami analytics hosted on port 3000 (let's call it umami.example.com) using a reverse proxy. I'm using Django and Apache (with mod_wsgi as hinted from the django project) and I have to setup DNS using Cloudflare. The main website works as intended, redirecting http traffic to https (more on that on the Apache section) and I'm tring to add this section under umami.example.com but every request ends up in a 404 error given by my main website. Currently I'm trying to make the umami part work using a reverse proxy (as shown in the first section of the Apache Config) #################################################################### 1 DNS DNS are configured using Cloudflare with 3 A records: example.com -> server IP address umami -> same server ip www -> again same ip and some MX and TXT ones. #################################################################### 2 Apache Config <VirtualHost _default_:80> ServerAdmin admin@example.com ServerName umami.example.com ProxyPass "/" "http://127.0.0.1:3000/" ProxyPassReverse "/" "http://127.0.0.1:3000/" </VirtualHost> <VirtualHost *:80> ServerName example.com ServerAlias www.example.com Redirect permanent / https://example.com/ </VirtualHost> <VirtualHost _default_:443> ServerAdmin admin@example.com ServerName example.com ServerAlias www.example.com Alias /static … -
Django Haystack different installation backends
At the Haystack docs there is a section at the installation where it indicates where your site configuration file will live and which backend to use, as well as other settings for that backend. There are mentions to some backends and I don't know which one I should choose... Solr, Elasticsearch, Whoosh, Xapian and Simple. Which one should I choose for a search engine not that complex but also not dumb. I want to look for items in my database by the title but also being able to handle typos? I want something that is open source and that does not use JavaScript. -
django.core.exceptions.ImproperlyConfigured, Requsted setting DEBUG (?)
I am getting the following error: "django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." The only point I can think of is that the project resides on a different mapped drive than local C. Does this mean I have to edit something, like maybe global_settings.py in django? -
Django using global variables
I believe this question can be applied beyond the scope of Django, but Django is all I know: how to handle global 'resource' variables? I am concurrently working on a testing framework for this tutorial project and finding myself copy-pasting field labels and help text to ensure their validity. Going forward, anytime I need to modify the label, I need to manually modify it in my testing framework as well which goes against basic programming principles. For example, # My ModelForm class in /my/path/models.py class MyForm(ModelForm): def clean_field(self): data = self.cleaned_data[<my_field>] ... return data class Meta: model = MyModel fields = [<field_a>, <field_b>, ...] # copy-paste labels = {<field_a>: <label_a>, ...} # copy-paste help_texts = {<field_a>: <help_text_a>, ...} # copy-paste ---- # Corresponding SimpleTestCase in /my/path/test_forms.py class MyFormTest(SimpleTestCase): def setUp(self): self.form = MyForm() def test_field_a_form_label(self): expected = <label_a> # copy-paste fl = self.form.fields[<field_a>].label # copy-paste self.assertTrue(fl is None or fl == expected) ... In Android, your project contains a 'resource' directory which has all the static values (help text, titles, etc) used throughout the project. This directory can then be accessed from anywhere through Context, creating a single source of truth. What is the recommended approach in web development for … -
Django rendering Form object rather than form fields
Sure I've missed something obvious, but any help appreciated. I have a form model: class UserForm(forms.Form): name = forms.CharField() A view: def userform(req): context = {} context['user_form'] = UserForm() context['message'] = 'test message' return render(req, 'apps/userform.html', context) And a template: {% extends 'base.html' %} {% block title %} | User Form {% endblock %} {% block content %} <h1>Form page</h1> <form method='POST'> {% csrf_token %} {{ user_form }} <button type='submit'>Send</button> </form> {{ message }} {% endblock %} I'm pretty sure everything is connected correctly and imported as required - the 'message' property on context renders fine under the form. However, {{ user_form }} in the template renders the actual Form object instance, rather than the actual form field I'm expecting. I see: <userform.views.UserForm object at 0x7fcab17e5c10> Then the form submit button. What have I missed? Django 4, if that matters. -
KeyError: 'lecture' in Django Serializer
I am trying to validate the request of the model. When I try to send patch request to the model there is a problem that I face: Error: if attrs["lecture"].author.id != self.context["request"].user.pk: KeyError: 'lecture' I don't know why I am getting such error. Does anybody know why I am getting the error? Full Code: Serializers class LectureAnnouncementSerializer(serializers.ModelSerializer): class Meta: model = LectureAnnouncement fields = ("id","lecture","teacher","announcement","file","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs["lecture"].author.id != self.context["request"].user.pk: raise ValidationError('Unauthorized Request') return attrs Models class LectureAnnouncement(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) teacher = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True, related_name='lectureannouncementsteacher') lecture = models.ForeignKey(Lecture, on_delete=models.CASCADE,null=True,blank=True, related_name='lectureannouncements') announcement = models.CharField(max_length=1000, unique=False, null=True, blank=True) file = models.FileField(upload_to='images',null=True,blank=True) timestamp = models.DateTimeField(unique=False,auto_now_add=True) -
Check if Djoser user exists by email
I am currently working developing a login screen where I am using djoser for authentication. I already use the /users/ and /token/login/ endpoints to create and log in users respectively in the frontend (JS fetch) and I know that /users/ will return an error message if the user already exists (which I'm displaying with react-hook-form). My question is: is there a way of verifying if the user already exists with their email only (without trying to create an account and working it out from the error message) -
how to create class name in django formset dynamically based on foreignkey value?
How can I pass the value from the slug field from the Product model to my formset and create a dynamic class name that will contain this value? I managed to create a fixed class name form-control in each form but I don't know how to make a dynamic class so it creates the slug that is a field in the Product model. When I put "class": self.related_product it gives me 'CalculatorForm' object has no attribute 'related_product' error. My question is what should I insert here to get slug value? forms.py class CalculatorForm(forms.ModelForm): author = forms.CharField(widget = forms.HiddenInput(), required = False) created = forms.DateTimeField(widget = forms.HiddenInput(), required = False) number_of_units = forms.IntegerField(min_value=0) total_price = forms.IntegerField(widget = forms.HiddenInput(), required = False) class Meta: model = CERequest fields = ('author', 'created', 'related_product', 'related_component', 'number_of_units') def __init__(self, *args, **kwargs): super(CalculatorForm, self).__init__(*args, **kwargs) for field in self.fields: new_data = { "class": 'form-control' #how to pass slug value here? } self.fields[str(field)].widget.attrs.update( new_data ) RequestFormset = formset_factory(CalculatorForm, extra=0, can_delete=False) models.py class CERequest(models.Model): author = models.CharField(max_length=255, blank=True, null=True) related_component = models.ForeignKey(CostCalculator, on_delete=models.CASCADE) number_of_units = models.IntegerField(default=0) related_product = models.ForeignKey(Product, on_delete=models.CASCADE) class Product(models.Model): ... slug = models.SlugField(max_length=250) -
How to traverse over reversed queryset in django?
I am trying to traverse twice over one reversed object, initally the for loop works but not on the second loop. x = Subscription.objects.filter(customer_id=customer_id).order_by('-id')[:count] tmp = reversed(x) y = call_function(subs=tmp) # inside this function as well object is of type reversed and i am able to loop over it inside the call_function. for j in tmp: # this loop is not running at all. here as well tmp is a reversed object print(j) # call_function(subs=s) def call_function(s): for i in s: print(i) -
What's the proper way to define this relationship in Django?
Okay, long story short, I have a model with - among other things - the following: class Connection(Model): currentnas = models.ForeignKey(NAS, null = True, blank=True, default = None, on_delete=models.SET_NULL, related_name='active') class NAS(Model): # Various data fields currentnas is, as the name suggests, the representation of the NAS that that connection is currently connecting through. This part works fine, however, now I'm trying to add another field to Connection: permittednas = models.ManyToManyField(NAS) The intention is to check during an authentication step whether currentnas matches one of the elements in permittednas; however, my first attempt to make this work ran into a snag when python informed me that TypeError: argument of type 'ManyRelatedManager' is not iterable. To clarify, I have a number of Connections a, b, c, d and a number of NAS objects 1, 2, 3, 4, and I want to be able to say that (for example) a is permitted to connect via 1, 2 and 4; b may connect via 2 and 4; c can connect via all four, and d may only connect via NAS 1. -
Django admin Valid form with funtion clean
In my django model I defined a clean function to validate additional conditions before saving the data. Here is my model: class TestRange(models.Model): SERVICE = [ ('s1', 'Service 1'), ('s2', 'Service 2') ] service = models.CharField(max_length=2, choices=SERVICE) SDA = [ (False, 'NO SDA'), (True, 'SDA') ] sda = models.BooleanField(choices=SDA) number_start = models.CharField(max_length=10, validators=[valide_phone_number]) number_end = models.CharField(max_length=10, validators=[valide_phone_number]) def clean(self): if int(self.number_end) < int(self.number_start): raise ValidationError({'number_end': _("The end number must be greater than or equal to the start number")}) if self.sda and len(self.number_start)!=10: raise ValidationError({'number_start': _("A SDA number consists of 10 digits")}) super(TestRange, self).clean() Since the definition of this function the default validation of the admin form no longer works, I no longer have to check the fields of the form before registration. So I got an error message: invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/admin/gestnum/testrange/add/ Django Version: 4.1 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: C:\Users\user\Documents\DEV\test\test\models\TestRange.py, line 25, in clean Raised during: django.contrib.admin.options.add_view Python Executable: C:\Users\user\Documents\DEV\test\.venv\Scripts\python.exe Python Version: 3.9.6 how to proceed to keep the default validation and add my additional validation without the function: defaut validate adminform Do you have a solution ? Without … -
Python Django Eureka Client is not unregistering from Eureka Server in Kubernetes Cluster
I want to register python django eureka client to java spring eureka server. There is no problem when registering django project to the eureka server on localhost, when django project is run it is registering to the eureka server. when stop django project with CTRL + C, it is unregistering from the eureka server. The problem is that registering django project via Kubernetes cluster, i am running pod with command "kubectl apply -f kub8s-media.yaml" and it is successfully registers but when i want to stop project using "kubectl delete -f kub8s-media.yaml" or restart using "kubectl rollout restart deployment kub8s-deploy" django project didn't unregister from eureka Dockerfile FROM python RUN mkdir /backend-media COPY . /backend-media WORKDIR /backend-media ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 EXPOSE 8001 RUN pip install -r requirements.txt CMD ["python", "manage.py", "runserver", "0.0.0.0:8001"] kub8s-media.yaml apiVersion: apps/v1 kind: Deployment metadata: name: backend-media-deploy spec: selector: matchLabels: app: backend-media replicas: 1 template: metadata: labels: app: backend-media spec: containers: - name: backend-media-app ports: - containerPort: 8001 image: aalfaa00/media:latest --- apiVersion: v1 kind: Service metadata: name: backend-media-svc labels: app: backend-media spec: type: NodePort ports: - port: 8001 protocol: TCP selector: app: backend-media eureka.py import random import string import os import py_eureka_client.eureka_client as eureka_client N … -
How Can I inherit two classes in Django?
I can not use Abstract base class because I need to use it as a foreign key in another model. When I use makemigrations it gives "you are trying to add a non-nullable field 'base_ptr' to childa without a default". django-polymorphic package doesn't change result. class Base(models.Model): #some base fields class ChildA(Base): #some extra fields class ChildB(Base): #some extra fields -
Running django app with docker, unrecognized runserver arguments
I'm having a problem with starting my django project in docker container. I have tried this in multiple ways, for example: docker-compose run web python manage.py runserver or just docker-compose up first time i have tried this i got no error, but i couldn't open the app in browser so i tried it again and then it stopped working completely. I'm getting this error: manage.py runserver: error: unrecognized arguments: python manage.py runserver My docker-compose.yml version: "3.9" services: db: image: postgres:alpine volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=gitlabdumptables - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=gitlabdumptables - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db My Dockerfile # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip3 install -r requirements.txt CMD python manage.py makemigrations CMD python manage.py migrate COPY . /code/ ENTRYPOINT [ "python", "manage.py", "runserver", "0.0.0.0:8000" ] -
Static file is not opening in Django project-- error 404 1825?
I am constantly getting 404 error when my page is trying to load static image file. ERROR: [12/Aug/2022 12:02:54] "GET /myApp/ HTTP/1.1" 200 370 [12/Aug/2022 12:02:54] "GET /static/myApp/images/cofee.jpg HTTP/1.1" 404 1825 SETTINGS: BASE_DIR = Path(__file__).resolve().parent.parent my_templates = Path(BASE_DIR, 'templates') static_dir = Path(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIRS = [ static_dir, ] HTML: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>We are here to Help</h1> <img src="{% static 'myApp/images/cofee.jpg' %}" alt= " no show "> </body> </html> NOTE: server is running without error and page is loading just fine with heading1 showing but static image is not showing. -
How to use parameters in class view and url?
I want to get parameter from template. But when I do it gives an error: TypeError at /report/2000-01-01/2022-08-12/Investigations/ wrapper_func() missing 1 required positional argument: 'request' It takes the parameters true but I think I can't pass them to the views. How can I do it? views.py class GroupingReportsPage(ReportsMixin, ListView): model = ProcessType def case_groups(date_1, date_2, process_group): fieldname = 'case_type_value' cases = Case.objects.filter(date_created__range=[date_1, date_2]) process_types = ProcessType.objects.filter(reporting_group__option=process_group) report_group = {} print('cases') print('cases') print(cases) print(process_types) return cases def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print('sadasds') self.case_groups() context['query_trend'] = 'query_trend' return context urls.py path('report/<str:date_1>/<str:date_2>/<str:process_group>/', report.GroupingReportsPage.as_view(), name='process_groups'), template <a href="{% url 'fdm:process_groups' date_1 date_2 index %}" style="color: black"> {{index}} </a> -
How to set maintenance mode with django in stateless aplication
I've hosted my app in Google Cloud Run, a simple Vue's frontend connected to a django API. The problem arises when I try to set maintenance mode to the API, protecting it from unexpected calls. For this purpose I've used django-maintenance-mode's package, but, as I said, due to the implicit stateless character of GC Run, the enviroment variable that stores the maintenance mode's value drops when there isn't any active instance, getting back to OFF. I'd like to know any other possible solution or fix overriding any of this package's methods to make it work in my project. Thanks in advance!! -
KeyError when selecting date in the past
I am making a members management app. I have a activation form and I wrote a script to check if date is valid (clean_start_date & clean_end_date). ie todays date or greater. Script is working fine (if I select today's date or greater). However, if I selected an old date only end_date works fine, start_date Throws KeyError. forms.py class ActiveMemberForm(ModelForm): def __init__(self, *args, **kwargs): super(ActiveMemberForm, self).__init__(*args, **kwargs) pass class Meta: model = ActiveMember fields = ( 'member', 'start_date', 'end_date', 'status', ) widgets = { 'start_date': widgets.DateInput(attrs={'type': 'date'}), 'end_date': widgets.DateInput(attrs={'type': 'date'}), } def clean_start_date(self): start_date = self.cleaned_data['start_date'] if start_date < timezone.now().date(): raise ValidationError('Please enter a valid start date!') return start_date def clean_end_date(self): #start_date = self.cleaned_data['start_date'] end_date = self.cleaned_data['end_date'] if end_date < timezone.now().date() or end_date < self.clean_start_date(): raise ValidationError('Please enter a valid end date!') return end_date models.py class ActiveMember(models.Model): member = models.OneToOneField(Member, on_delete=models.CASCADE, related_name='is_member') start_date = models.DateField(default=django.utils.timezone.now) end_date = models.DateField(default=django.utils.timezone.now) status = models.CharField(max_length=2, choices=(('1','Active'), ('2','Inactive')), default = '1', blank=True, null=True) def __str__(self): return str(f"{self.member}") Console Error Message Internal Server Error: /activate/ Traceback (most recent call last): File "C:\Users\timmeh\source\Python Projects\Django Projects\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\timmeh\source\Python Projects\Django Projects\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\timmeh\source\Python Projects\Django … -
filter django formset table in jQuery based on selected option asynchronously
I am trying to implement filter buttons in my django formset and found a solution that would allow user to do that asynchronously. I tried to use code from here but my html is more complex and I don't know how to filter each row based on text in Product column. The html that is generated looks like this: My problem is that I am not sure how to pass related_product name as value or as text in jQuery function so when I select test product it will show me only rows that contain "test product" text: So what should I put as class name in $('tbody tr').show(); to get related_product title and show all rows that contains this related_product title? views.py class ProductComponentView(TemplateView): template_name = "formset.html" def get(self, *args, **kwargs): get_components = CostCalculator.objects.all() get_datetime = timezone.now().strftime('%Y-%m-%dT%H:%M:%S') product_list = Product.objects.filter(status=1) formset = RequestFormset(initial=[{ 'author': self.request.user.email, 'related_product': component.related_product, 'related_component': component.id, 'created': get_datetime, 'number_of_units': 0 } for component in get_components]) return self.render_to_response( {'product_component_formset': formset, 'product_list': product_list, }) def post(self, *args, **kwargs): formset = RequestFormset(data=self.request.POST) if formset.is_valid(): for form in formset: form.save() return super().form_valid(form) formset.html {% for product in product_list %} <input class="filterbox" type="checkbox" name="interest" value="{{product.title}}" />{{product.title}}<br /> {% endfor %} <form method="post"> … -
Docker and Nginx: listen tcp4 0.0.0.0:80: bind: address already in use
I have a VPS server (Ubuntu), I am running multiple Django projects with Nginx and Gunicorn. I decided to deploy my latest project with Docker. Everything is working, except the port 80. I can run the website on example.com:1330 but once I change it to 80, I get this error: err: ERROR: for nginx Cannot start service nginx: driver failed programming external connectivity on endpoint project-nginx (a4417bdb121b0afb1e57e11b68dd0eb74f770ed74f654a2722f4cd74121): Error starting userland proxy: listen tcp4 0.0.0.0:80: bind: address already in use err: Encountered errors while bringing up the project. Here is a part of my: docker-compose.yml nginx: container_name: portfolio-nginx restart: unless-stopped build: ./nginx ports: - "80:80" # doesn't work - "1330:80" # works Nginx upstream project { server project-django:8000; } server { listen 80; server_name example.com; location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { root /code; } location /media/ { root /code; } } I thought the problem is I have Nginx already running on port 80: sudo netstat -ntulp | grep 80 Once I kill the process the docker website works on port 80. But I lose the other Django projects that doesn't run on docker. -
save multiple images in django admin
image = models.FileField( verbose_name='afbeelding', upload_to='website/ServiceImage/image', ) description = models.TextField( verbose_name='beschrijving', blank=True, null=True, ) work_in_progress = models.BooleanField( verbose_name='work in progress', ) label = models.CharField( max_length=100, null=True, blank=True, verbose_name='label' ) service_page = models.ForeignKey( Service, on_delete=models.CASCADE, verbose_name='service_page', related_name='service_image_set', ) created = models.DateTimeField( verbose_name='aangemaakt', auto_now_add=True, blank=True, null=True, ) last_modified = models.DateTimeField( verbose_name='laatst aangepast', auto_now=True, blank=True, null=True, ) class Meta: verbose_name = 'Realisatie afbeelding' verbose_name_plural = 'Realisatie afbeeldingen' ordering = [ 'created' ] This is model and this is form.py class ServiceImageForm(forms.ModelForm): model = ServiceImage image = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True})) def save(self, commit=True): instance = super(ServiceImageForm, self).save(commit) for photo in self.files.getlist('image'): ServiceImage.objects.create( image=photo, service_page=instance, ) return instance class Meta: exclude = () I need to select multiple images and save it in database so in this code I am selecting multiple images but not saving in django admin anyone here can tell me where I am making mistake.Should I need to change model or there is problem in save method? Can someone help me with this? -
Why Django ask for the id in raw queries?
I'm doing a raw query in Django 3.10.5 ################################### MediosBasicos.objects.raw('SELECT descripcion, COUNT("descripcion") AS "descrip" FROM "basedatos_mediosbasicos" GROUP BY "descripcion"') ################################### But for some reazon it ask me for the id. That has no sence. Someone knows why this happends or what is the purpose of it? -
How to host django website on hosting cyberpanel vps plan with a custom domain name?
please tell me the procedure to host my django based website on hostinger cyberpanel vps. no content is found on youtube and on other sources. i done many steps but I am unable to host my website, please let me know the procedure for this. -
Will azure free services be counted if using locally? Basically using localhost will the number of character counted for each text translation request
Making a translator for hackathon. Are we allowed to use free API's services of azure. Will the characters get counted if we run the code locally? If free characters of months get used will we get incurred with charges? Can we clear the session so that number of characters can be reused again when working locally? -
Django 4 Error: 'No time zone found with key ...'
After rebuild of my Django 4 Docker container the web service stopped working with error : zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Asia/Hanoi' My setup is: Python 3.10 Django 4.0.5 Error: > web_1 | Traceback (most recent call last): web_1 > | File "/usr/local/lib/python3.10/zoneinfo/_common.py", line 12, in > load_tzdata web_1 | return > importlib.resources.open_binary(package_name, resource_name) web_1 > | File "/usr/local/lib/python3.10/importlib/resources.py", line 46, > in open_binary web_1 | return > reader.open_resource(resource) web_1 | File > "/usr/local/lib/python3.10/importlib/abc.py", line 433, in > open_resource web_1 | return > self.files().joinpath(resource).open('rb') web_1 | File > "/usr/local/lib/python3.10/pathlib.py", line 1119, in open web_1 > | return self._accessor.open(self, mode, buffering, encoding, > errors, web_1 | FileNotFoundError: [Errno 2] No such file > or directory: > '/usr/local/lib/python3.10/site-packages/tzdata/zoneinfo/Asia/Hanoi' > web_1 | web_1 | During handling of the > above exception, another exception occurred: web_1 | > web_1 | Traceback (most recent call last): web_1 > | File "/home/app/web/manage.py", line 22, in <module> web_1 > | main() web_1 | File "/home/app/web/manage.py", > line 18, in main web_1 | > execute_from_command_line(sys.argv) web_1 | File > "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", > line 446, in execute_from_command_line web_1 | > utility.execute() web_1 | File > "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", > line 420, in execute web_1 | django.setup() web_1 > | File …