Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Node.js vs something else?
i need develop a airport transfer service website. I just look up on internet and find a few course and all build by node.js on backend. i wonder should I build that website by using node.js or do you have any other suggestions? That website will book car and assignment driver depending client choose, a kind of primitive Uber but client should appointment at least one day ago. -
Django - Default value based on another model field
This is my existing django model class Account(models.Model): env = CharField(max_length=10) now I need to add period field to my model based on the value of the env field in model. I can get the period value based on the env from following dict in my settings file mydict = { 'dev':1, 'prd':2 } How do I add my period field to model? period = Integerfield(default=setvalue from dict) -
why are only some css classes being generated in tailwind?
I have a project where I'm using Django as backend and tailwind for the css. tailwind is not giving me any errors and is finding classes in my files but not generating the css. the only class that its working for is bg-blue-500 and nothing else. if anyone could think of why this may be happening or how to fix is I would really appreciate it. html page {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Auctions{% endblock %}</title> <link rel="stylesheet" href="{% static 'auctions/output.min.css' %}"> </head> <body> <h1>Auctions</h1> <div> {% if user.is_authenticated %} Signed in as <strong>{{ user.username }}</strong>. {% else %} Not signed in. {% endif %} </div> <ul class="nav"> <li class="nav-item bg-red-500"> <a class="nav-link" href="{% url 'activeListings' %}">Active Listings</a> </li> {% if user.is_authenticated %} <li class="nav-item bg-blue-500"> <a class="nav-link" href="{% url 'logout' %}">Log Out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Register</a> </li> {% endif %} </ul> <hr> {% block body %} {% endblock %} </body> </html> tailwind.css @tailwind base; @tailwind components; @tailwind utilities; @layer base { h1 { @apply text-4xl; } h2 { @apply text-3xl; } h3 { @apply … -
I want to add this database of login users on my home page can anyone tell me how should i do this in python djago
[enter image description here][1] [1]: https://i.stack.imgur.com/qW49M.png this is the databasestrong text**** -
I am not able to use FPDF correctly in python in Django
Right now I need your help. When it comes to use fpdf in django I have several confusing problems, here I am going to give you my source code and you understand my situation. I tried several solutions but they were not proper clue. issue: I am going to create pdf and use method called FPDF().output("name.pdf") as it is, even I tried with open("name.pdf", mode="w") as file: as well and when i execute the FPDF().output("name.pdf") using django, it raises traceback called "no such file or drectory" Thanks from advance! class Resume: def __init__( self, personal_details: dict, work_experience: dict, education: dict, final_section: dict ): self.personal_details = personal_details self.work_experience = work_experience self.education = education self.final_section = final_section self.pdf_file = FPDF() def _normalize(self, slicer: str, limit: int) -> list: self.education = self.education summary = [] portion = '' temp = 0 for j in slicer.split(" "): if temp != limit: portion += j + " " else: summary.append(portion.strip()) portion = '' temp -= temp temp += 1 return summary def template_one(self, filename: str): path = str(pathlib.Path().resolve()).split("\\") full_path = "" for j in path: full_path += j + "/" personal_details_log = [ "Fullname:", "Email:", "Phone Number:", "City:", "Postal Code:" ] detail = [ "fullname", … -
How to Start Django Server on a remote host via robotframework .robot file?
How to Start Django Server on a remote host via robotframework .robot file? I tried robotframework-djangolibrary still not working on remote host, but local it's working. I tried executing manage.py runserver command but didn't work for remote again. Now in the picture i placed files in remote srever and executing this file automatically. Still no success enter image description here -
Why i can’t login using my login template
I am using a login template to log in to staff and non-staff members but the login page only allows the staff members or you can say superusers to login in which also logs me into the admin page, but I want to log in into the web app that I am using, not the admin page be it staff or non-staff for logging in. Is there any way to solve this issue? And yes I have already added: AUTH_USER_MODEL = "accounts.Account" LOGIN_REDIRECT_URL = "blogs" LOGOUT_REDIRECT_URL = "blogs" urls.py from django.urls import path from .views import CustomLogoutView, CustomRegistrationView, CustomLoginView urlpatterns = [ path("register/", CustomRegistrationView.as_view(), name="register"), path("login/", CustomLoginView.as_view(), name="login"), path("logout/", CustomLogoutView.as_view(), name="logout"), ] views.py from django.contrib.auth.views import LoginView, LogoutView from django.urls import reverse_lazy from django.views.generic import CreateView from accounts.models import Account from .forms import CustomRegistrationForm, CustomLoginForm class CustomRegistrationView(CreateView): model = Account form_class = CustomRegistrationForm success_url = reverse_lazy("login") redirect_authenticated_user = True template_name: str = "accounts/register.html" success_message = "You registered successfully." class CustomLoginView(LoginView): model = Account form_class = CustomLoginForm redirect_authenticated_user: bool = True success_url = reverse_lazy("dashboard") template_name: str = "accounts/login.html" class CustomLogoutView(LogoutView): template_name: str = "accounts/logout.html" next_page = None manager.py from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user( self, email, first_name, last_name, roll_no, … -
python virtual env overrides my ckeditor customized configuration
I need to customize my python-3.7/django-3.2/mezzanine-6.0/django-ckeditor-5.6.1 application just the same way as instructed here: how to add custom templates in django-ckeditor in django I modified the file <myStaticRoot>/ckeditor/ckeditor/plugins/templates/templates/default.js as explained, but didn't get the change in my web page before modifying also the corresponding file in my python virtual environment: <myvenv>/lib/python3.7/site-packages/ckeditor/static/ckeditor/ckeditor/plugins/templates/templates/default.js This is a very ugly trick, how can I prevent the python virtual environment from overriding my application specific settings ? -
To force use python3.9 after install libapache2-mod-wsgi-py3 django
I installed libapache2-mod-wsgi-py3 but It seems good for python3.6. My problem is set mod-wsgi for use python3.9 because my app django has all modules installed for this version. How can I do? I attach error log [Fri Oct 21 10:22:21.549718 2022] [wsgi:error] [pid 8227] mod_wsgi (pid=8227): Target WSGI script '/var/www/html/elastic_queries/python/djangosite/giustiziasite/giustiziasite/wsgi.py' cannot be loaded as Python module. [Fri Oct 21 10:22:21.549795 2022] [wsgi:error] [pid 8227] mod_wsgi (pid=8227): Exception occurred processing WSGI script '/var/www/html/elastic_queries/python/djangosite/giustiziasite/giustiziasite/wsgi.py'. [Fri Oct 21 10:22:21.550458 2022] [wsgi:error] [pid 8227] Traceback (most recent call last): [Fri Oct 21 10:22:21.550517 2022] [wsgi:error] [pid 8227] File "/var/www/html/elastic_queries/python/djangosite/giustiziasite/giustiziasite/wsgi.py", line 18, in <module> [Fri Oct 21 10:22:21.550522 2022] [wsgi:error] [pid 8227] application = StaticFilesHandler(get_wsgi_application()) [Fri Oct 21 10:22:21.550528 2022] [wsgi:error] [pid 8227] File "/usr/local/lib/python3.6/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Fri Oct 21 10:22:21.550532 2022] [wsgi:error] [pid 8227] django.setup(set_prefix=False) [Fri Oct 21 10:22:21.550537 2022] [wsgi:error] [pid 8227] File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 24, in setup [Fri Oct 21 10:22:21.550541 2022] [wsgi:error] [pid 8227] apps.populate(settings.INSTALLED_APPS) [Fri Oct 21 10:22:21.550546 2022] [wsgi:error] [pid 8227] File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 114, in populate [Fri Oct 21 10:22:21.550550 2022] [wsgi:error] [pid 8227] app_config.import_models() [Fri Oct 21 10:22:21.550555 2022] [wsgi:error] [pid 8227] File "/usr/local/lib/python3.6/dist-packages/django/apps/config.py", line 301, in import_models [Fri Oct 21 10:22:21.550558 2022] [wsgi:error] [pid … -
Change select field options in client script in NetSuite
I have a client script runs on Suitelet. On Suitelet we have a sublist which has many select columns. Let's say we have Select 1 and Select 2. Select 2 options should be different if you change the option in Select 1. Could this be done in Client Script? or in that Suitelet? Any help would be appreciated. ` var select1= sublist.addField({ id: 'custpage_select1', label: 'Select1', type: ui.FieldType.SELECT }); var select2= sublist.addField({ id: 'custpage_select2', label: 'Select2', type: ui.FieldType.SELECT }); ` In client script when the field is changed, I want to change options of Select 2 depend on Select 1. function fieldChanged(scriptContext){ if(scriptContext.fieldId=="custpage_select1"){ let page = currentRecord.get(); var select2 = page.getField({fieldID:"custpage_select2"}); select2.removeSelectOption({value:"value1"}); } } But this shows me an error that Cannot read properties of null Thank you -
Django And Elasticsearch
I am evaluating the opportunity to include some elasticSearch indexes in our Django Backend, I reviewed so far three django apps: django-elasticsearch-dsl elasticsearch-django django-haystack So far, I can't tell if there is such a package not needing to replicate content of the indexes in the django DB, from what I read, it seems like we have to have some standard Relational DB ORM objects attached to each indexes. If I am right, that then implies the data duplication, and potentially a huge one in our case. Is there a way with the mentioned packages to avoid this objects duplication? Or did I misread the whole thing and it's not actually duplicating data? Thanks for your insights! Marc -
how to set values using aftersubmit function in create mode
I need to set the values while creating the inventory item form, I deployed the script in the corresponding form, and it is working as I tried to send an email. For this, it is working, But I don't know when I tried but nothing happened. <!-- /** *@NApiVersion 2.0 *@NScriptType UserEventScript */ define(["N/url", "N/record", "N/runtime"], function (url, record, runtime) { function afterSubmit(context){ var recordobj = context.newRecord; var Type=context.type; if(Type== context.UserEventType.CREATE) recordobj.setValue({ fieldId:'custitem27', Value:'something', }); } return{ afterSubmit:afterSubmit } }); --> -
How can i Migrate users from admin to my sqlite date base
i made the code to add users in the ADMIN panel, but i would like to have those users in a data base, how can i do that (could be in my data base sqlite made it by django? or i have to create a model to create users in my data base (but how can i login them after that)? -
Django connection with Sybase SQL Anywhere 17 with pyodbc on Digital Ocean App Platform
I need help with connecting to the Sybase SQL Anywhere database via the pyodbc library. When I am running a local development server or local python desktop script connection is established easily and successfully. I found out that the problem is in the SQL Anywhere 17 driver. In the scripts below you can see that when I run pyodbc.drivers() in a local environment I get a list with a few drivers, and when I repeat the same in the App platform application console I get an empty list. My question is how can I install or transfer SQL Anywhere 17 driver to the App platform or ubuntu droplet? Thank you! views.py code connection_string = "Driver=SQL Anywhere 17;" \ "Server=xxx;" \ "Host=host;" \ "UID=user;" \ "PWD=pass;" \ "DBN=db_test;" \ "Port=xxxx;" \ "DSN=xxxx;" \ "dobroadcast=all;" \ "APPINFO=xxx;" def my_view(request): rows = [] with pyodbc.connect(connection_string) as conn: cur = conn.cursor() cur.execute('SELECT NAZIV1 FROM ARTIKEL') rows = list(cur.fetchall()) return render(request, 'app/my_template.html', {'rows': rows}) -
Razorpay Signature Verification faild
I am trying to integrate Razorpay into my django-rest-framework application. I am following this article. I am able to create Orders successfully. But not able to do the payment. You can directly see the whole code in github repository. views.py from django.shortcuts import render from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .constants import PaymentStatus import json import razorpay from .models import Order client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET)) def home(request): return render(request, "index.html") def order_payment(request): if request.method == "POST": name = request.POST.get("name") amount = request.POST.get("amount") razorpay_order = client.order.create( {"amount": int(amount) * 100, "currency": "INR", "payment_capture": "1"} ) order = Order.objects.create( name=name, amount=amount , provider_order_id=razorpay_order["id"] ) order.save() return render( request, "payment.html", { "callback_url": "http://" + "127.0.0.1:8000" + "/razorpay/callback/", "razorpay_key": settings.RAZORPAY_KEY_ID, "order": order, }, ) return render(request, "payment.html") @csrf_exempt def callback(request): def verify_signature(response_data): return client.utility.verify_payment_signature(response_data) print(f'first request.POST: {request.POST}') print(f'input {request.body}') if "razorpay_signature" in request.POST: payment_id = request.POST.get("razorpay_payment_id", "") provider_order_id = request.POST.get("razorpay_order_id", "") signature_id = request.POST.get("razorpay_signature", "") order = Order.objects.get(provider_order_id=provider_order_id) order.payment_id = payment_id order.signature_id = signature_id order.save() print(f'signature verification: {verify_signature(request.POST)}') if not verify_signature(request.POST): order.status = PaymentStatus.SUCCESS order.save() return render(request, "callback.html", context={"status": order.status}) else: order.status = PaymentStatus.FAILURE order.save() return render(request, "callback.html", context={"status": order.status}) else: payment_id = json.loads(request.POST.get("error[metadata]")).get("payment_id") provider_order_id = json.loads(request.POST.get("error[metadata]")).get( "order_id" ) order = … -
Django AJAX Get Request from Client Side
I am very new to Django and trying to learn sending an ajax request with id to Django server HTML <input class="search-input" type="search" placeholder="Search..." onkeyup="filterCars(this.value)"/> JS <script> function filterCars(str) { let xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "/?id="+str, true); xmlhttp.send(); } </script> Django url: urlpatterns = [ path('',views.index), path('<str:id>', views.getCar) ] Django views: def getCar(request): fileJs = serializers.serialize("python", CarModel.objects.all()) id = request.query_params["id"] print(id) return render(request, 'index.html', {'fileJs': fileJs}) For now my issue is that the id is not printing and seems I am not accessing it properly. This is the response I get in terminal: "GET /?id=h HTTP/1.1" 200 425559 Thanks a lot in advance! -
How to display name of city instead of id?
I have 2 models: class City(models.Model): name = models.CharField(max_length=50, default='') def __str__(self): return self.name class Street(models.Model): name = models.CharField(max_length=50) city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return f"{self.city}: {self.name}" And i want to display all streets of city by url: path('city/<int:pk>/street/', views.CityDetail.as_view()) The following View: class CityDetail(APIView): def get(self,request, pk, format=None): city = City.objects.get(id = pk) # try except for DoesNotExist streets = Street.objects.filter(city=city) serializer = StreetSerializer(streets, many=True) # Name instead of id! return Response(serializer.data) How to display name of cit instead of id? [{"id":1,"name":"Почтовая","city":1},{"id":2,"name":"Ленина","city":1},{"id":3,"name":"Быстрецкая","city":1}] -
Python Django +WhatsApp bot + Twilio ,use regex to match URL of different papers .I
I am building a WhatsApp bot that when grade 12 students type subject year and paper 1 or 2 ,the bot goes to saexams.co.za find a matching URL and then download paper and memo .All the URLs to the papers are like this https://saexampapers.co.za/wp-content/uploads/2021/09/Mathematics-NSC-P1-QP-Sep-2021-Eng.pdf but have different IDs after the year like '/09/' which range from 1 to 10 . how can i use regex to search for url with matching ID .code smaple is below. def bot(request): #message =request. POST["body"] if request.POST: message = request.POST["Body"] sender_name = request.POST["ProfileName"] number = request.POST['From'][9:] print(number) print(sender_name) print(request.POST) if message =="hi" or message =='Hi' or message =='Hello' or message=='Hie': message = client.messages.create( from_='whatsapp:+14155238886', body='Hello there {} , I am Nkosi Ncube BOT . I only assist you to download math papers .This is how you type the paper you want - Mathematics P2 Sep 2021'.format(sender_name), to='whatsapp:{}'.format(number) ) elif 'Mathematics' in message : message = request.POST["Body"].replace(" ","") sender_name = request.POST["ProfileName"] url1 =f'https://saexampapers.co.za/wp-content/uploads/{message[16:]}/09/{message[:11]}-NSC-{message[11:13]}-QP-{message[13:16]}-{message[16:]}-Eng.pdf' url2=f'https://saexampapers.co.za/wp-content/uploads/{message[16:]}/09/{message[:11]}-NSC-{message[11:13]}-Memo-{message[13:16]}-{message[16:]}-Eng.pdf' print(url1) print(url2) download = wget.download(url1) download2 = wget.download(url2) print(message) url_list =[url1,url2] for i in range(0,2): message = client.messages.create( from_='whatsapp:+14155238886', media_url = url_list[i], to='whatsapp:{}'.format(number) ) else: message = client.messages.create( from_='whatsapp:+14155238886', body='Sorry {} i dont understand try to rephrase'.format(sender_name), to='whatsapp:{}'.format(number) ) return HttpResponse("hello") … -
QuerySet Django, need to get multiple result on one
I got this model : class BfMatchingNafRome(models.Model): code_naf = models.CharField(null=False,max_length=255) libelle_naf = models.CharField(null=True,max_length=255) code_rome = models.CharField(null=True,max_length=255) I want to put some data in a table. {% for match in matching %} <tr> <th scope="row">{{match.code_naf}}</th> <td>{{match.libelle_naf}}</td> <td> {% for i in match.code_rome %} {{i}} {% endfor %} </td> {% endfor %} I use : matching = BfMatchingNafRome.objects.filter(code_naf__lte=activity.code_activity).order_by('code_naf') I've tried absolutely all I can find on stack overflow, google, youtube, but I cant link my datas. I just get, on my view, one line with code_naf - code_rome. I want one line per code_naf with all code_rome for this code_naf. I create multiple entries (for an other view I need one data by entry). But, for this view, I need to receive datas linked. Thanks for help -
How to make work javascript in template in django
I'm trying to use js to save values in selected options. It works if js put it in my HTML template. Like this: {% load static %} {% include "header.html" %} {% block content %} <script src="{% static 'ReportingTool/js/sort_text.js' %}"></script> <script src="{% static 'ReportingTool/js/sort_number.js' %}"></script> ... <form method="GET" action="."> <div class="row"> <div class="border border-2 p-2 g-2"> <label for="periodMin">Start date</label> <input type="date" class="myselect form-select form-select-sm" id="periodMin" name="period_min"> <label for="periodMax">End date</label> <input type="date" class="myselect form-select form-select-sm" id="periodMax" name="period_max"> </div> <div class="border border-2 p-2 g-2"> <label for="structDivisions">Structural divisions</label> <select id="structDivisions" class="myselect form-select form-select-sm" name="struct_division"> <option selected>Choose...</option> {% for SD in struct_divisions %} <option id="{{ SD.id }}" value="{{ SD }}"> {{ SD }}</option> {% endfor %} </select> <label for="workers">Worker</label> <select id="workers" class="myselect form-select form-select-sm" name="worker"> <option selected>Choose...</option> {% for worker in workers %} <option value="{{ worker }}">{{ worker }}</option> {% endfor %} </select> </div> <div class="border border-2 p-2 g-2"> <label for="workDone">Work done</label> <select class="myselect form-select form-select-sm" id="workDone" name="work_done"> <option selected>Choose...</option> {% for work in workstype %} <option value="{{ work }}">{{ work }}</option> {% endfor %} </select> <label for="scope_min">Scope min</label> <input type="number" min=0 class="myselect form-control form-control-sm" id="scope_min" name="work_scope_min"> <label for="scope_max">Scope max</label> <input type="number" min=0 class="myselect form-control form-control-sm" id="scope_max" name="work_scope_max"> <label for="notes">Notes contains</label> <input type="text" class="myselect … -
Websocket connection issue on django production server
I am facing an issue with the WebSocket protocol. I am using Django channels/daphne. Everything is working normally on the development local server. I think the issue is with NGINX settings. The error code is 1006 Here is the reverse proxy that I am using: location ~* \.(js|css|jpg|png|jpeg|html)$ { try_files $uri $uri/ /; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; #Persistent connection related configuration add_header X-Cache $upstream_cache_status; #Set Nginx Cache proxy_ignore_headers Set-Cookie Cache-Control expires; add_header Cache-Control no-cache; expires 12h; } location /ws/ { proxy_pass http://127.0.0.1:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } #PROXY-END/ -
How to get() the non-numeric primary key field's value during model save
I am trying to catch the primary key field's value during model save using: def save(self, *args, **kwargs): if self.pk: # For some post processing, I am trying to catch the instance "ID", and make changes to fields cls = self.__class__ old = cls.objects.get(pk=self.pk) # Getting current model state. << Error occurs here new = self # Newly instantiated model object with new values. # ... # ... This works fine if I have the following model definition (primary key as Integer): class myModel(models.Model): some_fld_id = models.AutoField(primary_key=True, verbose_name='... However, if I use a charField as the primary key like so: class myModel(models.Model): some_fld_id = models.CharField(primary_key=True, max_length=6, ... It fails with error: myModel matching query does not exist. And points to the line with: old = cls.objects.get(pk=self.pk) Now due to some constraints, I am to define the primary_key as a charField (and still be able to catch the pk value). How can I achieve this. -
Docker Django Is the server running on that host and accepting TCP/IP connections?
I'm running Django app on Docker container, the problem is it can't see the database connection is already up. Dockerfile FROM ubuntu RUN apt-get update # Avoid tzdata infinite waiting bug ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Africa/Cairo RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN apt -y install certbot python3-certbot-apache RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN apt -y install software-properties-common RUN add-apt-repository universe RUN apt update RUN ln -sf /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd RUN apt install wait-for-it RUN a2enmod headers RUN service apache2 restart COPY www/demo_app/water_maps/requirements.txt requirements.txt RUN pip install -r requirements.txt ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 5432 WORKDIR /var/www/html/demo_app docker-compose.yaml version: "2" services: db: image: postgres restart: always volumes: - ./data/db:/var/lib/postgresql/data ports: - '5332:5432' environment: - POSTGRES_DB=(db name here) - POSTGRES_USER=(db user here) - POSTGRES_PASSWORD=(db password here) django-apache2: build: . container_name: test_water_maps restart: always environment: - POSTGRES_DB=(db name here) - POSTGRES_USER=(db user here) - POSTGRES_PASSWORD=(db password here) ports: - 5000:80 - 5001:443 volumes: - ./www/:/var/www/html - ./www/demo_app/kml_files:/var/www/html/demo_app/kml_files - ./www/demo_app/temp_kml_file:/var/www/html/demo_app/temp_kml_file - ./www/demo_app/upload:/var/www/html/demo_app/upload command: sh -c 'wait-for-it db:5432 -- python manage.py migrate && apache2ctl -D FOREGROUND' # command: sh -c 'wait-for-it db:5432 -- … -
def send_confirmation_email coming up with error of nonetype
As I'm not using webhooks in my latest project, I need to setup function for sending confirmation emails when user places an order. However it always comes up with an error of Attribute Error : 'NoneType' object has no attribute 'user' What am I doing wrong here? def send_confirmation_email(order): """ Send email to customer with order confirmation """ cust_email = order.user_profile.user.email subject = render_to_string( 'checkout/confirmation_emails/confirmation_email_subject.txt', {'order': order}) body = render_to_string( 'checkout/confirmation_emails/confirmation_email_body.txt', {'order': order, 'contact_email': settings.DEFAULT_FROM_EMAIL}) send_mail( subject, body, settings.DEFAULT_FROM_EMAIL, [cust_email] ) -
Extra fields on many-to-many relationships: How to automatically create the "through" fields?
I'm trying to use a many to many field in order to add a set of facilities to a lead. The trouble is that i need an extra field for the date and time of the tour scheduled for each of the facilities i add to the lead. So when i create a lead and add facilities to the lead i have that extra field where i can enter date and time and access it afterwards as a list of facilities with their tour dates on the leads page. I came across many to many fields using "through" but I'm not sure if that's even the right option to use in this case. ManyToMany Fields with extra fields How can i use a many to many field using "through" and have the through field automatically be generated for each facility i add to my lead with the many to many field? Or is using through not a good option? I'm using Django Rest Framework with a React Frontend: models.py class Facility(models.Model): Name = models.CharField(max_length=150, null=True, blank=False) mainimage = models.ImageField(null=True, blank=True) Email = models.EmailField(max_length=150, null=True, blank=True) TelephoneNumber = models.CharField(max_length=30, null=True, blank=True) FacilityDescription = models.TextField(max_length=1000, null=True, blank=True) def __str__(self): return self.Name class …