Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
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 }