Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Coding in UpdateVIEW of django
I have a edit button on my webapp, that reference a UpdateView with Django. The problem is that i don't know a way to execute calculations before they save the change on the database on the UpdateView. When i create a register, he get save after pass trought some calculations, functions, etc, and to create he call this function: def post_create(request): form = InsereCursosForm() if(request.method == 'POST'): form = InsereCursosForm(request.POST) print(form) if(form.is_valid()): def calculos(): post_nmCurso = form.cleaned_data['nmCurso'] post_acFaculdade = form.cleaned_data['acFaculdade'] post_nuMaterias = form.cleaned_data['nuMaterias'] post_nmInstituicao = form.cleaned_data['nmInstituicao'] post_nmPlayer = form.cleaned_data['nmPlayer'] post_nuHoras = form.cleaned_data['nuHoras'] post_acWorkshop = form.cleaned_data['acWorkshop'] post_acImplementacao = form.cleaned_data['acImplementacao'] post_acComunik = form.cleaned_data['acComunik'] def seFaculdade(post_acFaculdade, post_nuMaterias, post_nuHoras): if post_acFaculdade == True: post_nuHoras = post_nuMaterias * 4 return post_nuHoras else: return post_nuHoras post_nuHoras = seFaculdade(post_acFaculdade, post_nuMaterias, post_nuHoras) def ptWorkshopsF(post_nuHoras, post_acWorkshop): if post_acWorkshop == True: v = post_nuHoras * Decimal('0.2') return v else: return 0 def ptImplementacaoF(post_nuHoras, post_acImplementacao): if post_acImplementacao == True: return post_nuHoras * Decimal('0.45') else: return 0 def ptComunikF(post_nuHoras, post_acComunik): if post_acComunik == True: return post_nuHoras * Decimal('0.1') else: return 0 getcontext().prec=2 post_ptHoras = float((Decimal(post_nuHoras * 0.45))/Decimal('1')) post_ptWorkshop = float(Decimal(ptWorkshopsF(post_nuHoras, post_acWorkshop))/Decimal('1')) post_ptImplementacao = float(Decimal(ptImplementacaoF(post_nuHoras, post_acImplementacao))/Decimal('1')) post_ptComunik = float(Decimal(ptComunikF(post_nuHoras, post_acComunik))/Decimal('1')) new_post = Cursos(nmCurso=post_nmCurso, acFaculdade=post_acFaculdade, nuMaterias=post_nuMaterias,nmInstituicao=post_nmInstituicao, nmPlayer=post_nmPlayer,nuHoras=post_nuHoras, ptHoras=post_ptHoras,acWorkshop = post_acWorkshop, ptWorkshop=post_ptWorkshop ,acImplementacao= post_acImplementacao, ptImplementacao=post_ptImplementacao,acComunik … -
Issue sending keys, values to django Q()
I am trying to filter some IDs using a django query and trying to do it efficiently, I want to get the same result I got from a less efficient function I created before, but I am getting an issue with the dictionary key using Q from tmd import models from django.db.models import Q category = { "utility": models.Account.UTILITY, "system": models.Account.SYSTEM } country = { "Guatemala": models.Country.objects.get(name='USA'), "Honduras": models.Country.objects.get(name='CA'), } def get_a(stage=None, **kwargs): base_args =[] base_args.append(Q(stage__in=stage)) for key, value in kwargs.items(): base_args.append(Q(key= value)) a_ids = models.Account.objects.filter(*base_args).values_list('id', flat=True) print("Number of a_ids: {}".format(a_ids.count())) return a_ids input: a_ids = get_a(country=country["USA"], category=category["utility"]) The issue is located exactly in this line: base_args.append(Q(key= value)) If I can make an input that changes the key for every iteration, this will be solved -
Automatically increasing the value of a variable in generate_series
I ran into the need to automatically increment the value of a variable in generate_series. By the condition of the business logic, the field identifier in the model does not increase automatically. I decided to try to find the maximum id value in advance and, within the of the generation, try to simply increase it by 1. But I don't understand how to do this correct. max_id = Companies.objects.aggregate(Max('id')) # {'id__max': 1529367} value = max_id['id__max'] cursor.execute(f''' INSERT INTO test.companies( id, name, city_id, revenue, labors ) SELECT {value} = {value}+1, # This is what I want, but I don't know how to do it ( SELECT x[1 + ((random() * 25)::INT) % 3] FROM ( SELECT '{{Google,Yandex,Amazon}}'::text[] ) AS z2(x) WHERE SEQ = SEQ ), (random() * 3000)::INT, (random() * 3000)::INT, (random() * 3000)::INT FROM generate_series(1,10) SEQ; ''') All this I do as part of my work for Python Django. -
I'm learning django, so i need a front end sites to create the back end of it, so how can i get a free one?
I'm learning Django, so I need a front end sites to create the back end of it, so how can I get a free one ? -
django - disable Invitation object creation if User object with the email exists
I'd like to make sure that nobody can't create an Invitation object with an email that is already in a database either as Invitation.email or as User.email. To disallow creating Invitation with existing Invitation.email is easy: class Invitation(..): email = ...unique=True) Is it also possible to check for the email in User table? I want to do this on a database or model level instead of checking it in serializer, forms etc.. I was thinking about UniqueConstraint but I don't know how to make the User.objects.filter(email=email).exists() lookup there. -
HTTPSConnectionPool(host='api.razorpay.com', port=443): Max retries exceeded with url: /v1/orders
I was developing a social-media/eCommerce web app with Django. I want to add a payment gateway for purchasing products on the website for that I am using 'Razorpay'. I integrated it which worked fine with my app. But I wanted to store the transaction-related details in a model called 'TransactionDetails'. For that, I call a new function within the view that handles the Razorpay gateway. which creates the instance of the model and saves it. But for some reason when I call that function I am getting this error, please help me to understand what is happening. here's my view : from django.shortcuts import render, redirect import razorpay from django.views.decorators.csrf import csrf_exempt from weShare.settings import razorpay_id, razorpay_secret_key from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin from django.urls import reverse_lazy from social.models import * from social.forms import * from .models import TransactionDetails from social.models import UserProfile client = razorpay.Client(auth=(razorpay_id, razorpay_secret_key)) def home(request, pk): rentee = UserProfile.objects.get(user=request.user) renteeName = rentee.user renteeLocation = rentee.location post = Post.objects.get(pk=pk) renter = post.author product = post.productName subPeriod = post.subscriptionPeriod montlycharge = post.productMonthlyCharge loc = rentee.location order_amount = post.deposite*100 order_currency = 'INR' order_receipt = 'order_rcptid_11' notes = {'Shipping address': 'Bommanahalli, Bangalore'} # OPTIONAL payment_order = client.order.create(dict(amount=order_amount, currency=order_currency, payment_capture=1)) payment_order_id = … -
python Django Postgres Setup (with docker) .. Trying to make migrations for postgres but make file is failing
so its my first time building a stack from scratch i am trying to connect to postgres for better management but i am sure i have an error in my docker file or make file can any body shed some light on this for me ? code below make file build: docker build --force-rm $(options) -t bonkit_websites:latest . build-dev: $(MAKE) build options="--target development" compose-start: docker-compose up --remove-orphans $(options) compose-stop: docker-compose down --remove-orphans $(options) compose-manage-py: docker-compose run --rm $(options) website python manage.py $(cmd) docker.yml version: "3.8" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_USER: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: tty: true image: bonkit_websites:latest command: python manage.py runserver 0.0.0.0:8000 volumes: *service-volumes enviroment: *app-variables depends_on: - db_migrate ports: - "8000:8000" db_migrate: image: bonkit_websites:latest command: python manage.py migrate volumes: *service-volumes enviroment: *app-variables depends_on: - postgres postgres: image: postgres ports: - "5432:5432" enviroment: - db-data:/var/lib/postgresql/data Docker File FROM python:3.9.7-slim as production ENV PYTHONBUFFERED=1 WORKDIR /app/ RUN apt-get update && \ apt-get install -y \ bash \ build-essential \ gcc \ libffi-dev \ musl-dev \ openssl \ postgresql \ libpq-dev COPY requirements/prod.txt ./requirements/prod.txt RUN pip install --user -r ./requirements/prod.txt COPY manage.py .manage.py #COPY setup.cfg ./setup.cfg COPY bonkit_website ./bonkit_website EXPOSE … -
How to render reverse fields using related name between foreign key models
I have two models if a foreign key relationship and a related name. I return a queryset of Foo and want to render fields of the related object Bar. However, item.link.value doesn't render anything. # Models class Foo(models.Model): item class Bar(models.Model: foo = models.Foreignkey(Foo, on_delete=models.CASCADE, related_name='link') value = models.Charfield(max_length=20) # View def test(request): qs = Foo.objects.all() context = { 'qs': qs } return render (request, 'somepage.html', context) # Template {% for item in qs %} <div> {{ item.link.value }} </div> -
Need help writing tests - Django framework
I am relatively new to Python with Django, and very new to writing tests. The app I'm working with allows a teacher to assign multiple assignments to a student. On the student dashboard, an assignment should only be available if the start date <= today's date. The student should only see the first assignment in the list. I need to compose tests to cover the following: create a few new assignments with different start dates and assign them to the currently logged in student use the same query that is used for the student dashboard to make sure that the only assignments returned are the ones with a start date <= today's date make sure that the only assignment the student sees on the dashboard is the one with the earliest start date Below I have posted the assignment code from models.py, as well as views.py code that shows what displays on the student dashboard. Please let me know if additional code is needed to help me get started with this. I would like to only use the built in django.test features to write my tests for now, if possible. Thanks very much for any help you can offer! models.py … -
Reload Form when select change
Is there a way to reload a form data in django when I change a select? I am trying to filter a select depending on the option selected in another without using ajax. What comes to mind is to use the __init__ of the form but I need to reload the form with the option selected in the first select and filtered the second. -
Gitlab returns Permission denied (publickey,password) for digitalocean server
I'm trying to implement CD for my dockerized Django application on the DigitalOcean droplet. Here's my .gitlab-ci.yml: image: name: docker/compose:1.29.1 entrypoint: [""] services: - docker:dind stages: - build - deploy variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 before_script: - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - export WEB_IMAGE=$IMAGE/web:web - export NGINX_IMAGE=$IMAGE/nginx:nginx - apk add --no-cache openssh-client bash - chmod +x ./setup_env.sh - bash ./setup_env.sh - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY build: stage: build script: - docker pull $IMAGE/web:web || true - docker pull $IMAGE/web:nginx || true - docker-compose -f docker-compose.prod.yml build - docker push $IMAGE/web:web - docker push $IMAGE/nginx:nginx deploy: stage: deploy script: - mkdir -p ~/.ssh - echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa - cat ~/.ssh/id_rsa - chmod 700 ~/.ssh/id_rsa - eval "$(ssh-agent -s)" - ssh-add ~/.ssh/id_rsa - ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts - chmod +x ./deploy.sh - scp -o StrictHostKeyChecking=no -r ./.env ./docker-compose.prod.yml root@$DO_PUBLIC_IP_ADDRESS:/Pythonist.org - bash ./deploy.sh only: - master I have copied my Publick key to the production server (DO droplet). The build job is successful but the deploy stage failed with the following error: $ chmod 700 ~/.ssh/id_rsa $ eval "$(ssh-agent -s)" Agent pid 26 $ ssh-add ~/.ssh/id_rsa Identity added: /root/.ssh/id_rsa (abdul12391@gmail.com) $ ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts … -
Django mod_wsgi Apache Server, ModuleNotFoundError: No Module Named Django
I read ton of articles, but still can't figure out what I'm missing. I'm running a django website from virtualenv. Here's my config file. The website address is replaced by <domain.com>, can't use that here. Config <VirtualHost *:80> ServerAdmin sidharth@collaboration-management ServerName <domain.com> ServerAlias <domain.com> DocumentRoot /home/sidharth/Downloads/gmcweb ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/sidharth/Downloads/gmcweb/static <Directory /home/sidharth/Downloads/gmcweb/static> Require all granted </Directory> <Directory /home/sidharth/Downloads/gmcweb/gmcweb> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess gmcweb python-home=/home/sidharth/Downloads/gmcwebenvlin python-path=/home/sidharth/Downloads/gmcweb WSGIProcessGroup gmcweb WSGIScriptAlias / /home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py </VirtualHost> Here's my WSGI.py file, didn't change anything never had to earlier import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gmcweb.settings') application = get_wsgi_application() Python Versions My virtualenv python version is 3.9.5 Default Google VM python version is 3.6.9 I installed apache modwsgi as well sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3 Error Log File [Thu Sep 23 15:05:06.554545 2021] [mpm_event:notice] [pid 32077:tid 140392561593280] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Thu Sep 23 15:05:06.554594 2021] [core:notice] [pid 32077:tid 140392561593280] AH00094: Command line: '/usr/sbin/apache2' [Thu Sep 23 15:05:19.081581 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] mod_wsgi (pid=32617): Target WSGI script '/home/sidharth/Downloads/gmcweb/gmcweb/wsgi.py' c$ [Thu Sep 23 15:05:19.081638 2021] [wsgi:error] [pid 32617:tid 140392409851648] [remote 103.206.177.13:49604] mod_wsgi (pid=32617): Exception occurred processing WSGI script '/home/sidharth/Downloads/g$ … -
How to run django-appointment project which is available in this site's github?https://pypi.org/project/django-appointments/ please help me
How to run django-appointment project which is available in this site's github?https://pypi.org/project/django-appointments/ -
How to add values for checked rows using javascript
I've uploaded a similar question in a previous post, but I'm re-posting because what I'm trying to achieve is a little clearer. We are outputting the list of students as a table. If we check the checkbox and click the Add Teacher button, we want the name of the currently logged in teacher to be added to the teacher field of the selected row. You can get the name of the currently logged in account with {{request.user.name}} . And I want it to be saved in DB by sending it to the server. <table class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Teacher</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td>{{ student.techer }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Add Techer" class="addtecher"> Current student information is modified as follows. urls.py path('student/<int:id>/edit/', views.edit_student, name='edit_student') views.py def edit_student(request, id): student = get_object_or_404(Student, pk=id) edited_student, errors = Student.student_form_validation(request) if errors: return JsonResponse({'code': 'error', 'error': … -
how can i connect django container to mysql container
Hi i want to connect django - mysql in each container :) i tried a lot of way but failed.. here is my mysql docker-compose.yaml version: "3" services: db: platform: linux/x86_64 image: mysql:5.7 container_name: good-mysql ports: - "3307:3306" environment: - MYSQL_ROOT_PASSWORD=test - MYSQL_DATABASE=testdb command: - --character-set-server=utf8mb4 - --collation-server=utf8mb4_unicode_ci volumes: - /Users/Shared/data/mysql-test:/var/lib/mysql network_mode: bridge i used mysql official image and my django Dockerfile FROM ubuntu:18.04 FROM python:3.8.6-buster ENV PYTHONUNBUFFERED 1 # General Packages RUN apt-get update \ && apt-get install -y libmariadb-dev \ && apt-get install -y python3-pip \ && apt-get install -y build-essential \ && apt-get install -y libcurl4-openssl-dev \ && apt-get install -y libssl-dev \ && pip install --upgrade pip RUN mkdir -p /project/myproject COPY ./myproject /project/myproject RUN mkdir -p /app WORKDIR /app RUN pip install -r requirements.txt CMD tail -f /dev/null and docker-compose.yaml version: '3.8' services: deepnatural-ai-api: build: . image: deepnatural-ai-api:latest container_name: deepnatural-ai-api ports: - 1000:1000 external_links: - "good-mysql:db" network_mode: bridge and i run docker-compose up -d each container and access mysql container, run mysql -uroot -p its work! but when i access django container run migrations its raise error connection 'default': (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") my django settings.py is ALLOWED_HOSTS … -
Django url issue if included trailing slash
I have this url in one of the Django app with trailing slash path('quiz/timeupdate/',updateTime.as_view(),name='timeupdates') and i'm calling this via javascript post method using navigator.sendBeacon. This as well has a trailing slash navigator.sendBeacon('http://127.0.0.1:8000/quiz/timeupdate/',form_data) it is showing me this error Not Found: /quiz/timeupdate/ if i remove trailing slash from both python and javascript then it works fine else it throws the above error -
Sending Email with Attached file in DJango Restful Framework (DRF)
I want to attach a file to an email message and send it to a specific email address. I am using DJango Restful framework to create the API endpoint. I have tried to follow the documentation and some guide, but I keep on hitting a rock. I get this error: def send_comment_mail_notification(request, space, target_email): message = request.POST.get('description', '') subject = request.POST.get('comment_cat', '') from_mail = space.email to = target_email msg = EmailMessage(subject, message, from_mail, [to],) image = request.FILES['file'] msg.attach(image.name, image.read(), image.content_type) msg.content_subtype = "html" msg.send() This is my models.py class Comment(BaseModel): comment_cat = models.ForeignKey( "admincat_user.CommentCategory", on_delete=models.CASCADE) description = models.TextField(max_length=512) file = models.FileField(upload_to="./comment", blank=True, null=True) Here is my Seriliazers.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = models.Comment fields = "__all__" read_only_fields = ("created_at", "updated_at") Here is my view.py class CommentViewSet(BaseViewSet): permission_classes = (BelongToSpace,) serializer_class = serializers.CommentSerializer queryset = models.Comment.objects.all() def callback(self, **kwargs): send_comment_mail_notification(self.request, self.space, "a.a@emial.com") my urls.py routes.register('comments', views.CommentViewSet, 'comments') Please, what am i missing or need to do to make it work -
При перезапуске контейнера обнуляется БД
Проект сосотит из контейнеров django + nginx + postgresql Запускаю через docker-compose -f dc.yml up -d --build И каждый раз после внесения правок в django приложения, чтобы применить их я перезапускаю сборку, но при этом и пересобирается контейнер БД(или это не так работает?), и база становится полностб пустой. Как мне правильно поступить, чтобы не заполнять БД каждый раз по 10 раз? -
check_password not verifying database stored password successfully
I am using Python 3.9.7 and DJango 3.2.7 Issue details Following code is being used to verify the submitted password. I can confirm that the submitted password has a valid value and user.password is hashed password stored in the database. passwordCheckResult = check_password(request.POST.get("password"), user.password) print(passwordCheckResult) Why does it always return None? What did I search so far Django check_password() always returning False but this is not fixing my issue I was wondering why the below code works and not above one... hashed = make_password("123") check_password("123", hashed) //this returns True -
Optimal way of calling model method while iterating a large queryset in Django
I have an example model as follows: class MyModel(models.Model): #model fields def my_model_method_1(self, *args): #logic for the method. This involves reverse lookup, fk fetching and calculations def my_model_method_2(self, *args): #logic for the method. This involves reverse lookup, fk fetching and calculations Now I am generating an excel file that has the data of the above model. I am querying the model using filter and values. my_model_filter = MyModel.objects.filter(fk_field_1__in=list_of_fk_1_field_ids) my_model_data = my_model_filter.values(all_fields_here) my_args = {"start_date": some_start_date, "end_date": some_end_date} for my_model in my_model_data: model_id = my_model["id"] my_model_object = my_model_filter.get(id=my_model_id) val_1 = my_model_object.my_model_method_1(**my_args) val_2 = my_model_object.my_model_method_2(**my_args) # other logic # the above methods are called again for other calculations. Then the whole data is then converted to excel file. The problem is that calling and getting these methods is taking time. Infact for about 10k instances it is taking about 30 mins to generate the report. I have identified that more time is taking when these methods are called. So is there anyway where i can speed up calling these methods? One way that I reduced the time for my_model in my_model_data: model_id = my_model["id"] my_model_object = my_model_filter.get(id=my_model_id) val_1 = my_model_object.my_model_method_1(**my_args) val_2 = my_model_object.my_model_method_2(**my_args) my_model["val_1"] = val_1 my_model["val_2"] = val_2 for my_model in … -
How to set Debug=False and Allowed_hosts in Django without Http error 500
I would like to publish my website made in Django with Debug=False setting. However, this gives me error 500. I did my best but it still doesn't work. Here is what I already tried: I went through this question: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False I learnt I need to add allowed_hosts but neither localhost, *, nor the link to my website worked. I tried to collect staticfiles. It did not help. My project is on heroku and heroku collects all staticfiles authomatically by itself. There might be some problem with setting of whitenoise, but I am not able to run debug=False even locally. You can find all my code here: https://github.com/eliska-n/elinit/tree/master. Here I share my settings.py file. Django settings for elinit project. Generated by 'django-admin startproject' using Django 3.2.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import django_heroku import dj_database_url from decouple import config # 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production … -
Django: How to get and save a foreign key field in POST method
I am try to save a data in two models Booking and Event. The first one working well but I get error in the Event, I don't know how to get and save the foreign key data. This is my Event model: class Event(models.Model): def __str__(self): return self.title title = models.CharField(max_length=200) description = models.TextField(blank=True) start_time = models.DateTimeField() end_time = models.DateTimeField(blank=True, null=True) place = models.CharField(max_length=200,blank=True) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, blank=True,null=True) doctor = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) And this is my views: def registerBooking(request): if request.method == 'POST': form = BookingForm(request.POST) place = request.POST.get('place','') visit_type = request.POST.get('visit_type','') description = request.POST.get('description','') patient = request.POST.get('patient','') doctor = request.POST.get('doctor','') created_at = request.POST.get('created_at','') if form.is_valid(): new_booking = form.save() new_event = Event(title=visit_type,description=description,start_time=created_at,place=place,patient=patient,doctor=doctor) new_event.save() return JsonResponse({"msg":"Booking and Event successfully saved."}) #return redirect(reverse('dashboard')) else: return JsonResponse({"msg":"Invalid data"}) else: form = BookingForm() return render(request, 'patient/register_booking.html', {'form':form}) new_booking is working but the problem is in new_event, I get this error: "ValueError: Cannot assign "'1'": "Event.patient" must be a "Patient" instance." -
Show specific data based on a parameter django
Hi everyone I have a question, I want to show the information for an specific pokemon when I type its name on the url (ex: http:/0.0.0.0:8000/pokemon/Pikachu) I can display all the information in the model but not the one that belongs to that specific name, how can I do it? Here's my view class PokemonView(APIView): """Pokemon API View""" def get(self, request): """Returns the pokemon information""" pokemon_info = Pokemon.objects.all() serializer = PokemonSerializer(pokemon_info, many=True) return Response(serializer.data) And this one is my serializer class PokemonSerializer(serializers.ModelSerializer): """Transform the pokemon data (model) into a json""" class Meta: model = Pokemon fields = '__all__' Thanks -
ImportExportModelAdmin gives error django.template.exceptions.TemplateDoesNotExist: admin/import_export/change_list_import_export.html
i am trying to make admin panel such that services and service_price must appear on same page Like this And As Clicking on Services on django admin panel I am getting this error Error: Traceback (most recent call last): File "C:\Users\PycharmProjects1\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\PycharmProjects1\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\PycharmProjects1\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\PycharmProjects1\venv\lib\site-packages\django\template\response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "C:\Users\PycharmProjects1\venv\lib\site-packages\django\template\response.py", line 65, in resolve_template return get_template(template, using=self.using) File "C:\Users\PycharmProjects1\venv\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: admin/import_export/change_list_import_export.html Here is my Code: Admin.py: from import_export.admin import ImportExportModelAdmin class ServicePriceInline(admin.TabularInline): model = ServicesPrice @admin.register(Services) class ServicesAdmin(ImportExportModelAdmin): inlines = [ ServicePriceInline ] search_fields = ['service_name'] Models.py: class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,related_name='sub_service') service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) service_description = models.CharField(max_length=5000, null=True, blank=True) category_id = models.ForeignKey(Category,on_delete=models.CASCADE) active_status = models.BooleanField(default=True) type = models.SmallIntegerField(blank=True, null=True) class ServicesPrice(models.Model): price_id = models.AutoField(primary_key=True) service_id = models.ForeignKey(Services,on_delete=models.CASCADE) variant_id = models.ForeignKey(Variant,on_delete=models.CASCADE) price_name = models.CharField(max_length=100, null=True, blank=True) price_description = models.CharField(max_length=5000, null=True, blank=True) discount_percentage = models.FloatField(null=True, blank=True) discount_amount = models.FloatField(null=True, blank=True) active_status = models.BooleanField(default=True) -
how to reduce Django text field height
I am Creating Ordering Form Where I need to Add Location in TextField. I Want To Know How To Reduce TextField Height class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) organisation = models.ForeignKey(UserProfile,null=True, blank=True, on_delete=models.SET_NULL) foodlancer = models.ForeignKey("Agent", on_delete=models.CASCADE) catagory = models.ForeignKey("Catagory", related_name="leads" ,null=True, blank=True, on_delete=models.SET_NULL) date_added = models.DateTimeField(auto_now_add=True) phone_number = models.CharField(max_length=20) email = models.EmailField() location = models.TextField(max_length=250) persons = models.IntegerField(max_length=100) Right Now It's Just Like That: And I Want To Do Like That: