Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django slug with id in url
How can made a url with slug and id, like: https://example.com/product/beauty-slug/1 The Product model can accept repeated title product, and insted use unique slug i prefer use the slug with id models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') slug = models.SlugField(max_length=250,unique=True,null=True) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.product_title) return super().save(*args, **kwargs) And how use it in a template product_list.html <a href="{% url 'product_view' product.slug %}">see product</a> urls.py ... path('product/<slug:slug>', ProductView.as_view(), name='product_view'), ... Thats works, but i know i gona have identical products title, so i think with id is better to my case, becouse if needed costumer can reference the order to seller with id number... -
how to have different anchor tag in the same for loop
** {% for i in objectss %} <div class="col-lg-4 col-md-6 col-12" data-aos="fade-up" data-aos-delay="400"> <div class="class-thumb"> <a href="accounts/let/"><img src="{{i.image.url}}" class="img-fluid" alt="Class"></a> <div class="class-info"> <h3 class="mb-1">{{i.name}}</h3> <span><strong>Trained by</strong> - Bella</span> <span class="class-price">₹{{i.price}}</span> <p class="mt-3">{{i.desc}}</p> </div> </div> </div> {% endfor %} **``` {% for i in objectss %} <div class="class-info"> <h3 class="mb-1">{{i.name}}</h3> <span><strong>Trained by</strong> - Bella</span> <span class="class-price">₹{{i.price}}</span> <p class="mt-3">{{i.desc}}</p> </div> </div> </div> {% endfor %}``` In this code for loop helping to display 6 typer of excercises on my html page. I want to add anchor tags for user so that if the user click on the singing image he get redirected to singing excercise page and same for other excercises. -
Closed connection: Django channels with async websockets
I'm trying to run this command, but it keeps closing the websocket connection: #!/usr/bin/env python from django.core.management.base import BaseCommand from channels.layers import get_channel_layer from asgiref.sync import async_to_sync class Command(BaseCommand): help = "Send message" def handle(self, **options): channel_layer = get_channel_layer() msg = { 'type': 'hello', 'content': 'hello' } async_to_sync(channel_layer.group_send)('chat', msg) print('done') I followed all the steps and examples (like this guide: https://channels.readthedocs.io/en/latest/topics/channel_layers.html#using-outside-of-consumers), the rest of the websocket code is working (using redis) and I can send/receive messages from a javascript frontend page. Here's the output I get from the command: Creating tcp connection to ('redis', 6379) Closed 1 connection(s) done I don't see any Redis errors, it's just a fresh docker container. -
Python get screenshot from active page's element
i want to take screenshot of django active page's elements. I research about selenium and playwright but they opening the pages on new browser. The page on which I want to take the screenshot has dynamic information and it is constantly changing, so it is not appropriate to take a screenshot by opening it on a new page. Each user will enter different information on the opened page and take a screenshot of the relevant element. -
Having Error page Not found Using Django Id based URLs in detail Page
i m having this type of error my hyperlink is look lke this my view functon look like that url patterns look lik that -
Video Conferencing Implementation in website
I have idea to implement video conferencing in my helath care website project & I don't know how to implement it. So it will be great favor to help -
Django websocket: Can't send message to channel outside consumer
I'm trying to get this example to work: https://channels.readthedocs.io/en/latest/topics/channel_layers.html#using-outside-of-consumers I have a Django application that starts a connection over websocket, and a command that sends a message, like this: from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.channel_layer.group_add("chat", self.channel_name) await self.accept() print(f'[{self.channel_name}] - You are connected') async def disconnect(self, close_code): await self.channel_layer.group_discard( "chat", self.channel_name ) #!/usr/bin/env python from django.core.management.base import BaseCommand from channels.layers import get_channel_layer from asgiref.sync import async_to_sync class Command(BaseCommand): help = "Send message" def handle(self, **options): channel_layer = get_channel_layer() msg = {"message": 1} async_to_sync(channel_layer.group_send)('chat', msg) When I connect from a webapp, I get this log: [specific..inmemory!XodgAfVQQhKL] - You are connected Running the command does nothing..what am I missing? -
Only accept 15 seconds video file
I have django app I want to know how can I take a 15 second video file Force to take 15 seconds I am using react as frontend with django-rest-framework any idea ? -
Django DRF - API shows json format instead of interface
I recently updated to Django 4.0 and DRF 3.13.1, and now my API shows in json format by default, whereas before it was showing the interface. I would like to see an interface like so: But this is what I now get. Is there a way to change this back to the interface? Sorry if this is a silly question. -
Can I call a function in both create and update in ModelSerializer
Can i call same function in both create and update without overriding it? Hi im fairly new at this and trying to implement my code using the DRY principle. So im calling a function say for create_update_password in ModelSerializer's while creating or changing the password for this i have to override create and update in ModelSerializer and create_update_password in both of them. Im not doing any extra functionality in any of them them apart from calling this function. So is there any way that i can invoke this function in create and update without overrding it. Ill really appericiate it if anyone can give any suggestion. Below is the code Example Thanks You def create_update_password(self, instance, validated_data): password = validated_data["password"] instance.set_password(password) instance.save() class UserModelSerializer(ModelSerializer): def create(self, validated_data): instance = super(UserModelSerializer, self).create(validated_data) self.create_update_password(instance, validated_data) return instance def update(self, instance, validated_data): instance = super(UserModelSerializer, self).update(instance, validated_data) self.create_update_password(instance, validated_data) return instance -
Set specific valdiation rule in UpdateView
I set an UpdateView class to update data of user's markers. I have a Marker model with a field category. I want to have one and only "Where I live" category marker in all the user's markers. Is there a way to create a function in the UpdateView class to invalidate the form if there too many "Where I live" markers. class UpdateMarkerView(UpdateView): model = Marker fields = ["name", "description", "category"] template_name = "map/detail.html" success_url = "/" class Marker(models.Model): WIL = "WIL" WIWG = "WIWG" WIW = "WIW" IDK = "IDK" CATEGORY_MARKER = [(WIL,"Where I live"), (WIWG, "Where I want to go"),(WIW,"Where I went"),(IDK,"I don't know")] user = models.ForeignKey(User,blank=True, null=True,on_delete = models.SET_NULL) name = models.fields.CharField(max_length=100) description = models.fields.CharField(max_length=100) lat = models.fields.DecimalField(default=False, max_digits=5, decimal_places=3) lon = models.fields.DecimalField(default=False, max_digits=5, decimal_places=3) category = models.CharField(max_length=50, choices = CATEGORY_MARKER, default = IDK) I've already done it with a basic function but I can't find a way to it with a generic view if it's possible. -
Automate update database
i have application for dailyhours for work,i just looking around about specific hour will be run script to check database if some value are None will be add value to database. So my question is i need do this with some script with rest api or maybe django-celery will be okay for that ? example: start:8:00 end:12:00 daily:4:00 but sometimes if you forget close work you need change value for some workers in PA so i wanna create script which will be do it automate everyday if value are None -
customer registration not showing in django admin
Trying to create customer registration form for ecommerce website . No errors while submitting the form, but details are not shown in django admin . Here are required codes : models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) address = models.CharField(max_length=200, null=True, blank=True) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name urls.py urlpatterns = [path("register",views.register, name="register")] forms.py class CustomerRegistrationForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) email = forms.CharField(widget=forms.EmailInput()) class Meta: model = Customer fields = ["username", "password", "email", "full_name", "address"] def clean_username(self): uname = self.cleaned_data.get("username") if User.objects.filter(username=uname).exists(): raise forms.ValidationError( "Customer with this username already exists.") return uname views.py def register(request): form = CustomerRegistrationForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") user = User.objects.create_user(username, email, password) form.instance.user = user return redirect("/") return render(request,"register.html",{'form':form}) register.html {% load crispy_forms_tags %} <div class="container"> <div class="row"> <div class="col-md-6 mx-auto"> <h3>Customer Registration Form</h3><hr> <form action="" method="POST"> {% csrf_token %} {{form|crispy}} <button class="btn btn-primary" >Register as a Customer</button> </form> <p> Already have an account? <a href="/home">Login here</a></p> </div> </div> </div> Thank you in advance:) -
Duplicate Django Admin functionality to Add/Edit Related Field
I am looking to duplicate the functionality of Django Admin that displays related fields in a dropdown list and allows one to edit a selected object or add a new object. Digging into the Django admin code, the add/edit button open a popup and set the IS_POPUP_VAR, but I lose the trail from there. What functionality does django.contrib.admin utilize to refresh the dropdown list with related objects once that set of objects is updated, and where is it located in the source (to be used as an example)? -
Where the right place to put recurrent function in Django
I want to make a function that will be used in different parts of my application. It is a function to send email notifications, something like: def mail_notification(): subject = 'New Product' from_email = 'master.aligabra@gmail.com' to = 'ali.corretor.imoveis@gmail.com' html_content = render_to_string('email/new_message_product_client_email.html') msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.content_subtype = "html" msg.send() My doubt is, in a View, signals.py, forms.py, Django have a "right" place or is where i prefer? -
How to return Modal processing result to Modal
I want to display the search screen in the modal screen and display the search processing results on that modal screen. Search result display is completed with modal. But,In my writing style, when I press the process button in modal, the result is displayed on another screen instead of modal. What should I do? I'm using Modal with Ajax in Django. Ajax is a beginner. I found this as a result of my research, but it didn't work. <head> <base target="_self"> </head> Ajax function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(function(){ $('#edit_foo').on('click', function (event) { event.preventDefault(); var form = $('form')[0]; var formData = new FormData(form); var form … -
using if is giveing me different results in the same cod
as show in pic, why is this happen to ( Iron - Fe )( Carbon - C)( Nitrogen - N)( Phosphors- P) only the ( Sulfur - S) is working good whitout problem my html cod is: {% if object.Iron_Fe != '-' %} <tr type="hidden> <td style="text-align:left">Iron - Fe</td> <td>{{ object.Iron_Fe }}</td> </tr> {% endif %} {% if object.Carbon_C != '-' %} <tr type="hidden> <td style="text-align:left">Carbon - C</td> <td>{{ object.Carbon_C }}</td> </tr> {% endif %} {% if object.Nitrogen_N != '-' %} <tr type="hidden> <td style="text-align:left">Nitrogen - N</td> <td>{{ object.Nitrogen_N }}</td> </tr> {% endif %} {% if object.Phosphorus_P != '-' %} <tr type="hidden> <td style="text-align:left">Phosphorus - P</td> <td>{{ object.Phosphorus_P }}</td> </tr> {% endif %} {% if object.Sulfur_S != '-' %} <tr type="hidden"> <td style="text-align:left">Sulfur - S</td> <td>{{ object.Sulfur_S }}</td> </tr> {% endif %} -
CSS styling doesn't apply on a Django Project
I am trying to style my textarea for wiki project. There already exists a default CSS and I added background-color to test if it works but it doesn't change. I have restarted the program to load static files but nothing changes. Can you help me please? Here's the html page: {% extends "encyclopedia/layout.html" %} {% block title %} Create New Page {% endblock %} {% block body %} <h1>Create New Page</h1> <form action="{% url 'new_page' %}" method="POST"> {% csrf_token %} <input type="text" name="title" placeholder="Title"> <textarea name="new_entry" id="new_entry"></textarea> <input type="submit" name="save_entry" id="save_entry" value="Save"> </form> {% endblock %} CSS: textarea { height: 90vh; width: 80%; background-color: black; } And layout.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}" method="GET"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href="{% url 'new_page' %}">Create New Page</a> </div> <div> <a href="{% url 'random' %}">Random Page</a> </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% … -
How do you pass two parameters through url in django
I want to pass two parameters through url in django. First of all, here is my current html: {% for lesson in lessons %} {% for class in lessons %} <a href="{% url 'next-page' lesson.pk %}">Link to next page {{lesson}} {{class}}</a> {% endfor %} {% endfor %} And this is my url: path('nextpage/<int:pk>/', ListView.as_view(), name='next-page'), However, I want something like below: {% for lesson in lessons %} {% for class in lessons %} <a href="{% url 'next-page' lesson.pk class.pk %}">Link to next page {{lesson}} {{class}}</a> {% endfor %} {% endfor %} and my url is: path('nextpage/<int1:pk>/<int2:pk>', ListView.as_view(), name='next-page'), Then I want to be able to access the primary keys in my view below: class LessonList(generic.ListView): model = Lesson template_name = 'lesson_list.html' context_object_name = "lessons" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) lesson_id = self.kwargs['pk1'] class_id = self.kwargs['pk2'] return context Obviously, the above code does not work. However, I want to basically be able to pass two parameters in the url, and access both of them in my view's get_context_data. Thank you, and please leave any questions you might have. -
Unable to run collectstatic , "references a file which could not be found: js/canvas-to-blob.min.js.map"
I'm trying to deploy a django react application on heroku , which uses whitenoise to handle staticfiles and cloudinary to handle media files , but when i try to run python manage.py collectstatic it returns an error 'js\canvas-to-blob.min.js' references a file whic could not be found , so i used the find static command to find the static file and discovered it was in the virtualenv folder (venv\Lib\site-packages\cloudinary\static\js\load-image.all.min.js ) and it belongs to cloudinary , when i comment out all its content , collectstatic works fine , pls is there any way to fix the error -
How to overcome locations field caught empty in validated data?
I've a model: class ListingPrice(Timestamps): price = models.ForeignKey("Price", on_delete=models.CASCADE) location = models.ForeignKey("location", on_delete=models.CASCADE) class Meta: unique_together = ["price", "location"] class Price(Timestamps): package = models.ForeignKey("products.Package", on_delete=models.CASCADE) locations = models.ManyToManyField("location", through="ListingPrice") price = models.DecimalField(max_digits=11, decimal_places=3) with a serializer: class LocationSerializer(serializers.ModelSerializer): name = LocalizedField() class Meta: model = location fields = ['id', 'name'] class PriceSerializer(serializers.ModelSerializer): locations = LocationSerializer(many=True) class Meta: model = Price fields = ['package', 'locations', 'price'] def create(self, validated_data): print("validated_data, validated_data) and viewset: class PriceViewSet(ModelViewSet): queryset = Price.objects.all() serializer_class = PriceSerializer ordering = ['id'] permissions = { "GET": ["view_minimum_listing_price", ], "POST": ["add_minimum_listing_price", ], 'PUT': ['update_minimum_listing_price', ], 'DELETE': ['delete_minimum_listing_price', ], } In testing I'mm using the following: data = { "price": 12, "package": self.package.id, "is_enabled": False, "location": [{'name': self.location.name, 'id': self.location.id}] } response = self.client.post(path=self.url, data=data, format='json') locations appear as empty dict in validated_data? I need to caught it and added it to the price by locations.add. how to implement this? -
How can I let the user add a new field in a Django-form dynamically, instead of letting them append the entire form at every addition?
In forms.py: class BillGateway(forms.Form): from_date=forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='From ', label_suffix=' - ') to_date=forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='To ', label_suffix=' - ') billing_date=forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Date of Billing ', label_suffix=' - ') rt_cash_amount_desc=forms.CharField(label='RT Cash Amount Description', label_suffix=' - ', required=False) rt_cash_amount=forms.DecimalField(label='RT Cash Amount', label_suffix=' - ', required=False) other_desc=forms.CharField(label='Other Head', label_suffix=' - ', required=False) other_amount=forms.DecimalField(label="Other Head's Amount", label_suffix=' - ', required=False) In views.py: def bill_gateway_view(request): if request.method=='POST': fro=request.POST.get('from_date') to=request.POST.get('to_date') bill_date=request.POST.get('billing_date') rt_cash_desc=request.POST.get('rt_cash_amount_desc') rt_cash_amount=request.POST.get('rt_cash_amount') other_desc=request.POST.get('other_desc') other_amount=request.POST.get('other_amount') request.session['fro']=fro request.session['to']=to request.session['bill_date']=bill_date request.session['rt_cash_desc']=rt_cash_desc request.session['rt_cash_amount']=rt_cash_amount return HttpResponseRedirect('/provisional_bill/') else: form=BillGateway() return render(request, 'account/bill_gateway.html', {'form':form}) In templates: <form action="" method="post" novalidate> {% csrf_token %} {{form.as_p}} <button type="submit" id="savebtn">Proceed</button> </form> Now, what I want to achieve is to let the user extend the other fields, both, the other_desc and other_amount if he/she needs to fill in more details in the bills. I'm fairly new to this concept. I have seen some tutorials in which the tutors mainly used htmx to achieve such things and seemed pretty cool and easy but what they did was adding the whole form again upon clicking the add button. I just want the user to be able to add these two fields only and not the entire form. How can I achieve this? I have spent my whole day looking … -
What will happen if I push changes from one branch to another?
I have two branches in my project. main and test_deploy It's incorrect to push changes without any tests to the main branch, but never mind. I use the main branch to make some changes locally and the test_deploy where I have other changes in settings.py (for example DEBUG=False, use a cloud for storing my model images and so on) and files for deployment(Procfile, runtime.txt and so on). For example, I'm going to add a new app and push it to the main branch and to the test_deploy branch too(to get the newest version of my project) I have a question. What will happen if I commit these changes to the main branch, push it to this branch AND also push it to the test_deploy branch? Will I have conflicts that I'll have to fix manually? Or I have firstly pull all files from the test_deploy branch and then push it?(I don't wanna pull files from the test_deploy branch. That's why I asked this question) Summary So, generally, I wanna push changes from the main branch to test_deploy, but without pulling separate files from the test_deploy branch, because they are superfluous on the main branch which I use locally. -
How to keep track of attendance in django project
I have a project in which two different models have cyclic many-to-many relation. Models are "Training" and "Student", where a student can enroll to many trainings and vice-versa, so i want to keep track of attendance of each student for each training. How can i achieve this in django? -
How do you create next and previous buttons for django lists?
I want to basically create a previous and next button so that the dates of a list would change on the same page (next means next day, and previous means previous day). Here is the generic list view I am using: class LessonList(generic.ListView): model = Lesson template_name = 'lesson_list.html' context_object_name = "lessons" def get_queryset(self): today = datetime.datetime.today() queryset = Lesson.objects.filter(date=today) return queryset Here is my html: {% for lesson in lessons %} <h1> {{lesson}} </h1> {% endfor %} And here is my model: Lesson(models.Model): name = models.CharField(max_length=100) date = models.DateField(null=True, blank=True) I did not mention it in the above code, but this list view already takes a primary key through the url, so I need another way of transferring the date value of the list to the next page when I click either the next or previous button. Is there any way I can do this? I would appreciate it if you guys could write the full code based on the code I have given in this question. If you have any questions, please leave a message.