Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multistage docker build for Django
I am dockerizing my Django application with docker multi-stage build. Now am facing an issue with dependencies Dockerfile FROM python:3.8-slim-buster AS base WORKDIR /app RUN python -m venv venv ENV PATH="/app/venv:$PATH" COPY requirements.txt . RUN pip install -r requirements.txt \ && pip install gunicorn COPY entrypoint.sh . COPY . . FROM python:3.8-slim-buster WORKDIR /app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY --from=base /app /app/ ENV PATH="/app/venv:$PATH" ENTRYPOINT sh entrypoint.sh When running the container it raises import error. ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
login not working in Django after migrating to 3.2 getting error: django.db.utils.ProgrammingError
I recently migrated my Django version from 2.2 to 3.2 and login stopped working after that. In 2.2 it was working fine. It is giving an error:- > Traceback (most recent call last): > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/handlers/exception.py", > line 47, in inner > response = get_response(request) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/handlers/base.py", > line 181, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/views/generic/base.py", > line 70, in view > return self.dispatch(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/decorators.py", > line 43, in _wrapper > return bound_method(*args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/views/decorators/debug.py", > line 89, in sensitive_post_parameters_wrapper > return view(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 146, in dispatch > return super(LoginView, self).dispatch(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 74, in dispatch > response = super(RedirectAuthenticatedUserMixin, self).dispatch( > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/views/generic/base.py", > line 98, in dispatch > return handler(request, *args, **kwargs) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 102, in post > response = self.form_valid(form) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/views.py", > line 159, in form_valid > return form.login(self.request, redirect_url=success_url) > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/forms.py", > line 196, in login > ret = perform_login( > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/utils.py", > line 171, in perform_login > if not _has_verified_for_login(user, email) and signup: > File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/allauth/account/utils.py", > line 139, in _has_verified_for_login > ret = EmailAddress.objects.filter(user=user, … -
How to display uploaded pdf file along with machine name and operation number based on select from dropdown
In this project, I want to display machine name and operation number along with uploaded pdf files based on select machine name and operation number from dropdown menu. This project is working but when I add and select another file in same machine name and operation number, it is displaying two pdf files along with previous pdf file of another machine name and operation number, exactly I don't want it. It should display machine name and operation number along with uploaded pdf file based on select from dropdown menu. And also when I upload another pdf files in same machine name and operation number, it should display two pdf files along with same machine name and operation number within same row. This project is working fine but I want above validations. Please anyone can help me out, this will be great for me. Please.. views.py: def upload(request): controlmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machinename', '') operation_no = request.POST.get('operationname','') choiced_cmachine = Controlmachine.objects.filter(machine_name=machine_name, operation_no=operation_no) cmachines = Controlmachine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines,'choiced_cmachine':choiced_cmachine}) def index(request): if request.method == 'POST': form = ControlmachineForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save() model_instance.save() else: form = ControlmachineForm() controlmachiness = Controlmachine.objects.all() return render(request,'usermaster/upload_file.html',{'form':form,'controlmachiness':controlmachiness}) upload.html: … -
Django inspectdb not creating primary keys
When I run python manage.py inspectdb --database totals > modelstest.py it appears to function as expected and I get my models, but it does not create primary keys and add an id field although everything I can find online says it does, little confused. I went into my settings file and added DEFAULT_AUTO_FIELD='django.db.models.AutoField' but now when I try to migrate again there is nothing to migrate, I flushed my db and tried to migrate again but it didn't really do anything, a little confused how I can migrate again to kick in that auto field setting now? -
how to dump postgres database in django running in docker-container?
I have an application running in a docker container and psql database running in a docker container as well. i want to dump database while in django container, i know there is dumpdata in django but this command takes long time, i also tried docker exec pg_dump but inside django container this command doesn't work. services: db_postgres: image: postgres:10.5-alpine restart: always volumes: - pgdata_invivo:/var/lib/postgresql/data/ env_file: - .env django: build: . restart: always volumes: - ./static:/static - ./media:/media ports: - 8000:8000 depends_on: - db_postgres env_file: - .env Is there any way to do pg_dump without using docker exec pg_dump while in django container? -
How can I add certain number of day to a date, with python - timedelta?
I am stuck with an issue. Basically, I have to add, depending on the type of duration, a certain number of days to a date. My model and functions are like that: models.py from django.db import models import datetime # Create your models here. FRAZIONAMENTO = ( ('Annuale', 'Annuale'), ('Semestrale', 'Semestrale'), ('Quadrimestrale', 'Quadrimestrale'), ('Mensile', 'Mensile'), ) class Polizza(models.Model): cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE) numero_polizza = models.CharField(max_length=100) data_decorrenza = models.DateField() data_scadenza = models.DateField(blank=True, null=True) ramo_polizza = models.CharField(max_length=100, choices=RAMO_POLIZZA) polizza_nuova = models.BooleanField(default=True) frazionamento = models.CharField(max_length=100, choices=FRAZIONAMENTO) premio = models.DecimalField(max_digits=5, decimal_places=2) provvigione = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) creata = models.DateTimeField(auto_now_add=True) aggiornata = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Polizza' ordering = ['data_scadenza'] def __str__(self): return self.ramo_polizza + ' ' + self.frazionamento @property def get_data_scadenza(self): if self.frazionamento == 'Annuale': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=365)) elif self.frazionamento == 'Semestrale': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=180)) elif self.frazionamento == 'Quadrimestrale': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=120)) elif self.frazionamento == 'Mensile': data_scadenza = self.data_decorrenza + \ str(datetime.timedelta(days=30)) return data_scadenza def save(self, *args, **kwargs): self.provvigione = self.get_provvigione super(Polizza, self).save(*args, **kwargs) views.py def nuova_polizza(request): clienti = Cliente.objects.all() polizze = Polizza.objects.all() context = { 'clienti': clienti, 'polizze': polizze, } return render(request, 'anagrafica/nuova_polizza.html', context) def salva_nuova_polizza(request): if request.method == 'POST': cliente … -
Show a part of the template that has been previously filtered
I would like to know what is the most pythonic way to get the following result: Let's say we have a view: def myView(request): context = {} if something: context['A'] = "Whatever" else: context['B'] = "Whatever" return render(request, 'mypage.html', context) In the template, let's say mypage.html we have the following scenario: {% if A %} A code {% else %} B code {% endif %} When the page loads, the code is rendered depending on whether we have A or B in the view context. My question is: if the page renders with the A code (for example), is it possible through a button when clicking on that button to hide A code and show B code instead? -
How to connect uploaded pdf file to dropdown list in django
In this project, I want to display uploaded pdf files along with machine name and operation number based on select from dropdown list. Here, when I select machine name and operation number, It is displaying the pdf file but when I select another machine name and operation number, it is displaying two pdf files along with previous pdf file, exactly I don't want this, How to solve this. And also when I add another pdf file in same machine name and operation number, It should display two pdf files within same row. This project is working correctly, but I want above validations. Please anyone solve this for me, that will be great for me. Please views.py: def control_upload(request): if request.method == 'POST': form = ControlForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save() model_instance.save() else: form = ControlForm() controlmachiness = Controlmachine.objects.all() return render(request,'master/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def control_index(request): controlmachines = Controlmachine.objects.all() return render(request,"master/control_show.html",{'controlmachines':controlmachines}) def control_destroy(request, id): controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() return redirect("/") control_show.html: <div class="col-md-12"> <div class="table-responsive"> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%"> <thead> <th><input type="checkbox" id="checkall" /></th> <th>ID</th> <th>Machine Name</th> <th>Operation Number</th> <th>File</th> <th>Delete</th> </thead> <tbody> {% for control in controlmachines %} <tr> <td><input type="checkbox" class="checkthis" /></td> <td>{{ control.id }}</td> <td>{{ control.machine_name }}</td> <td>{{ … -
Filtering out a message for a single user
Inbox = Messages.objects.filter(Q(sender=request.user)&Q(senderDeleted=False) | Q(receiver=request.user)&Q(receiverDeleted=False)).order_by("-time", "read") context['Inbox'] = Inbox unreadMessagesCount = Messages.objects.filter(Q(receiver=request.user) & Q(read=False)&Q(receiverDeleted=False)).count() context['unreadMessagesCount'] = unreadMessagesCount I am trying to filter out messages by who doesn't want them to be seen anymore. The logic goes if senderDeleted or receiverDeleted is True then don't let the messages appear anymore. Currently the messages stay on the page unless they both click delete or the message sender being deleted is the current user logged in. What I'd like for it to do is remove it from the view of a single user and allow the other user to still view it. When clicking on the elements it does switch the fields to the True value as well. @login_required @require_http_methods(["POST"]) def delete(request,messageID): #Only remove the message if both people want it removed or if the send and receiver are the same person data_to_be_deleted = Messages.objects.get(id = messageID) if data_to_be_deleted.sender == data_to_be_deleted.receiver: data_to_be_deleted.delete() return redirect('messagesInbox') else: if data_to_be_deleted.sender==request.user: data_to_be_deleted.senderDeleted=True data_to_be_deleted.save() else: data_to_be_deleted.receiverDeleted=True data_to_be_deleted.save() data_to_be_deleted = Messages.objects.get(id = messageID) if data_to_be_deleted.senderDeleted and data_to_be_deleted.receiverDeleted: data_to_be_deleted.delete() return redirect('messagesInbox') models.py: class Messages(models.Model): sender = models.ForeignKey(Profile,related_name='sender',on_delete=models.CASCADE) senderDeleted = models.BooleanField(default=False) receiver = models.ForeignKey(Profile,related_name='receiver',on_delete=models.CASCADE) receiverDeleted = models.BooleanField(default=False) subject = models.CharField(default='',max_length=100) text = models.CharField(default='',max_length=4096) time = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) parent = … -
How do you setup your .venv environment?
I have a few basic questions regarding Virtualenv. I can install it, I can run it, activate it, all of this is good. My question is "And then what ?" How do setup your dev env ? -Do you create a new .venv for each project ? -And within that each project having its specific modules ? -Modules which are not used (for any reason, try a few, keep one, for instance) how are they removed ? -Going this way, once your project is finished and delivered, or dropped for any reason, how do you uninstall its .venv ? I did read the docs, it's mainly about installation, examples, coding and so on. What I can't figure is a proper usage of this tool. Thanks in advance for your help -
How to use jQuery to make a Django Alert appear (sliding down)
The following script is working fine to fade out my Django alert: <script> $(document).ready(function(){ window.setTimeout(function() { $(".alert").fadeTo(500, 0).slideUp(500, function(){ $(this).remove(); }); }, 2000); }); </script> But the following is not working---I'm just trying to do the opposite here: make the Django alert appear by sliding down. How can I make the below work? <script> $(document).ready(function(){ $(".alert").show().slideDown(500, function(){ }); }); </script> -
Django web page shows error when running server
I have just started a Django project and spun up a web server. I have made minimal changes which I will post below. When I start my server, I am given a url which I click on to navigate to my web app. I see the following error I am running python manage.py runserver to run my server Following are the only changes I have made to the files: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', ] urls.py from django.urls import path from .views import HomePageView urlpatterns = [ path('', HomePageView, name='home'), ] urls.py in the project folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')) ] views.py from http.client import HTTPResponse from django.http import HttpResponse def HomePageView(request): return HTTPResponse("Hello Django") -
Logging in django is not outputting anything
I was having issues with print statements and Django and I saw on here that its better to do logging. I am not sure what I am doing wrong though. It logs sometimes to console and other times it doesn't for the same page and I cant get it to log anything in my post method. I have tried doing the ```logger = logging.getLogger("mylogger") above all the class views, ive tried adding that line to each individual method and ive tried only having it in 1 at a time. Any thoughts? Settings.py Logger Settings LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'filters': ['require_debug_true'], }, }, 'loggers': { 'mylogger': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), 'propagate': True, }, }, } Views.py class CreateOrderView(View): def get(self, request,): logger = logging.getLogger("mylogger") logger.info("TEST") # this should be removed once user_ids are implemented through login system and session creation request.session["user_id"] = 1 # should be set to session.get("user_id") probably in the future user_id = request.session.get("user_id") trade_form = CreateTradeForm() order_form = CreateOrderForm() context = {} context["user_id"] = user_id context["order_form"] = order_form context["trade_form"] = trade_form return render(request, "trading_log/add-order.html", context) def post(self, request): trade_form … -
Unable to return using post method in an html form. what am i doing wrong?
I am new to programming, i have been learning django for the first time. I created a form using home.html file an i requested using POST method, but in the error it is giving the request method as GET. When I remove the method="POST" and put request.GET in views file, it is working fine. What am I doing wrong here? home.html < form action="add" method="POST"> {% csrf_token %} Enter 1st number : <input type="text" name="num1"><br> Enter 2nd number : <input type="text" name="num2"><br> <input type="submit"> views.py def add(request): val1= int(request.POST['num1']) val2= int(request.POST['num2']) res= val1 +val2 return render(request, 'result.html' ,{'result': res}) I am getting the following error: MultiValueDictKeyError at /add 'num1' Request Method: GET Request URL: http://127.0.0.1:8000/add?num1=17&num2=4 Django Version: 4.0.1 Exception Type: MultiValueDictKeyError Exception Value: 'num1' -
Serializing RAW SQL query Django
Hope you doing well. I need to serialize my RAW SQL query: SELECT nn.*,nm.*FROM notifications_newsletter nn LEFT JOIN notifications_message nm ON nn.id=nm.newsletter_id_id ORDER by nm.status DESC models.py from django.db import models class Newsletter(models.Model): start_datetime = models.DateTimeField() text = models.TextField(blank=True) filter = models.ForeignKey('Filter', null=True, on_delete=models.SET_NULL) end_datetime = models.DateTimeField() class Message(models.Model): send_datetime = models.DateTimeField('%Y-%m-%d %H:%M:%S', auto_now=True) status = models.BooleanField(default=False) newsletter_id = models.ForeignKey('Newsletter', on_delete=models.CASCADE) client_id = models.ForeignKey('Client', on_delete=models.CASCADE) views.py from django.core.serializers import serialize from django.http import HttpResponse from .models import Newsletter def some_view(request): sql = 'SELECT nn.*,nm.*FROM notifications_newsletter nn ' \ 'LEFT JOIN notifications_message nm ' \ 'ON nn.id=nm.newsletter_id_id ORDER by nm.status DESC' qs = Newsletter.objects.raw(sql) qs_json = serialize('json', qs) return HttpResponse(qs_json, content_type='application/json') If I do it with serializers.serialize() all joined data (message table) doesn't exist in response. But if print(qs.columns) the columns send_datetime, status, etc. will be printed. Response: [ { "model": "notifications.newsletter", "pk": 42, "fields": { "start_datetime": "2022-01-21T21:56:09Z", "text": "This is test message for 900 operator code.", "filter": 1, "end_datetime": "2022-01-21T18:00:00Z" } }, ] I need something like: [ { "model": "notifications.newsletter", "pk": 43, "fields": { "start_datetime": "2022-01-21T22:03:26Z", "text": "This is test message for 904 operator code.", "filter": 2, "end_datetime": "2022-01-21T18:00:00Z", "messages": [ { "send_datetime": "2022-01-21T22:03:26Z", "status": 0, "newsletter_id": 43, "client_id": … -
How do I make my urlpatterns smarter, to avoid cumbersome code in my templates?
Right now I have defined my URLs such that they can include different combinations of category (always on), attribute_slugs (1 and/or 2) and brand_slug, all using the urlpatterns defined below. In my views.py file I make sure that each slug exists in the respective model, or else a 404 is thrown. I also make sure that the attributes have a specific ordering, so that I avoid identical pages where the attributes are just switched around in the URLs. Then the context is sent to a template. In my template for the categories, I implement an ecommerce filter based on the context. For example, the filter can show links to the attributes contained by the products on that particular page. So if you are on the page: /shoes/, then the color filter has the options: /shoes/green, /shoes/blue/, /shoes/black/ etc. This filter is made with the default { % url % } template tag with parameters based on the context. It works fine, but there is one issue. It is based on a lot of logical statements in the template, which is cumbersome. For example, there is an if-statement to check if there is 0 attribute, 1 attribute and 2 attributes on … -
Extend user to have many medications
I would like to save many medications to the Profile like so. models.py class Profile(AbstractUser): class Medications(models.Model): user = models.ForeignKey(Profile,related_name='user',on_delete=models.CASCADE) name = models.CharField(default='',max_length=100) amount = models.IntegerField() per_time = models.IntegerField() time_choices = (('other', 'Other'),('Post meal', 'Post meal'),('Breakfast' ,'Breakfast')) choice = models.CharField(max_length=10, choices=time_choices,default='others') forms.py class MedicationForm(forms.ModelForm): name = forms.CharField(max_length=100, required=True, help_text='Required.') amount = forms.IntegerField( required=True, help_text='Required.') class Meta: model = Medications fields = ('name','amount','per_time','choice') Now in here I would like to create a Medication with the request user. I used if form.is_valid(): form.save() which just gives IntegrityError at /addMed/ NOT NULL constraint failed: pages_medications.user_id which needs to be from request.user @login_required @require_http_methods(["POST"]) def addMed(request): print('Adding med') print(request.user) print(request.POST) med = MedicationForm(request.POST or None,) print(med) return redirect('medications') Which gives Adding med user <QueryDict: {'csrfmiddlewaretoken': ['-'], 'name': ['Tylenol'], 'amount': ['1'], 'per_time': ['1'], 'choice': ['other'], 'medicationForm': ['Upload']}> Then list all the medications in here. views.py @login_required def medications(request): context={} context['nmenu'] = 'medications' context['medicationForm'] = MedicationForm() return render(request, 'home.html', context) -
Set up connection to VPN on Amazon Lightsail app
I've got an server on AWS using Lightsail that uses Linux/Django OS/app combination. I need to use the Django framework to create a function that will take requests coming into the server, and forward them on to another API. This API is only accessible through a VPN. I believe that by just connecting my OS to the VPN any requests my Django app sends should go through the VPN (in theory, please correct me if I'm wrong), however I am unsure how to connect to the VPN using just the Linux command line. I have the server name, a username and password, which I can connect to fine on my Windows machine by just adding a VPN connection. Is anyone able to advise if it is possible to connect this OS provided by Amazon Lightsail to a VPN, and if so how to do so in order for me to able to route HTTPS requests to the API behind a VPN! Thanks, hopefully I'm posting this in the right place! -
Push rejected, failed to compile Python app on Heroku
I'm trying to deploy a Django app to Heroku, it starts to build, download and installs everything, but that's what I get when it comes to 'Collectstatic environment variables': ****** Collectstatic environment variables: PYTHONUNBUFFERED=1 PKG_CONFIG_PATH=/app/.heroku/vendor/lib/pkg-config:/app/.heroku/python/lib/pkg-config: DEBUG_COLLECTSTATIC=1 BPLOG_PREFIX=buildpack.python PWD=/tmp/build_5f41d4f4 HOME=/app LANG=en_US.UTF-8 SOURCE_VERSION=ff7fb8a801cfb1de3d7b84e14312dbe284946333 REQUEST_ID=f6aa81af-75e0-afbc-a547-0f055efec989 ENV_DIR=/tmp/d20220120-46-2ziyj3 PYTHONPATH=. CPLUS_INCLUDE_PATH=/app/.heroku/vendor/include:/app/.heroku/python/include: BIN_DIR=/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin LIBRARY_PATH=/app/.heroku/vendor/lib:/app/.heroku/python/lib: SHLVL=1 LD_LIBRARY_PATH=/app/.heroku/vendor/lib:/app/.heroku/python/lib: PIP_NO_PYTHON_VERSION_WARNING=1 BUILDPACK_LOG_FILE=/dev/fd/3 STACK=heroku-20 BUILD_DIR=/tmp/build_5f41d4f4 CACHE_DIR=/tmp/codon/tmp/cache PATH=/app/.heroku/python/bin:/app/.heroku/vendor/bin::/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/ EXPORT_PATH=/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/../export C_INCLUDE_PATH=/app/.heroku/vendor/include:/app/.heroku/python/include: DYNO=run.3282 PROFILE_PATH=/tmp/build_5f41d4f4/.profile.d/python.sh OLDPWD=/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136 _=/usr/bin/env ! Push rejected, failed to compile Python app. ! Push failed This is my settings.py file: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-%d8=4wbz@n20@d6%4#0cw&)d&*ozxu#+$ctv$)mioc_tw(&-=0' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['dwek-portfolio.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates" ], '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 = 'my_site.wsgi.application' # Database … -
Using related_name in Django
I am getting confused with the usage of related_name in django models, i know that the idea is to give me access to all the fields of a different table with foreignkey i am just not sure how to use it. My model.py: class Component(MPTTModel): name = models.CharField(max_length=100) manufacturer = models.CharField(max_length=100) model = models.CharField(max_length=100) serial_number = models.CharField(max_length=255) price = models.IntegerField() note = models.TextField() image = models.ImageField(blank=True, null=True, upload_to='components_imgs') parent = TreeForeignKey("self", verbose_name=( "Parent Component"), blank=True, null=True, related_name='children', on_delete=models.CASCADE) def __str__(self): return f"{self.id}, {self.name}" class Job(models.Model): job_type = ( ('I', 'Interval'), ('O', 'One time'), ) name = models.CharField(max_length=100) description = models.CharField(max_length=100) type = models.CharField(max_length=1, choices=job_type) interval = models.IntegerField() is_critical = models.BooleanField() due_date = models.DateField() component = models.ForeignKey( Component, related_name='jobs', on_delete=models.CASCADE) runninghours = models.ForeignKey( RunningHours, related_name="RHjobs", on_delete=models.CASCADE) def __str__(self): return self.name my view.py: def worklist(request): components = Component.objects.all() Component_jobs = components.jobs.all() context = {"component":components, "Component_jobs":Component_jobs} return render(request,"worklist.html",context) I am trying to understand why these lines give me an error 'TreeQuerySet' object has no attribute 'jobs' components = Component.objects.all() Component_jobs = components.jobs.all() but these lines work just fine, component = Component.objects.all() component_id = Component.objects.get(id=pk) job_id = component_id.jobs.all() are they not the same but with one i am getting all the jobs for a … -
How can I make packages installed using Poetry accessible in Docker?
I have a Django REST framework API that I'm trying to run in Docker. The project uses Poetry 1.1.12. When running, I can see that Poetry is installed correctly, and that Poetry installs the packages in my pyproject.toml, including Django. I'm using supervisor to run the API using Daphne, as well as some other tasks (like collecting static files). However, when supervisor runs the app, I get: Traceback (most recent call last): File "/home/docker/api/manage.py", line 22, in <module> main() File "/home/docker/api/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Traceback (most recent call last): File "/home/docker/api/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' Notice how I set POETRY_VIRTUALENVS_CREATE=false and ENV PATH="/root/.local/bin:${PATH}". According to the poetry installation script, that is the path that needs to be added to PATH. Here is an abridged versioned of my Dockerfile: FROM python:3.9-slim-buster ENV PATH="/root/.local/bin:${PATH}" RUN apt-get update && apt-get install -y --no-install-recommends \ ... \ curl \ supervisor \ && curl -sSL 'https://install.python-poetry.org' | python - && poetry --version \ && apt-get remove -y curl \ … -
Communicate with a specific client [JS/PY]
I use angular client side (TS) and Django server side (PY). Unfortunately despite what I find on the internet, I can't send a message to a SPECIFIC client from the server. Socket.io doesn't exist in PY, I've seen the websockets but that only talks about sending a message to ALL clients in a group. But if I want to send a message only to a client B I don't see how to do it. Please help me, and guide me on the solution to use PS: I'm starting with the PY backend, be indulgent. Thank you. -
Django error: TypeError at /forums/ 'str' object is not callable
I am making a Django forums project and I have run into this issue. whenever I go to my forum page I see this error: TypeError at /forums/ 'str' object is not callable. If anyone knows how to fix this I would appreciate the help. forms: from django import forms from . import models class ForumForm(forms.ModelForm): class Meta: model = models.Post fields = ('message',) models from django.db import models # Create your models here. class Post(models.Model): message = models.TextField(blank=True, null=False) created_at = models.DateTimeField(auto_now=True) URLs from django.contrib import admin from django.urls import path, include from . import views app_name = 'forums' urlpatterns = [ path('', views.ForumForm.as_view(), name='forum') ] views from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from . import forms # Create your views here. class ForumForm(generic.CreateView): template_name = 'forums_simple/forum.html' form_class = 'ForumForm' success_url = '/' def form_vaild(self, form): self.object = form.save(commit=False) self.object.save() return super().form_vaild(form) -
Django isn't evaluating template variables
When I inspect the page I see: post="{% url daySlots %}" But Im expecting to see this evaluated to: post="/daySlots/" Its also ignoring other variables, the html shows the variable name like: {{ duration }} instead of the value like 1.5 that Im expecting. in my views.py the html code is generated in a function like: html_cal = Calendar(today.year, today.month, day_colors) context = { "html_cal": mark_safe(html_cal) } response = render(request, "pages/book.html", context) book.html looks like {% block content %} <div class="row"> {{ html_cal }} </div> {% endblock content %} The Calendar function also has some formatted text like: td = f"post=\"{{% url daySlots %}}\" Any ideas on how to get Django to recognize the variables within the html? -
How can I mock django model object?
For example, I have many interrelated tables in my project class A(models.Model): name = models.models.CharField(max_length=16) class B(models.Model): name = models.models.CharField(max_length=16) a = models.ForeignKey(A, on_delete=models.CASCADE) class C(models.Model): name = models.models.CharField(max_length=16) b = models.ForeignKey(B, on_delete=models.CASCADE) and so on. I need to test model C and have no interest in A and B models. Is there any chance to mock model B that can be used when creating model C objects? I mean I'd like to create few objects without building a massive test base to test one tiny model.