Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How can I test the database read/write time in Django?
I need to prototype a basic website in Django and test the read and write speed of the database using the default Sqlite. I will have just one button on the website and when pressed, I want the to obtain the time it took for the database to process the button press. How can I do this? -
I'm trying to add an attribute to the object I've created in Django shell to create some queries but it says the object is not itrable
I'm trying to make a project with django I've migrated the model successfully and when I want to add account number to my checkingaccount objects it says the object is not iterable everything else works properly(as I tested) this is the models.py: from django.db import models # Create your models here. class Bank(models.Model): name = models.CharField(max_length=300) def __str__(self) -> str: return self.name class BankAccount(models.Model): bank = models.ForeignKey(Bank, on_delete=models.CASCADE) balance = models.DecimalField(max_digits=18, decimal_places=2) account_number = models.IntegerField() types = ( ('c', 'checking account'), ('s', 'savings account'), ) type_selection = models.CharField('account type', max_length=1, choices=types ) def __str__(self) -> str: return str(self.account_number) class CheckingAccount(models.Model): balance = models.DecimalField(max_digits=18, decimal_places=2) date_created = models.DateField() last_transaction = models.DateField() account_number = models.ManyToManyField(BankAccount) def __str__(self) -> str: return self.account_number def deposit(cash, self): self.balance += cash def check_balance(self): return self.balance def withdrawal(self, cash): self.balance -= cash class SavingsAccount(models.Model): balance = models.DecimalField(max_digits=18, decimal_places=2) date_created = models.DateField() account_number = models.ManyToManyField(BankAccount) def __str__(self) -> str: return self.account_number def deposit(cash, self): self.balance += cash def check_balance(self): return self.balance this is the shell input and output: >>> acC.account_number.set(ac) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Armin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py", line 992, in set objs = tuple(objs) TypeError: 'BankAccount' object is not iterable any helps … -
how i can solve these issue in vscode and django framework
here in my viwes.py I tried to select recommended python interpreter but nothing happen Import "rest_framework" could not be resolved -
Paypal Sandbox not sending IPN back to django through ngrok tunnel, but works fine on IPN Simulator
I have a django app that uses django-paypal to manage payments and trigger certain actions using signals.py when the payment is received @receiver(valid_ipn_received) def payment_notification(sender, **kwargs): ipn = sender if ipn.payment_status == 'Completed': # payment was successful, do something In order to test it locally, I'm using ngrok to expose the local server to Paypal services. Using the IPN Simulator everything is working fine and the signal in the django platform is triggered. However, when I interact with the sandbox under the same conditions, I am not receiving the IPN back from Payal after the payment is completed. From the sandbox business account dashboard I can see the payment is received, but looking at the IPN History from the same account I notice that Paypal is not able to send the IPN, claiming a "failed operation" without further information (not even an error code from the server). The strangest thing is that the sandbox flow was working like a charm until two days ago. Now I am only able to test through the IPN Simulator. What am I doing wrong? -
Selenium And Django - You can use them like in a script?
You can use Django and Selenium like in a script? Example: When user click on a button on web app then in backend selenium go on headless mode to one page url and get page source or click on a button on the url. -
how to render formset initial values in django-tables2?
I would like to render formset with initial values in django-tables2 and allow users to filter it by using django-filter. The problem is that I am not sure how to render initial values and allow users to filter these initial values on their own. If there is no way to connect django-filter, django-tables2 and formset initial values then how can I create a filter that will allow users to filter initial values in my rendered formset. It must allow to select and filter multiple product from the list. The table looks like this: What I am missing is the ability to allow users ability to select number of units and submit it as normal formset so the column # of units should look like this: models.py class ProductComponent(models.Model): related_product = models.ForeignKey(Product, on_delete=models.CASCADE) service = models.CharField(max_length=500, default='', blank=True) component_name = models.CharField(max_length=254, default='') class Request(models.Model): author = models.CharField(max_length=255, blank=True, null=True) related_component = models.ForeignKey(ProductComponent, on_delete=models.CASCADE, blank=True, null=True, default=1) number_of_units = models.IntegerField(default=0) related_product = models.ForeignKey(Product, on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now) filters.py class ProductComponentFilter(FilterSet): related_product = filters.ModelMultipleChoiceFilter( queryset=Product.objects.all(), field_name='related_product', ) class Meta: model = ProductComponent fields = { 'related_product', } views.py def component_list(request): get_components = CostCalculator.objects.all() get_datetime = timezone.now().strftime('%Y-%m-%dT%H:%M:%S') formset = RequestFormset(initial=[{ 'author': request.user.email, 'related_product': component.related_product, … -
Displaying the user's favorite products in Django
Displaying the user's favorite products in Django When I want to display the user's favorite products, the query result does not display anything and returns me None. Actually, I want to show the user which products he has added to his favorite list My model, view and address Url as follows my model: class UserWishlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, related_name='user_favourite') products = models.ManyToManyField(Product, related_name='product_favourite', blank=True, ) my url : path('wish/', views.wish, name='wish'), my view: def wish(request): data = UserWishlist.objects.get(user_id=request.user.id) return render(request, 'home/test.html', {'data': data}) my template : {{ data.products.name }} -
Problem with django rest framework APIview in pythonanywhere
I built an APIView to handle login. I use post method to send email and passwrod like below class LoginApi(views.APIView): permission_classes = (AllowAny,) # Adding permission to everyone def post(self,request): email = request.data['email'] password = request.data['password'] ... This works in my own system but when in push this to pythonanywhere the shape of request.data change like this: in my system : {"email":"email","password":"1234"} but in pythonanywhere is: <QueryDict: {'_content_type': ['application/json'], '_content': ['{"email":"email","password":"1234"}\r\n']}> my django version and rest-framework is the same with pythonanywhere. just my python version is 3.10 but pythonanywhere is 3.9. but I don't think it's the problem.