Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
how to make unique field exception message on django
I have a create document form which has only two fields first, title second, a foreign key to Note model. Now i want to make the document title unique so i used; title = models.CharField(max_length=32, default='document-title', unique=True) Well it works! but it doesnt show any feedback that new Document couldnt created... here is the documentation i tried to follow: https://docs.djangoproject.com/en/4.2/topics/forms/modelforms/#considerations-regarding-model-s-error-messages forms.py from django import forms from django.forms import ModelForm from .models import Document class DocumentForm(ModelForm): class Meta: model = Document fields = {'title',} labels = {'title': '',} widgets = {'title': forms.TextInput(attrs={'placeholder': 'document_title'}),} error_messages = { NON_FIELD_ERRORS: { "unique_together": "model name is not unique.", } } i tought it would display a message right next to the input field but it doesnt show anything... I want to have a display under/next to the input field how can i do it? -
How to solve mypy error for django abstract class?
I have the next django abstract class, describing preview mixin: from django.core.files.storage import default_storage from django.db import models from sorl.thumbnail import get_thumbnail class PreviewMixin(models.Model): preview = models.ImageField(blank=True, null=True) class Meta: abstract = True def _get_preview_thumbnail(self, geometry_string: str, crop: str = 'noop', quality: int = 100) -> str: preview = '' if self.preview: thumbnail = get_thumbnail(file_=self.preview, geometry_string=geometry_string, crop=crop, quality=quality) preview = default_storage.url(name=thumbnail) return preview When I am running mypy, I get an error: error: "DefaultStorage" has no attribute "url" [attr-defined] My code works correct for me without errors. What should I fix or add or update to pass this mypy checking? Versions of packages are: django 4.2.2 mypy 1.4.1 django-stubs 4.2.3 django-stubs-ext 4.2.2 sorl.thumbnail 12.9.0 mypy.ini [mypy] python_version = 3.11 plugins = mypy_django_plugin.main, mypy_drf_plugin.main exclude = .git, .idea, .mypy_cache, .ruff_cache, node_modules check_untyped_defs = true disallow_untyped_decorators = true disallow_untyped_calls = true ignore_errors = false ignore_missing_imports = true implicit_reexport = false local_partial_types = true no_implicit_optional = true strict_optional = true strict_equality = true warn_unused_ignores = true warn_redundant_casts = true warn_unused_configs = true warn_unreachable = true warn_no_return = true [mypy.plugins.django-stubs] django_settings_module = 'settings' -
I am adding the div-container class after the header but its being displayed at top of the page
I am adding the div-container class after the header but its being displayed at top of the page. Basically we are trying to add the class div-container after the header our doctors but what happens is it is being displayed else where. we have base.html and this file extends that enter image description here. {% extends 'pages/base.html' %} {% block content %} <section class="home" id="home"> <div class="slideshow-container"> <div class="mySlides fade"> <img src="images/img1.jpg" alt=""> <div class="text">Caption Text</div> </div> <div style="text-align:center"> <span class="dot" onclick="currentSlide(1)"></span> </div></div> <div class="content"> <h3>we take care of your healthy life</h3> <p>Maintaining good health will ultimately lead to a happy mind which is more valuable than any precious gift in today’s life. Having a healthy life must be a part of everyone’s lifestyle. If one has a healthy and happy mind, then one will always stay motivated towards one’s work and will be productive at work.</p> <a href="#" class="btn">Learn More </a> </div> </section> <!-- home section ends --> <!-- Table section starts --> <section class="Table-container"> <div class="cell"> <div class="cell"> <th> <td><p class="tooltip">doctors at work<span class="tooltiptext">Top 5 doctors in our hospital. 1. Dr. Siddhartha Mukherjee – Biologist. 2. Dr. Naresh Trehan – cardiothoracic surgeon. 3. Dr. Sudhansu Bhattacharyya – Cardiac … -
Reset password validation link
def reset_password_validate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64).decode() user = User._default_manager.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): request.session['uid'] = uid messages.info(request, 'Reset your Password') return redirect('reset-password') else: messages.error(request, 'Link is Expired') return redirect('my-account') when the link is clicked it gives the messages.error, i need it to redirect to the reset password page -
Does django support using the @use keyword to import scss files?
I've been trying to make use of the @use keyword to import scss files but when django compiles the imported files don't show up but the @import keyword works well. I used the @use keyword but all the imported files didn't show up. until i used the @import keyword and it worked perfectly. -
django-debug-toolbar :Loading module from was blocked because of a disallowed MIME type (“text/plain”)
I've just installed django-debug-toolbar in my project and unfortunately in browser I've encounter with bellow error in browser side and toolbar couldn't display! Loading module from was blocked because of a disallowed MIME type (“text/plain”). -
How to link a css file and a html file for a django website template?
I have a css code and a html file exported from my figma design templates. Idk if I want to combine this css and html to have them in my django website. I'm not someone who knows anything about css plus just a bit of html, I'm learning python. Please let me know if I should do any additional work. -
Indexing a SearchVector vs Having a SearchVectorField in Django. When should I use which?
Clearly I have some misunderstandings about the topic. I would appreciate if you correct my mistakes. So as explained in PostgreSQL documentation, We need to do Full-Text Searching instead of using simple textual search operators. Suppose I have a blog application in Django. Entry.objects.filter(body_text__search="Cheese") The bottom line is we have "document"s which are our individual records in blog_post field and a term "Cheese". Individual documents are gonna be translated to something called "tsvector"(a vector of simplified words) and also a "tsquery" is created out of our term. If I have no SearchVectorField field and no SearchVector index: for every single record in body_text field, a tsvector is created and it's checked against our tsquery, in failure, we continue to the next record. If I have SearchVectorField field but not SearchVector index: that tsvector vector is stored in SearchVectorField field. So the searching process is faster because we only check for match not creating tsvector anymore, but still we're checking every single record one by one. If I have both SearchVectorField field and SearchVector index: a GIN index is created in database, it's somehow like a dictionary: "cat": [3, 7, 18], .... It stores the occurrences of the "lexems"(words) so that … -
Django search with postgres.search works incorrect and case-sensitive with Cyrillic letters
I'm trying to create search for my project with postgres.search. And it works but works incorrect. It works too precisely. For example: When I'm searching bolu, nothing is found. But when I'm searching bolum it founds. How can I fix it? # filters.py class DepartmentFilter(filters.FilterSet): branch = filters.CharFilter(field_name="branches__id", lookup_expr="in") q = filters.CharFilter(method="search_filter") def search_filter(self, queryset, _, value): search_vector = SearchVector("name") search_query = SearchQuery(value) return ( queryset.annotate(search=search_vector) .filter(search=search_query) ) class Meta: model = Department fields = ["branch", "q"] # models.py class Branch(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Branches" def __str__(self): return self.name class Department(models.Model): name = models.CharField(max_length=100) branches = models.ManyToManyField(Branch, related_name="department") def __str__(self): return self.name [ -
How to setup django signals in django project which has multiple apps in it?
Tree structure of my project ├── apps │ ├── app1 │ │ ├── admin.py │ │ ├── config.py │ │ ├── __init__.py │ │ ├── migrations │ │ ├── models.py │ │ ├── signals.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ └── app2 │ ├── admin.py │ ├── config.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── signals.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── dummy │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── templates ├── home_page.html └── index.html i have tried few things to setup django signals like in app1-->__init__.py inserted this default_app_config = "apps.app1.config.App1Config" and in config.py file inserted this code app1-->config.py from django.apps import AppConfig class App1Config(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "app1" def ready(self): from . import signals and in app1--> signals.py file inserted this code to check if signals are working or not from django.db.models.signals import post_save from django.dispatch import receiver from .models import Demo @receiver(post_save, sender=Demo) def your_signal_handler(sender, instance, created, **kwargs): if created: print("Created") else: print("Created") but its not working i want to use django signals for project at work … -
how to save same data in tow tables in django
i write django code it save into tow table in data base and one of these table is temporary when the patient leave hospital ,deleted his data from temporary but still saved in the anther table problem when i want to update data or add more data to this patient i click save then data cleaned but not saving in any database tables [[[enter image description here](https://i.stack.imgur.com/nx55C.png)](https://i.stack.imgur.com/KUtHe.png)](https://i.stack.imgur.com/L8E4G.png) if i click save that should be update data in tow tables -
Django sockets don't work in production, when deployed in Azure Web App
Python version 3.10 Recently my websockets stopped working when deployed in Azure. I am using Python Django with Daphne. When run locally everything works fine also if ssh into the web server and run another instance of Django, I can locally also connect to the websocket. But when I'm trying to connect to websockets in production as a client, the socket connection instantly fails. Also when viewing logs it seems like they get redirected to HTTP requests? That is why I get a 404 error Not Found: /ws/notifications/ 169.254.129.1 - - [01/Jul/2023:10:14:35 +0000] "GET /ws/notifications/?token={myToken}HTTP/1.1" 404 2753 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" The code gets built and deployed without any errors, so I am confused to why this is happening. My front-end is also calling the correct uri wss://api.pickme.lv/ws/notifications/. Also as I mentioned they were working previously, now they just stopped. Please ask if you required additional information, because tbh I have no clue where to start with this. I also have websockets enabled in my Azure config ], "vnetPrivatePortsCount": 0, "vnetRouteAllEnabled": true, "webSocketsEnabled": true, "websiteTimeZone": null, "windowsFxVersion": null, "xManagedServiceIdentityId": null } -
error when i execute the makemigrations command in django
I'm following the cs50 course, i have added a new passenger model in models.py file but cant execute the makemigration command. i pretty new to django, excuse me if im asking something obvious This is my models.py code from django.db import models 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})" # Create your models here. class Flights(models.Model): origin=models.ForeignKey(Airport , on_delete= models.CASCADE , related_name="departures") destination=models.ForeignKey(Airport , on_delete=models.CASCADE , related_name="arrivals") duration=models.IntegerField() def __str__(self): return f" {self.origin} to {self.destination} : {self.duration}" class Passenger(models.Model): first=models.CharField(max_length=24) last=models.CharField(max_lenght=24) flight=models.ManyToManyField(Flights , blank=True , related_name="passengers") def __str__(self): return f"{self.first} {self.last}" This is the error im getting, I couldnt find anything online that explained this issue $ python manage.py makemigrations Traceback (most recent call last): File "D:\practice\airlines\manage.py", line 22, in <module> main() File "D:\practice\airlines\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Users\faisa\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File … -
Google ads for django
I have created a django Web application. Now I want to deploy it in production but first I want to know that how can I run Google ads on it ? Whether we can run ads ? If yes then how ? Thanks in advance I tried searching for that on internet found some post but didn't get anything clearly -
Python Knowledge and Its Relevance in Django Development
I spent a lot of time learning Python and building a strong knowledge base in it. My goal was to enter the Django domain and explore frameworks like DRF (Django REST Framework) to become a proficient Python developer. I started learning Django and DRF a couple of months ago, and it has been a good experience so far. My question is: up until now, I haven't had the opportunity to use the majority of Python's advanced tools that I learned. Is it because I am still a beginner in Django, or is it unnecessary to use these advanced tools such as enumerations, metaclasses, modules like fractions, descriptors, etc.? From what I've observed, it seems that a basic understanding of Python is sufficient to work with Django. Thank you for taking the time to answer my question. I expected that having a good knowledge of Python would give me a significant advantage. -
AWS Route53 + Nginx + Django, host 2 applications with CNAME
I am trying to host 2 applications in aws EC2 instances. I am using dockerlized nginx, django. The 2 apps are 2 separate django containers. I added record Record A => www.main.com XXX.XXX.XXX.XXX Record CNAME => www.aap2.main.com www.app1.com Now, how should I configure Nginx so that if user access with URL www.main.com, it is served with app1 and if user access with URL www.aap2.main.com, it is served with app2? I tried playing around with nginx.conf file but did not have luck so far. -
how do i submit form elements to sever emidiately after filling a particular form field
i have this mini flask application i am building and i have nested a form in another and i wish to submit the nested form using just javascript after i finish filling it. i am trying to do this with javascript but currently what my script deos is it submits the nested form emidiately the page loads and when i fill the inputs it deosnt submit again. bellow are my code for my html form, flask route to collect the form and the javascript HTml <form method="POST" action="/skills" enctype="multipart/form-data"> <h3>Skills</h3> <form method="POST" action="/skills" enctype="multipart/form-data" id="myForm"> <div class="form-group"> <label for="skills">Skills (comma-separated)</label> <input type="text" class="form-control" id="skills" name="skills" required> </div> <h3>Work Experience</h3> <div id="work-experience"> <div class="form-group"> <label for="work-title-1">Title</label> <input type="text" class="form-control" id="work-title-1" name="work_title_1" required> </div> <div class="form-group"> <label for="work-company-1">Company</label> <input type="text" class="form-control" id="work-company-1" name="work_company_1" required> </div> </div> <!-- Add a hidden submit button --> <input type="submit" style="display: none;"> </form> <div class="form-group"> <label for="work-start-date-1">Start Date</label> <input type="text" class="form-control" id="work-start-date-1" name="work_start_date_1" required> </div> <div class="form-group"> <label for="work-end-date-1">End Date</label> <input type="text" class="form-control" id="work-end-date-1" name="work_end_date_1" required> </div> {% if ex_summary %} <div class="form-group"> <label for="work-end-date-1">description</label> <textarea class="form-control" id="sumary" name="ex_summary" rows="8">{{ ex_summary }}</textarea> </div> {% endif %} </div> <button type="button" class="btn btn-primary" id="add-work-experience">Add Work Experience</button> <h3>Certifications</h3> <div id="certifications"> … -
How to solve Django Rest Api Deployment 404 Error on Vercel
I tried to deployed my django rest api project on vercel and it shows the message deployment successfully. But i open the visit it shows an error 404: NOT_FOUND Code: NOT_FOUND ID: bom1::d724b-1688197940778-5b5d73a1c7a7 i dont know how to fix this error im using the vercel deployment on first time. There is any solution to fix this error -
request.user showing "AnonymousUser" in django classview dispatch method but not in "get_object" method
class ProductViewSet(viewsets.ReadOnlyModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] # @method_decorator(custom_ratelimit) def dispatch(self, request, *args, **kwargs): print(request.user.id) # return "AnonymousUser" return super().dispatch(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): # some lines of code return Response(serializer.data) def get_object(self): user=self.request.user print(user) # return user EMAIL (I am using custom user model) # some code return obj I am not able to understand why dispatch() method not able to find user on other hand get_object() method is able to find the user and returning user email. FYI- I am using a custom user model and instead of a username I am using email. I want to use a decorator to count request limits for that reason I am using this dispatch method to pass users. -
Django distincted queryset slicing does not have consistency
I have queryset of empoyees-attendance and i am doing aggregation & disctinction on (current day, employee code). I got distincted queryset, Afterthat i am doing slicing, and found slicing consistency not happenning as we are expecting. I am adding screenshot of reference here. Could you please anyone explain this behaviour and how we can overcome this?