Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make edit function work in views.py Django
I am creating an edit option for my entry. But instead of redirecting to the entry page, it is taking me to the addpage to create a new form. How do I redirect to the edit page? Also, how do I make sure that the users previous input would reflect when they click on the edit button. I used initials - is this the best way to do it since I'm not using models but rather forms.Form. VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Tell us more!" }) def edit_page(request, title): entry = util.get_entry(title) if request.method == "POST": form = AddPageForm(request.POST, initial={ "title": title, "content": content }) if form.is_valid(): util.save_entry(title, content) return redirect('encyclopedia:entrypage', title=title) else: form = AddPageForm() return render(request, "encyclopedia/editpage.html", {"form":form}) EDIT PAGE {% block body %} <h1>Edit {{ title }}</h1> <form action="" method="post"> {% csrf_token %} {% form %} <input type="submit" value="Submit" class="btn btn-secondary"> </form> ENTRY PAGE {% block body %} {{ content|safe }} <a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Update</a> <!-- <input="text" name="title" value="{{game.title}}" /> <input="text" name="genre" value="{{game.genre}}" /> --> {% endblock %} URLS.PY app_name = "encyclopedia" urlpatterns = [ path("add_page", views.add_page, name="addpage"), path("edit_page/<str:title>", views.edit_page, name="editpage") ] -
Using selected fields from ModelMultipleChoiceField to run a SQL query
I'm learning Django and I'm trying something that may be unorthodox. In forms.py, I have the following class: class CompareFormClient(forms.ModelForm): class Meta: model = OrderFile fields = ['origine'] items = forms.ModelMultipleChoiceField( widget=FilteredSelectMultiple( 'items', False, ), queryset=OrderFile.objects.all().values_list('reference', flat=True) ) In models.py, I have these two classes: class OrderFile(models.Model): uploadedfile = models.ForeignKey(File, on_delete=models.CASCADE, default=1) ean = models.CharField(max_length=50) designation = models.TextField(blank=True) reference = models.CharField(max_length=200) quantite = models.IntegerField() prix_unitaire = models.IntegerField(blank=True) prix_total = models.IntegerField(blank=True) poids_unitaire = models.IntegerField(blank=True) poids_total = models.IntegerField(blank=True) composition = models.TextField(blank=True) origine = models.IntegerField(blank=True) nomenclature_douaniere = models.CharField(max_length=50) reference_transport = models.CharField(max_length=50) class DeliveryFile(models.Model): uploadedfile = models.ForeignKey(File, on_delete=models.CASCADE, default=1, db_constraint=False) ean = models.CharField(max_length=50) designation = models.TextField(blank=True) reference = models.CharField(max_length=200) quantite = models.IntegerField() prix_unitaire = models.IntegerField(blank=True) prix_total = models.IntegerField(blank=True) poids_unitaire = models.IntegerField(blank=True) poids_total = models.IntegerField(blank=True) composition = models.TextField(blank=True) origine = models.IntegerField(blank=True) nomenclature_douaniere = models.CharField(max_length=50) reference_transport = models.CharField(max_length=50) Both models OrderFile and DeliveryFile are already filled with data. In my form, I select values from the following queryset : queryset=OrderFile.objects.all().values_list('reference', flat=True). My objective is to run a SQL query to find any differences with the selected values (from ModelMultipleChoiceField) between two tables. This SQL query would be the following: SELECT id --want to use the selected values from the django form here FROM foo FULL OUTER … -
How to implement SocketIO in Django ASGI
I tried this; https://github.com/ly3too/django-channels-with-socket.io But I keep getting 404 for the socket-io. Are there any other methods to implement the socket io? -
html2canvas javascript screenshot pass to python
would it be possible to use html2canvas to take a picture of the user`s screen but also i wanna use this image with python function. What I want to do is save the image of the html element with javascript and send it to slack with python. function capture() { html2canvas(document.getElementById("main"), { letterRendering: 1, allowTaint: true, useCORS: true, }) .then(function (canvas) { document.getElementById("result").src = canvas.toDataURL("image/png", 0.5); }) .catch((e) => { alert(e); }); } -
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?