Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration error: Applying migrations throws an error, and querying 'flight.objects.all()' results in an error as well
I'm facing an issue with my Django project where I encounter errors when trying to apply migrations using python manage.py migrate and when executing flight.objects.all(). Here's the code: from django.db import models # Create your models here. class Flight(models.Model): origin = models.ForeignKey('airport', on_delete=models.CASCADE, related_name="departure") destination = models.ForeignKey('airport', on_delete=models.CASCADE, related_name="arrival") duration = models.IntegerField() def __str__(self): return f"{self.origin} to {self.destination}" class Airport(models.Model): city = models.CharField(max_length=64) code = models.CharField(max_length=3) def __str__(self): return f"{self.city} ({self.code})" The Flight table previously had two Character fields instead of foreign keys and I had stored a row in it but later I decided use Airport table as a foreign key in Flight table. However after I exited the shell and tried to run "python manage.py migrate" I got an error: django.db.utils.IntegrityError: The row in table 'flights_flight' with primary key '1' has an invalid foreign key: flights_flight.origin_id contains a value 'Kathmandu' that does not have a corresponding value in flights_airport.id. I figured it might be because of the previously stored data in the Flight table so i tried to delete it, however i cant even view the contents of the Flight table. Whenever i try running "flight.object.all()" i get another error: django.db.utils.OperationalError: no such column: flights_flight.origin_id Can anyone help … -
Django user.set_password(password) is not hashing the password
I have wrote Custom user Model in Django everything is working fine except password is not being hashed when but when I had created the superuser password was hashed here are my models for custom user and custom user manager model.py() class CustomUser(AbstractUser): email = models.EmailField(_("email address"), null=False,blank=False,unique=True) USERNAME_FIELD='email' REQUIRED_FIELDS = ["username"] object=CustomUserManager() class CustomUserManager(UserManager): def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self,username ,email, password, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user( username,email, password, **extra_fields) def create_superuser(self,username, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(username, email, password, **extra_fields) should i use this from django.contrib.auth.hashers import make_password and how to use this -
How to handle ForeingKey fields in DRF serializer
I have 2 models with ForeignKey relation class Order(models.Model): ip = models.CharField(max_length=15) ref_code = models.CharField(max_length=15) is_ordered = models.BooleanField(default=False) class OrderItem(models.Model): product = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) quantity = models.IntegerField(default=1) size = models.ForeignKey(Size ,on_delete=models.CASCADE, related_name='sssize', default = None) order = models.ForeignKey(Order, related_name="item", on_delete=models.CASCADE) This is my serializer class CreateOrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem exclude = ('is_ordered',) def create(self, validated_data): order_item, created = OrderItem.objects.update_or_create( product = validated_data.get('product',None), quantity = validated_data.get('quantity', None), size = validated_data.get('size',None), ) return order_item I need to somehow get or create Order object base on ip (which i get from request) and is_ordered fields and pass it to serializer or do it in view I have tried to add order field in view.py after i get my serialized data but i get an error saying that order field is required View.py def post(self, request, pk): serializer = CreateOrderItemSerializer( data=request.data, ) print(serializer.initial_data) if serializer.is_valid(): product = serializer.save() ip = get_client_ip(request) order = Order.objects.get_or_create(ip = ip, is_ordered = False) product.order.add(order.id) Or need i get ip strait from POST method JSON? -
Unknown field(s) (client_value, client_name) specified for Client. Check fields/fieldsets/exclude attributes of class ClientDataAdmin
I have a model that I want to add to my admin pages. The model class is. class Client(models.Model): FBUSER = "FBU" GOOGLEUSER = "GU" FBACCESSCODE = "FBAC" GOOGLESECRET = "GS" MISC = "MISC" CLIENT_KEY_CHOICES = [ (FBUSER, "Facebook User ID"), (FBACCESSCODE, "Facebook Access Code"), (GOOGLEUSER, "Google User"), (GOOGLESECRET, "Google Secret"), (MISC, "Misc"), ] client_key = models.CharField( max_length=4, choices=CLIENT_KEY_CHOICES, default=FBUSER, ) id = models.BigAutoField(primary_key = True), client_name = models.CharField(max_length=100, blank=True, null = True), client_value = models.CharField(max_length=100, blank=True, null = True), and my admin.py is class ClientDataAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['client_key', 'client_name', 'client_value' ]}), ] list_display = ('client_name', 'client_key', 'client_value') search_fields = ['client_name'] I have looked at several similar error explanations and fixes but none fit, this case. I have other models and admin scripts that work fine, but I cannot find anything wrong here. The admin page shows the add link but I get the following error when I hit it... Unknown field(s) (client_value, client_name) specified for Client. Check fields/fieldsets/exclude attributes of class ClientDataAdmin. Request Method: GET Request URL: http://localhost:8000/admin/kdconnector/client/add/ Django Version: 4.1.7 Exception Type: FieldError Exception Value: Unknown field(s) (client_value, client_name) specified for Client. Check fields/fieldsets/exclude attributes of class ClientDataAdmin. I suspect it comes from the choices … -
Why is my breakpoint in Django not activated when I use a custom authentication backend
I have a custom user authentication back end in Django so I can make a user log in with email and or username. I placed a break point in the in the authenticate method but it is not firing so I can check why the authenticate method is returning None all the time. I changed the settings to include: AUTHENTICATION_BACKENDS = ["users.backends.EmailOrUsernameBackend"] Here is the view to handle the login: from django.contrib.auth import authenticate @api_view(["POST"]) def LoginUser(request): email = request.data.get("email") username = request.data.get("username") password = request.data.get("password") exists = User.objects.filter(email=email).exists() if exists: user = User.objects.get(email=email) if user.is_active and user.email_verified_at is None: authenticated = authenticate(email=email, username=username, password=password) if authenticated is not None: serializer = LoginSerializer(authenticated) token, created = Token.objects.get_or_create(user=user) return Response( {"id": serializer.data["id"], "Authorization": token.key, "role": user.role}, status=HTTP_200_OK, ) else: return Response("Wrong email and/or password", status=HTTP_401_UNAUTHORIZED) else: return Response("Account is not active! Did you change your email and haven't confirmed it?") else: return Response("Email is not registered, please register") Here is the custom backend to authenticate the username, or email and password: class EmailOrUsernameBackend(ModelBackend): def authenticate(self, **kwargs): breakpoint() email = kwargs.get('email') username = kwargs.get('username') password = kwargs.get('password') if email: try: user = User.objects.get(email=email) except User.DoesNotExist: return None elif username: try: user = … -
Best way to old "version" of specific parameters on django model
I want to do a "version control" kind of thing. I have a django model called "Person" I also have a method of updating all persons "gender" and "language" according to "detection" version. this method improves from version to version. I dont want to "detect" gender of person in latest version to not over use resources, each detection cost ... my method need to run over all persons with gender version 1 or language version 1 and update the person lang and gen to version 2 (run the method). so the simple is: class Person(models.Model): phone = models.CharField(max_length=50, blank=True, null=True) phone_version = int ... language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) language_version = int ... but I have also 20 more filters (like gen and lang) so I prefer to have one attribute named version, so I could filter also in a simple way. if I do ManyToManyField to class Version it will be slow to do filters, right ? class Person(models.Model): phone = models.CharField(max_length=50, blank=True, null=True) language = models.ManyToManyField( "instagram_data.Language", verbose_name=_("language_code_name"), blank=True) version_control = models.ManyToManyField(DetectionVersion ...) class DetectionVersion(models.Model): phone_version = int ... language_version = int .. is the second fast and a good solution ? -
Wrong distance between two points in Geodjango
I have user class: class User(AbstractBaseUser): location = PointField(srid=4326) and I calculate distance between two points in serializer this way: obj.location.distance(request.user.location) * 100 For example I have two points: POINT(-95.3385 29.7245) POINT(-85.3385 29.7245) One point is for authorized user the other is for the other user. Serializer returns 1000 kilometers. I don't know what is latitude and longitude and it doesn't matter because in online calculators in one case it is a little bit more than 1000 km and in the other - a little bit less than 1000 km. And it is never 1000 km. Any ideas why this is happening? -
Calling javascript functions in static, Django
Im struggling to understand why I cant call a javascript function when my Bootstrap button is clicked in Django. I have created the static folder in my directory "main/static/main/js/script.js" I am able to load the static css file for boostrap without any issues, but for whatever reason the javascript function "testing()" cant be called. Web browser console logs as Uncaught ReferenceError: testing is not defined onclick. Am i suppose to use AJAX instead, or is there simply something wrong with my settings or url path. my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATICFILES_DIRS = [BASE_DIR /'main/static'] STATIC_URL = '/static/' my scripts.js function testing() { alert("Button clicked!"); } my index.html, that is using bootstrap: {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>MoviePicks</title> <!-- Core theme CSS (includes Bootstrap)--> <link rel="icon" type="image/x-icon" href="{%static 'main/assets/favicon.ico'%}" /> <link href="{%static 'main/css/styles.css'%}" rel="stylesheet" /> </head> <body id="page-top"> <!-- Header--> <header class="bg-dark bg-gradient text-white"> <div class="container px-4 d-flex flex-column align-items-center text-center"> <!--code to play … -
How to save multiple product ID from cart to Order table under one Order ID?
I tried to do this with my own coding based on the internet and chatgpt. However it only save one item from the cart. Can somebody help me?? (p/s : I used ManyToMany field for ProdID under Order table to save multiple products from Cart page) models.py (i put the null = True bcs i just want to focus on the orderID functionality) class Cart(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE) item_qty = models.IntegerField(default=1) class Customer(models.Model): CustID = models.CharField(max_length=100, primary_key = True) CustName = models.TextField() CustAdd = models.TextField() CustPhone = models.TextField() class Order(models.Model): OrderID = models.CharField(max_length=100, primary_key = True) ProdID = models.ManyToManyField(Product) CustID = models.ForeignKey(Customer, on_delete = models.CASCADE, null=True) totalprice = models.FloatField(null=True) ordered_date = models.DateTimeField(auto_now_add=True) payment = models.TextField(null=True) paystatus = models.CharField(max_length=50,default='Pending') coding related to my problem in cartpage.html <form action="{% url 'placeorder' %}" method="get"> {% csrf_token %} <tbody> <tr> {% for cart in cart %} <td><button pid = "{{ cart.product.ProdID }}" class="remove-cart btn"><ion-icon name="close-outline"></ion-icon></button></td> <input type="hidden" name="prodid" value="{{cart.product.ProdID}}" id="prodid" class="prodid"> <td class="w-5"><image src="{{ cart.product.ProdPic.url }}" style="height:80px; width:65px;" class="rounded-circle"></td> <td>{{cart.product.ProdName}}</td> <td class="cart-product-quantity"> <input type="button" pid = "{{ cart.product.ProdID }}" class="minus-cart btn btn-light btn-circle btn-sm" value="-"></input> <span id="quantity" min="1">{{ cart.item_qty }}</span> <input type="button" pid = "{{ cart.product.ProdID }}" class="plus-cart btn btn-light btn-circle … -
How to make calorie goal dynamic in my django app that user can input according to them?
https://github.com/geetanshpardhi1/FitCalorie The above link redirects you to my repo where you can find code. In myapp/index.html (line no.127) I have added functionality for the calorie goal which is hardcoded for value 2000 and I want to make it dynamic for each user, how can I do it? My doubt is in which model do I have to add a goal field and how can I integrate HTML input with it? -
Budgeting feature for django ecommerce web app
Can anyone help me with login to build a budget feature within a ecommerce platform. i have this project I am designing for my final year project but i want to design a page where user can find multiple product within a specific price. Let say the user want to a shirt, bag and shoe but have 7000, I want the app to return all the three product that can be bought with 7000. -
Django - Display specific attribute of object in <Select> in template
I have the following Python models: class Usuario(models.Model): login = models.CharField(max_length=200) senha = models.CharField(max_length=200) meta = models.ManyToManyField('meta', through='Usuario_meta') def __str__(self): return f'id: {self.id} - login: {self.login} - senha: {self.senha}' class Meta(models.Model): tipo = models.CharField(max_length=200) def __str__(self): return f'id: {self.id} - senha: {self.tipo}' class Usuario_meta(models.Model): usuario = models.ForeignKey(Usuario,on_delete=models.CASCADE) meta = models.ForeignKey(Meta,on_delete=models.CASCADE) data = models.DateField() valor = models.IntegerField() def __str__(self): return f'Meta do usuário: {self.usuario} - meta:{self.meta} - data:{self.data} - valor: {self.valor}' The following view: class UsuarioMetaCreate(CreateView): model = Usuario_meta template_name = 'lancamento_meta_cadastro.html' fields = '__all__' The following html: <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Submit" /> </form> Which displays the following: I would like to show, in the "usuario" select, only the attribute "login". Apparently, it calls the 'str()' and displays all the fields. Is there a way to show only a specific attribute while using CreateView and without modifying the 'str()' method? I have already tried using <form action="" method="post"> {% csrf_token %} {{form.usuario.login}} <input type="submit" value="Submit" /> </form> But it doesn't display anything -
How to use python
How to solve this question using Python. Does anyone try to help me to solve this question? I'm trying to solve this question but it is not working properly. -
Dynamically create periodic tasks or one time tasks - django celery beat
We have multiple scripts written in different lang ( Python, shell, golang ) and so on. I am trying to create a centralized application, where any user can create periodic tasks or one time tasks using django/celery. Basically the idea is user1 -> python test.py arg user2 -> ./test.sh arg1 arg2 The idea is not to pre defined tasks and dynamically create tasks. is it possible ?? any lead or blog should be helpful. -
DRF: Serializer update method returns KeyError during partial update, instead of ValidationError raised by model clean() method
In Django Rest Framework, I'm testing one of the endpoints for proper exception handling. A ValidationError is expected but instead a KeyError is returned. I've been trying to debug this case for a while now so here's the step-by-step breakdown of what happens: Step 1: Incoming data gets serialized: class BatchIdView(APIView): ... def patch(self, request, batch_id): ... serializer = BatchSerializer(batch, data=data, partial=True) if not serializer.is_valid(): return Response(data=humps.camelize(serializer.errors), status=status.HTTP_400_BAD_REQUEST) There are no custom validators in this serializer and data is validated during this step (is_valid() method returns True) Step 2: Attempting to update the object (actually this code comes directly following previous snippet): try: serializer.update(batch, serializer.validated_data) except ValidationError as e: return Response(data=humps.camelize(e.messages), status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response(data={"error": str(e)}, status=status.HTTP_501_NOT_IMPLEMENTED) Step 3: During the update() method, model's save() method triggers validation: class Batch(models.Model): ... def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) def clean(self): if self.product_type in ["..."] and self.model is not None: raise ValidationError({"model": "error text goes here"}) I've double-checked that this raise ValidationError() line gets triggered in that particular test case. Step 4: Instead of returning the validation error, the serializer decides to trigger to_representation() method which is customized and is checking for another field: def to_representation(self, instance): … -
FileField doesn't upload when deploying on server
I'm deploying a Django app on my server. On my local machine, it works fine. I've also been able to access site thanks to Caddy and running the python runserver 0.0.0.0:8000 command as a systemd service. When I now try to upload a file to my server via the form that I have created, the file doesn't get uploaded. My forms.py: class EntryForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Title'})) modelMedium = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}), required=False) modelLarge = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class': 'form-check-input'}), required=False) file = forms.FileField(required=True) timeStamps = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Time Stamps in seconds'}), required=True) def __str__(self): return self.title class Meta: model = Entry fields = ['title', "modelMedium", "modelLarge", "file", "timeStamps"] The corresponding part of view.py: def upload(request): if request.method == "POST": form = EntryForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Uploaded successfully!") return redirect("home") else: messages.success(request, "Invalid form!") return redirect("upload") When looking at journalctl, I'm not getting any error messages, Django gives me the message "Uploaded successfully", and the entry into my model is made correctly (even with the file name), but the file does not exist when I check the directory. I checked all the permissions for the folders that I am referencing and they are all set correctly (or I assume … -
I am implementing Django email sender, however , it is giving me an error that some module is not found
Following is the error: ModuleNotFoundError: No module named 'django.core.mail.backends.smpt' views.py: def register_patient(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone= request.POST['phone'] pic = request.POST['picture'] print(name) patient = Patient(name=name, email=email, phone=phone, photo=pic) patient.save() subject = "Thank you for registering" message = "Welcome the the clinic." from_email = settings.EMAIL_HOST_USER recipient_list = [email] send_mail(subject, message, from_email, recipient_list) print("fsfsdf") return render(request, "thanks_reg.html",{"name" : name}) imports: from django.core.mail import send_mail from django.conf import settings I have imported django.core.mail. Perhaps, it reqiures some other module to be imported -
In Django, given an instance of Model A, how to define a relation between two instances of model B?
What (I think) I'm trying to achieve is to create a new column in my database (resp. a new field in my model) for model B every time there is a new instance of model A. To clarify, say I have the following model in Django : class Unit(models.Model): unit = models.CharField(max_length=200) with two instanciations : Kilograms and Volume (m^3). I'm looking to specify the following class: class Object(models.Model): object = models.CharField(max_length=200) # Field to relate `Volumes` to `Kilograms`, as a float so that I'm able to declare the relation between Kilograms and Volume (m^3) for each specific object. In a way, I'm trying to declare a float that relates the volume for each kilogram of the object (or vice-versa). I could use a workaround and add a FloatField if I knew Kilograms and Volume would be the only instances of Unit, but unfortunately, there might be others. PS: Additional (less important) question: Could I select a default unit, and declare the other ones compared to that default unit. Something like the following: class Object(models.Model): object = models.CharField(max_length=200) default_unit = models.ForeignKey(Unit, on_delete=models.CASCADE) # Field to compare unit_1 to default_unit # Field to compare unit_2 to default_unit # And so on … -
Translate model field names in Django Rest Framework serializers
How to translate model field names in Django Rest Framework serializers. I am working on a django project and django rest framework(DRF) and I need to return the translated fields of a model in french if the user selects 'french' or in english if the user selects 'english'. So how to do that, please? I tried to translate field names in the serializer using gettext_lazy from django.utils.translation import gettext_lazy as _ class TranslatedCharField(serializers.CharField): def get_field_names(self, declared_fields, info): field_names = super().get_field_names(declared_fields, info) translated_field_names = [str(_('title')).lower() if field_name == 'title' else field_name for field_name in field_names] return translated_field_names class PostSerializer(serializers.ModelSerializer): title = TranslatedCharField() class Meta: model = Post fields = ['title','about'] I tried to that using some third party packages such as: drf-extensions django-rest-framework-translate django-rest-framework-translate but still not working... -
Some translations are not getting translated
I have this in my admin.py: class SomeAdmin(admin.ModelAdmin): @admin.display(description=_('Cases %(year)d') % {'year': previous_year}, ordering='cases_previous_year') def previous_year(self, inv_presidency): ... some code ... and this in app/locale/ar/LC_MESSAGES/django.po #: case_tracking/gdoi/case_movements/admin.py:313 msgid "Cases %(year)d" msgstr "قضايا %(year)d" everything is getting translated, except the one mentioned above!! why is that? Thanks -
in Django, how can i pass data from a DetailsView class from a form in a UpdateView?
Im doing a "To Do" list in Django, the problem is that im trying to make a update in each task, but when i click the button "Actualizar" (Update), i want the form in that view comes pre fill with details of the task im updating (like title, description, status, expiring date and tags), and as all of you can see, the form comes with nothing in it. gif of the problem Here is part of my code: In "views.py" class DetalleTarea(LoginRequiredMixin, DetailView): model = Tarea context_object_name = 'Tarea' template_name = 'templates_app/app_1/detalle_tarea.html' class ActualizarTarea(LoginRequiredMixin, UpdateView): model = Tarea form_class = TareaForm template_name = 'templates_app/app_1/crea_actualiza_tarea.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) etiquetas = Etiqueta.objects.all() context['etiquetas'] = etiquetas estados = Tarea.estado context['estados'] = estados return context def get_success_url(self): return reverse_lazy('detalle_tarea', kwargs={'pk': self.object.pk}) In "urls.py" from django.urls import path from . import views from .views import VistaLoginCustom, ListaTareas, DetalleTarea, CrearTarea, ActualizarTarea from django.contrib.auth.views import LogoutView urlpatterns = [ path('', views.home, name='home'), path('login/', VistaLoginCustom.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('lista_tareas/', ListaTareas.as_view(), name='lista_tareas'), path('lista_tareas/tarea_n_<int:pk>/', DetalleTarea.as_view(), name='detalle_tarea'), path('crear_tarea/', CrearTarea.as_view(), name='crear_tarea'), path('actualiza_tarea/tarea_n_<int:pk>/', ActualizarTarea.as_view(), name='actualiza_tarea'), ] In "detalle_tarea.html" <div class="container"> <div class="row"> <div class="col-md-6 offset-md-3"> <div class="card mb-3"> <a href="{% url 'lista_tareas' %}" class="text-decoration-none"><svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="blue" class="bi … -
django cannot export and import javascript variables in static files
I have static files in django call it A.js and B.js in A.js I have for example for constant like const variable = "Hello, World" export {variable} **in B.js I have:** import {variable} from './A.js' Kindly note that both files are in the static files directory of django project. My question is how am I going to import successfully the variable so that it checks into variable and use them in the template without getting exceptions Uncaught SyntaxError: Unexpected token 'export' and the whole JS does not work -
Email is not sending in django code as well as it is not giving any error in the console
I am implementing a code to send email. However, the code is not sending the email and also it is not showing any tangible error. views.py code: @require_POST def thanks(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone= request.POST['phone'] doctor = request.POST['doctor'] msg = request.POST['reason'] print(name, email, phone, msg) appointment_db = Appointment(name=name, email=email, phone=phone, doctor=doctor, message=msg) appointment_db.save() subject = "Thank you for registering" message = "Welcome the the clinic." from_email = settings.EMAIL_HOST_USER recipient_list = [email] send_mail(subject, message, from_email, recipient_list) print("email sent") return render(request, "thanks.html", {"name": name}) In the above code, the second-last line is also not printing anything in the console. settings.py: EMAIL_BACKEND= "django.core.mail.backends.smpt.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT= 587 EMAIL_HOST_USER = "host email" # email from which i sent email EMAIL_HOST_PASSWORD = "host password" #password of the host account imports in views.py: from django.core.mail import send_mail from django.conf import settings It is basically a registration form which is sending confirmation email to the person who is attempting to register.strong text -
How to submit a form embedded within Folium HTML Popup in python
I am developing a web app in Django/Folium/Python to add markers to the map and I want to click on the marker and a popup appears with a form to be filled out and submitted. I have successfully developed that app but the submission does not work. If I add the URL inside the code it gives me this error: Encountered unknown tag 'url' This is my code in Python: def monitoring(request, pk): map = folium.Map(location=[lat, lng], zoom_start=15) html = f"""<form action="{% url 'index' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="note heading">Note heading</label> <input type="text" name='note_heading' class="form-control"> </div> <input type="hidden" name="lat" value="${lat}"> <input type="hidden" name="lng" value ="${lng}"> <div class="form-group"> <label for="note">Note</label> <textarea class='form-control' name="note_des" >Enter note here</textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form>` """ iframe = folium.IFrame(html, width=200, height=200) popup = folium.Popup(iframe) # , max_width=100) marker = folium.Marker([lat, lng], popup, draggable=True).add_to(map) map = map._repr_html_() context = {"lat": lat, "lng": lng, "map": map} return render(request, "maps/monitoring.html", context) -
Add a custom admin action in Django when an object in another model is created
I wanted to implement one functionality in my Django application such that a custom admin action is created whenever an object is created in some other model. For e.g. I have one model as Semester: class Semester(models.Model): name = models.CharField(_("Semester Name"), max_length=30, default=None, null=True, blank=True, help_text="Name of the semester") def __str__(self): return self.name and another model as UnregisteredStudent: class UnregisteredStudent(models.Model): email = models.CharField(_("email"), max_length=30, default="") semester= models.ForeignKey(Semester, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return str(self.email) In the UnregisteredStudent table I have emails filled up and am using custom admin actions to add semester field to each object in UnregisteredStudent table. My custom admin action in UnregisteredStudent looks like: @admin.action(description="Add Semester as Semester 1") def semester1(self, request, queryset): semester = Semester.objects.get(name="Semester 1") for obj in queryset: obj.semester= semester obj.save(update_fields=["semester"]) Now as I have done this for semester 1, as and when new semester objects are created I would need new such admin actions like: @admin.action(description="Add Semester as Semester 2") def semester2(self, request, queryset): semester = Semester.objects.get(name="Semester 2") for obj in queryset: obj.semester= semester obj.save(update_fields=["semester"]) Right now I have to add custom admin actions manually in my admin.py, but I suppose this might not be the correct approach to the problem as in …