Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove '*' sign on a field when dealing with crispy forms?
So in the crispy form documentation(link here: https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html#change-required-fields), it states that: Asterisks have an asteriskField class set. So you can hide it using CSS rule. models.py class Post(models.Model, HitCountMixin): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateField(auto_now_add=True) image = models.ImageField(default='default_pics/default_post.jpg', upload_to='post_pics') # a teacher can have many blog posts author = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True) forms.py class BlogFrom(forms.ModelForm): class Meta: model = Post fields = ['title', 'content', 'image'] widgets = { 'image': forms.FileInput(attrs={"class":"asteriskField"}) } help_texts = { 'image': 'If you do not set any image, one will be set automatically for you upon creation.' } I am not sure how to proceed from here. Help me please! -
Requesting Source Code for Photo-Truth Verification Project using Django, Vue, HTML, CSS, and SQL
I am a final year undergraduate student working on a project titled "Photo-Truth Verification Using Encrypted Metadata". My project aims to develop a web application that can verify the authenticity of photos using encrypted metadata. The project will be implemented using Django, Vue, HTML, CSS, and SQL. However, as my final year project defense is approaching fast, I am struggling to complete the project on time. I have very basic knowledge in programming and would appreciate any help I can get with the source code for my project. If anyone has experience with these technologies and would be willing to assist me with the source code for this project, I would be extremely grateful. Ideally, I need the source code within the next 5 days so that I can complete the project and prepare for my defense I have attempted to generate the source code for my project using AI like Chat GPT. Unfortunately, my limited programming knowledge made the process confusing and complicated. Therefore, I am seeking assistance from an experienced developer who has knowledge of the specific technologies I am using. I am expecting to receive the complete source code for my project, with a focus on the … -
stream multi videos flask_socketio from Multi Clients to one server
can any one plz help me, to write a simple code in python based on Flask and flask_socketio, to recieve and process videos from multi clients in the same time. i used Threads but it's so difficult to apply it on flask_socketio. this is my old code based on socket library but i want to change it to flask_socketio: # In this video server is receiving video from clients. # Lets import the libraries import socket, cv2, pickle, struct import imutils import threading import pyshine as ps # pip install pyshine import cv2 server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) print('HOST IP:',host_ip) port = 9999 socket_address = (host_ip,port) server_socket.bind(socket_address) server_socket.listen() print("Listening at",socket_address) def show_client(addr,client_socket): try: print('CLIENT {} CONNECTED!'.format(addr)) if client_socket: # if a client socket exists data = b"" payload_size = struct.calcsize("Q") while True: while len(data) < payload_size: packet = client_socket.recv(4*1024) # 4K if not packet: break data+=packet packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("Q",packed_msg_size)[0] while len(data) < msg_size: data += client_socket.recv(4*1024) frame_data = data[:msg_size] data = data[msg_size:] frame = pickle.loads(frame_data) text = f"CLIENT: {addr}" frame = ps.putBText(frame,text,10,10,vspace=10,hspace=1,font_scale=0.7, background_RGB=(255,0,0),text_RGB=(255,250,250)) cv2.imshow(f"FROM {addr}",frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break client_socket.close() except Exception as e: … -
New users on Django app at heroku doesn't persist on database
We started a project on Heroku, using Django, but users aren't persisted on Django User table on our database, but as Admin users at Django? We use User.objects.create_user() from django.contrib.auth.models.User Database is MySQL Any tips? -
Using the URLconf defined in iblogs.urls, Django tried these URL patterns, in this order:
I know this question has been asked before, but I haven't found an answer that solves my situation. I'm looking at the Django tutorial, and I've set up the first URLs exactly as the tutorial has it, word for word, but when I go to http://127.0.0.1:8000/, it gives me this error: but when i go to http://127.0.0.1:8000/admin/ its working fine,where and what i am doing wrong? i am using python version 3.11.1 please let me know for any other info Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog Using the URLconf defined in iblogs.urls, Django tried these URL patterns, in this order: admin/ ^media/(?P<path>.*)$ The current path, blog, didn’t match any of these. urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from .views import home urlpatterns = [ path('admin/', admin.site.urls), path(' ', home) ] views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home(request): return HttpResponse("hello") urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django migration: django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'slug'")
I am having a very similar problem as in the below question: django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'slug'") I also think that the reply marked as accepted will work for me. The problem is that I can't figure how to implement this solution (I was trying to ask in comments to the answer, but I don't have enough reputation). After reading https://docs.djangoproject.com/en/4.1/ref/migration-operations/, nothing became clearer. I tried to search the Internet for guides on how to edit or copy migrations, but I haven't found anything useful to me, apart from discovering that migrations are/can be also files? Until now, I thought that migration is an action, not a file. I am very new to Django, and the only thing I have ever done with migrations is to just run a basic python manage.py migrate and python manage.py makemigrations commands. Would anyone be able to advise what 'copy migrations.AlterField operation twice,' means? How can I copy a migration? And why does it have .AlterField attached to it? This whole paragraph seems like it might be a solution to my problem, but my knowledge is insufficient to figure out what to do with it... Could someone please explain how to … -
Google Cloud Scheduler - Decode OIDC Http Authorization Decode in Django
I have deployed a django app in GCP Cloud Run and trying to setup a cron job in GCP Scheduler. The job uses OIDC authentication. How to verify the OIDC in the backend. I tried the below code, but I could not get any data from the decode. from google.auth import jwt def send_mail(request): auth_header = request.headers.get('Authorization') if auth_header: auth_type, creds = auth_header.split(' ', 1) if auth_type.lower() == 'bearer': certs = requests.get('https://www.googleapis.com/oauth2/v1/certs') claims = jwt.decode(creds, certs=certs.json(), verify=True) logger.info(f"Claims: {claims}") return HttpResponse(status=204) -
Send files to another server with Django
I have a project in which I made the frontend in Angular and the backend in Django. The frontend is uploaded on my hosting service and the backend is uploaded to pythonanywhere. What I am looking for is the media files to be uploaded to my hosting. I found that it can be done using django-storages but the documentation is very unclear and I can't understand it. I already followed the steps, adding DEFAULT_FILE_STORAGE and FTP_STORAGE_LOCATION to my settings.py but I don't know how to proceed. I searched the internet for information about it but got nothing. I would appreciate more information about it or any alternative to achieve my goal -
How to load an image from ImageField of all instances of a model
So I have an app called todo, a Good model with ImageField. In my template I want to iterate over all instances of Good model and display all instances' images which were uploaded by admin in admin panel but when I try to run the code below I get: Not Found: /todo/static/goods_images/image_2023-04-03_224219080.png [04/Apr/2023 00:22:26] "GET /todo/static/goods_images/image_2023-04-03_224219080.png HTTP/1.1" 404 2355 model.py: from django.db import models class Good(models.Model): name = models.CharField(max_length=100) price = models.FloatField() pic = models.ImageField(upload_to='todo/goods_images', null=True, blank=True) class Meta: ordering = ['-price'] def __str__ (self): return str(self.name) views.py: from django.shortcuts import render from django.views.generic.list import ListView from .models import Good class GoodsList(ListView): model = Good context_object_name = 'goods' template_name = 'goods_list.html' goods_list.html: {% load static %} <html> {% for good in goods %} <div> {{ good.pic }} <img src="{{ good.pic.url }}" /> {{ good.name }} {{ good.price }} </div> {% endfor %} </html> settings.py: from django.urls import path from .views import GoodsList from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('goods_list/', GoodsList.as_view()), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Already went through a couple of videos but all of them load as static only one image and so in template write the exact path to it but … -
Django how get all invoices containing item
I spent over two days looking in docs and internet and cannont find solution. I have models: class Invoice(models.Model): (...) class Product(models.Model): (...) class InvoicedItems(models.Model): invoice = models.ForeignKey(Invoice, on_delete=CASCADE) article = models.ForeignKey(Product, on_delete=CASCADE) How to get list of all invoices containing one product? I want to make search engine. I tried to define in InvoicedItems: def get_invoices_by_article(article): inv_obj = InvoicedItems.objects.filter(article=article) inv = inv_obj.invoice return inv But all the time I get error: 'QuerySet' object has no attribute 'invoice' I know that I am close but I need your help. Thanks in advance! -
Add autocomplete to CKEditorUploadingWidget
I have a Django form that uses CKEditorUploadingWidget from the ckeditor_uploader package. The form class is called TemplateMesForm and contains a CharField named temp_html. from ckeditor_uploader.widgets import CKEditorUploadingWidget class TemplateMesForm(forms.RequestForm): temp_html = forms.CharField(label='Html:'), widget=CKEditorUploadingWidget()) I would like to add autocomplete to the temp_html field, but I'm unsure how to do so. Can you please help me with this? -
Django movie and director relation. Movie is not attached to the director
I'm making a model, consisting of a movie and a director. When I create a movie, I want the movie to be automatically owned by the director I selected but it's not working. class Movie(models.Model): name = models.CharField(max_length=100) category = models.CharField(max_length=100) imdb = models.DecimalField(max_digits=2, decimal_places=1) director = models.ForeignKey('Director', on_delete=models.DO_NOTHING) class Meta: verbose_name_plural = 'Movies' def __str__(self): return self.name class Director(models.Model): name = models.CharField(max_length=150) movies = models.ManyToManyField(Movie, related_name='movies', blank=True) class Meta: verbose_name_plural = 'Directors' def __str__(self): return self.name I am creating a new movie using django-admin page. for instance;django-admin creating movie However the movie is not automatically added to the director. Director I also want a movie to belong to only one director. How can I do these. I will be very glad if you can help me. Thanks in advance -
Broken pipe error when using @shared_task in Django
I am utilizing the celery library to execute tasks in the background even when the user closes or refreshes the page. Since the task takes some time, I opted to use celery. The algorithm works fine as long as I don't refresh or close the page. However, I encounter the "Broken pipe from ('127.0.0.1', 56578)" error when it occurs. I also attempted to update the account after executing nonFollowers_users(), but I received an error stating that the MySQL server had gone away. for id in accounts: account = Account.objects.get(id=id) #below method is @shared_task from celery nonFollowers_users(account, count, sleep) try: return JsonResponse({'success': True}) except (ConnectionResetError, BrokenPipeError): # the connection was closed, return a response with an appropriate status code return HttpResponse(status=499) -
I am unable how this line of code is working
class ReviewCreate(generics.CreateAPIView): # queryset=Review.objects.all() serializer_class=ReviewSerializer def perform_create(self, serializer): pk=self.kwargs.get('pk') # print(pk) watchlist=WatchList.objects.get(pk=pk) serializer.save(watchlist=watchlist) print("1") In the line serializer.save(watchlist=watchlist) why watchlist=watchlist is being passed.when i goes in CreateAPIView class of rest framework generic class there post method is implemented and from there on it is going into mixins class where create method is implemented like this. class CreateModelMixin: """ Create a model instance. """ def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): try: return {'Location': str(data[api_settings.URL_FIELD_NAME])} except (TypeError, KeyError): return {} As control goes to perform_create function it is saving the data in DB but in our views.py we are again doing serializer.save(watchlist=watchlist). Then why we are doing this again and how data is created in DB with only watchlist field value whereas Review model has other field also .Pls Help -
How to hierarchically output data?
Can you show exactly how to hierarchically output all the children and parents of a model instance. For example, I have a model and a code. How do I get all the parents and children of the object? Model: class Menu(models.Model): name = models.CharField(max_length=150) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, blank=True, null=True, related_name='parent_name') def __str__(self): return self.name And the following code: def index(request, name='Magomed'): menu_item = Menu.objects.raw(''' WITH RECURSIVE menu AS ( SELECT id, parent_id, name FROM app_menu WHERE name = %s UNION SELECT app_menu.id, app_menu.parent_id, app_menu.name FROM app_menu JOIN menu ON app_menu.parent_id = menu.id OR app_menu.id = menu.parent_id) SELECT * FROM menu;''', [name]) -
Show the data in the Template according to the value of the select
Hi friends i need help as i am new to django! I need to show the information that I have saved in a table according to the option chosen from a select. When selecting the select option in the template I save the value in a variable using JavaScript (I do that without problems). I can't get the value of that variable to the get_context_data method, to later show it in my template. JavaScript code: $(function () { $('select[name="reporteFecha"]').on('change', function () { var fecha = $(this).val(); $.ajax({ url: window.location.pathname, type: 'POST', data: { 'action': 'search_fecha', 'fecha': fecha }, dataType: 'json', }) }); }); Views code: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ### I need to obtain within this function the value of the select in a variable ### context = { 'title': 'Reporte de Control de Electricidad', 'entity': 'Reporte Electricidad', 'list_url': reverse_lazy('cont_elect:Reporte_list'), 'form': ReportForm(), } return context I need to obtain in a variable inside the get_context_data the value that I capture with the JavaScript to later be able to show it in the template -
Django error "Select a valid choice. That choice is not one of the available choices." when use foreign key with djongo
I have a bug when i use django with mongoDB using djongo connector. I don't know why it has this error while doing any create operation in Django admin.. Its happening in models where foreign keys are there , for foreign key it is showing Models.py from djongo import models import uuid # Create your models here. class Blog(models.Model): name = models.CharField(max_length=100) class Meta: abstract = True class Entry(models.Model): blog = models.EmbeddedField( model_container=Blog ) headline = models.CharField(max_length=255) class Product(models.Model): img = models.ImageField(null=True, blank=True, upload_to="static/images/") name = models.CharField(max_length=200) price = models.FloatField() compare_at_price = models.FloatField() description = models.CharField(max_length=1000) estimate_ship_date = models.DateTimeField() def __str__(self): return self.name @property def imageURL(self): try: url = self.img.url except: url = '' return url class ProductTag(models.Model): title = models.CharField(max_length=10) color = models.CharField(max_length=7) background = models.CharField(max_length=7) product = models.ForeignKey( Product, on_delete=models.CASCADE, null=True) def __str__(self): return self.title class ThumbnailImage(models.Model): alt = models.CharField(max_length=200) img = models.ImageField(null=True, blank=True, upload_to="static/images/thumbnails") product = models.ForeignKey( Product, on_delete=models.CASCADE, null=True) @property def imageURL(self): try: url = self.img.url except: url = '' return url class Images(models.Model): alt = models.CharField(max_length=200) img = models.ImageField(null=True, blank=True, upload_to="static/images/images") product = models.ForeignKey( Product, on_delete=models.CASCADE, null=True) @property def imageURL(self): try: url = self.img.url except: url = '' return url i'm trying to use the … -
Is session auth possible in Django Rest Framework with a mobile client?
I want my application to have a mobile client (non native, built using Quasar). As I understand token auth will work, so I have chosen and implemented JWT for the web app though I havent tested the mobile client yet. I was wondering is it possible/recommended to use session auth in this context? -
Django form not registering user, even though all fields are valid
Within this app, I am presenting users with a registration form in which they enter their username, password, confirm their password (this confirmation is not part of the form, rather a check I do to ensure the passwords match in views.py), and their email. For some reason, whenever I attempt to register a with a the wrong confirmation password I keep getting the error "Something went wrong... Please try again!" in my else block instead of "passwords must match". I am pretty stuck and not sure what went wrong as before this functionality was fully operational and I started working on other features for my app. views.py def register(request): if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] confirmation = request.POST['confirmation'] # Ensure password matches confirmation if password != confirmation: messages.error(request, 'Passwords must match.') return render(request, "network/register.html", { "register_form": form }) # Attempt to create new user try: user = User.objects.create_user(username=username, email=email, password=password) user.save() except IntegrityError: messages.error(request, 'Username already taken.') return render(request, "network/register.html", { "register_form": form }) login(request, user) return HttpResponseRedirect(reverse("index")) else: # Always returns this whenever submitted messages.error(request, 'Something went wrong... Please try again!') return render(request, "network/register.html", { "register_form": form … -
Is there a way to load html AND event listeners dynamically?
Im using Django with htmx, and I use htmx in templates to load and remove not only html dynamically but also script tags that contain event listeners. Now the problem is that event listeners dont work when you load the script that contains them dynamically. I could use events like "onclick=dothis()" in the dynamically loaded html and have the "dothis()" function in the dynamically loaded script tag. This would work but I would prefer to use event listeners. Is there another way to solve this problem? -
Pictures do not show up in Django
I have uploaded a CSV file with the names of the image addresses and put the images in my media folder (media/album_pics) but when running the side it doesn't show me the images, before this it did. how come? my model: class Album(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) release_date = models.CharField(max_length=10) artist = models.CharField(max_length=100) genre = models.CharField(choices=GENRE_CHOICES, max_length=20) image = models.ImageField(default='default2.jpg', upload_to='album_pics') spotify_url = models.URLField(max_length=250) -
I am not able to import the test_app model in the core/view.py
[enter image description heenter image description herere](https://i.stack.imgur.com/jeiya.png)enter image description here I want to import the Test_app class in core/view.py I am not able to import test_app in core ,I also added test_app in installed app in setting.py still not able to import ,Please help e=me with this problem -
Strange connection issue with Redis/Celery/Django/Kombu. Unable to use celery tasks
I have setup a celery task which connects to the Sendgrid API to update the contacts. However when the Celery and Celery Flower are running I cannot send tasks and it just repetitively sends error messages related to Kombu connecting. Here is a brief readout: Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: [E 230403 16:27:39 base_events:1753] Future exception was never retrieved Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: future: <Future finished exception=OperationalError('[Errno 111] Connection refused')> Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: Traceback (most recent call last): Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: yield Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/connection.py", line 433, in _ensure_connection Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: return retry_over_time( Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/utils/functional.py", line 312, in retry_over_time Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: return fun(*args, **kwargs) Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/connection.py", line 877, in _connection_factory Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: self._connection = self._establish_connection() Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/connection.py", line 812, in _establish_connection Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: conn = self.transport.establish_connection() Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: conn.connect() Apr 3 16:27:39 ip-172-31-5-114 pipenv[7862]: File "/var/www/cellar/ss/shared/.venv/lib/python3.9/site-packages/amqp/connection.py", line 323, in … -
Django signals created value wrong return
I am generating a reference number to an objects field. If the record is new, the signal will fill other fields before saving. If the record is not new, I also have an action for it. I will check for an objects specific field and see if it changed and do some other action. Here is a snippet of the signal function: @receiver(pre_save, sender=ProofOfPayment) def pre_save_for_proof_of_payment(sender, instance, created=False, **kwargs): print('created', created) if created: upload_date = datetime.datetime.now().strftime('%Y%m%d%H%M%S') reference_number = 'PAYMENT-' + upload_date instance.reference_number = reference_number received = PaymentStatus.objects.get(pk=1) # Received instance.payment_status = received else: obj = sender.objects.get(pk=instance.pk) if not obj.payment_status == instance.payment_status: if instance.payment_status.name == 'Completed': instance.expiry_date = datetime.datetime.now() + datetime.timedelta(days=30) I am simulating the process in the admin. I create a new record. When I create the new object, I get an error because the variable created is set to False, doing the else function in the snippet. obj = sender.objects.get(pk=instance.pk) ProofOfPayment matching query does not exist. I am not sure why the created value is set to False even if the record is new. When I don't place a default value in the function: def pre_save_for_proof_of_payment(sender, instance, created, **kwargs): I get this error: pre_save_for_proof_of_payment() missing 1 required positional argument: … -
Django and Time Zone for regions that no longer observe the Daylight Save Time (DST)
I have a Django project, time zone is enabled for multiple purposes, my TIME_ZONE = 'America/Mexico_City', however, since this year 2023, in this time zone it's no longer observed the DST, I use the localtime to get the right date/time in some cases, but it detects the DST >>> localtime(timezone.now()) datetime.datetime(2023, 4, 3, 10, 14, 49, 782365, tzinfo=<DstTzInfo 'America/Mexico_City' CDT-1 day, 19:00:00 DST>) >>> timezone.now() datetime.datetime(2023, 4, 3, 15, 14, 54, 953013, tzinfo=<UTC>) >>> datetime.now() datetime.datetime(2023, 4, 3, 9, 15, 7, 628038) datetime.now() has the correct date/time, of course I can change the localtime for datetime.now(), but there are a lot of them, I want to understand how I can "update" or "sync" my Django project so it take the correct DST when some region change it for both observe or not longer observe it.