Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
class not seing it's properties
my class from django.db import models from django.contrib.auth.models import User class Task(models.Model): id: models.UUIDField(unique=True, auto_created=True) content: models.CharField(default="") deadline: models.IntegerField(default=None) creationDate: models.DateField(auto_now_add=True) author: models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) -> str: return str(self.id) + str(self.content) my error: File "/Users/ironside/Documents/Python/PythonDjango-Project/api/models.py", line 13, in str return str(self.id) + str(self.content) AttributeError: 'Task' object has no attribute 'content' I tested, and all other properties give the same error ('content' changes to property name). It's as if it only sees id as valid property. I'd like to be able to print the id + content or any other property -
django.core.exceptions.ImproperlyConfigured Django 4.2.6
So, I started refactoring my project, but I also deleted my migrations folder (which I just learned is a no-no.) Now I can't run the server or tests. I only get the error below. File "C:\Users\Documents\projects\venv\Lib\site-packages\django\urls\resolvers.py", line 237, in _compile raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: "^users\.(?P<format>[a-z0-9]+)/?\.(?P<format>[a-z0-9]+)/?$" is not a valid regular expression: redefinition of group name 'format' as group 2; was group 1 at position 37 I tried starting the project again in a separate folder with a new db, copying and pasting the necessary code, then running makemigrations and migrate, but the same error keeps appearing. I don't want to have to start from scratch again, so if there's a way to fix it, please let me know. I still have the migrations table and info in my first db, if that helps. -
How to add element class in ckeditor on django?
I'm trying add default element class in ckeditor on Django website like. <ul class="sm-circle"></ul> -
Set default widget for custom model field in django 4
I would like to have a custom field which uses a specific widget. In my example it's a model.CharField derived field. It should always use forms.Textarea instead of the default forms.TextInput. I want to have this definition in MyCustomField class, to not always have to override the admin form to use the specific widget. This is my code: class MyCustomField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 # Set the fixed max length here super().__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {'widget': forms.Textarea} defaults.update(kwargs) return super().formfield(**defaults) It just shows forms.TextInput widget instead of forms.Textarea - any idea what is wrong? -
How do I inherit from different templates in Djanog based on whether the user is logged in or not
Exactly what the question says. I have three templates base.html, logged_in_base.html, and page.html. I want page.html to extend base.html when the user isn't logged in and to extend logged_in_base.html when the user is logged in. How do I do this? (This is basically because I have a different navbar for logged in users and not logged in users.) -
Textarea adding whitespaces everytime I submit
I have a form with textarea and everytime I click the submit button and use it again, it adds whitespaces. {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <h1>Edit Page</h1> <form method="POST" action="{% url 'edit' title=title %}"> {% csrf_token %} <div id="title"> <label>Title:</label> <textarea name="title" class="form-control" style="width: 600px; height: 50px;">{{ title }}</textarea> </div> <div id="body"> <label>Body:</label> <textarea name="content" class="form-control" rows="5" style="width: 600px; height: 400px;">{{ content }}</textarea> </div> <input type="submit" class="btn btn-primary" value="Edit" style="margin-left: 546px; margin-top: 10px;"> </form> {% endblock %} I need to know how do I prevent it adding whitespaces -
Run a specific function on a specific field in a queryset
I am trying to run a function on a specific field in a queryset before i send it to the template for rendering. I have the following models. class Customer(models.Model): name = models.CharField(max_length=255) class Device(models.Model): cid = models.ForeignKey(Customer, on_delete=models.CASCADE) name = models.CharField(max_length=255) oid = models.TextField(null=True) I have the following view, that i am trying to run the checkStatus function on queryset field of objectid, but everytime it runs i get the following error, the "info" is the value that the checkStatus function is returning back. error TypeError: QuerySet.annotate() received non-expression(s): info. views.py def device_detail(request, cid): customers = models.Customer.objects.all() customer_details = get_object_or_404(models.Customer, id=cid) device_details = customer_details.device_set.all() device_details.annotate(checkStatus("objectid")) return render(request, 'devices/detail.html', { 'device_details': device_details }) -
deployed django webpage using apache and mode_wsgi doesnt show other pages aside from index.html
I am totally new to the world of Django, I recently tried to deploy my website on production server and I have been successful to some extent. I deployed the website on a windows base VPS, using apache and mode_wsgi. the webpage is up and running, I can view it on localhost, the problem is when I try to show other pages of the website like "localhost/about", it gives me " Not Found The requested resource was not found on this server. " does anybody had the same issue? any help in how to solve it would be much appreciated -
Django not sending debug errors in production
I have a django app running on production but server errors are not sent to the established e-mail. This is my settings.py: ADMINS = [('Foo the man', "******@gmail.com")] SERVER_EMAIL = os.getenv('SERVER_EMAIL') EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_HOST_IMAP = os.getenv('EMAIL_HOST_IMAP') EMAIL_PORT = '587' EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') Regular e-mails from within the app are being sent correctly, but debug errors are not sent and I can't figure out why. -
Accessing model attributes results in Self not defined error
Can anyone help me understand why I am receiving the error self is not defined while accessing a class attribute? Thanks for your help class Receipt(models.Model): "" receipt_id = models.AutoField( primary_key=True, db_comment="" ) store_name = models.TextField( max_length=255, default="Unidentified", db_comment="" ) total_amt = models.DecimalField( max_digits=6, decimal_places=2, default=0.00, db_comment="" ) def create_from_document(document): "" if (document is None): return False self.store_name = document.store_name self.total_amt = document.total_amt self.save() return self -
Why does my Django view return 'Reverse for 'initiate_transcription' with arguments '('',)' not found'?
A user uploads a file on page 1 and the site redirects them to page 2 where they can click a button which triggers the service. I'm trying to create a unique URL for each user upload and I know the error has to do with the {% url 'initiate_transcription' session_id %} in HTML page 2 form but i'm not sure what to change. Here is the code: urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.transcribeSubmit, name = "transcribeSubmit"), path("init-transcription/<str:session_id>/", views.initiate_transcription, name = "initiate_transcription"), ] views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) session_id = str(uuid.uuid4()) request.session['session_id'] = session_id # Render the 'transcribe-complete.html' template to a string return JsonResponse({'redirect': reverse('initiate_transcription', args=[session_id])}) else: else: form = UploadFileForm() @csrf_protect def initiate_transcription(request, session_id): if request.method == 'POST': try: # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcript = transcribe_file(path_string,audio_language, output_file_type ) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, … -
Django inline with PolymorphicParentModelAdmin
i have a problem with my CreationInline, i have this code in models.py: class Creation(PolymorphicModel): """Model representing a creation.""" original_title = models.CharField('Título original', max_length=10000, null=True, blank=True,) subtitles = models.TextField('Subtítulos, capítulos y entregas', null=True, blank=True,) authorship = models.TextField('Autoría', null=True, blank=True,) publication_year = models.IntegerField("Año de publicación",default=2023, choices=((i,i) for i in range(1930, 2024))) synopsis = models.TextField('Sinopsis', null=True, blank=True,) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True,) keywords = models.ManyToManyField(KeyWord, blank=True) product = models.OneToOneField("Product", on_delete=models.CASCADE, related_name="product_creation") def __str__(self): return self.product.title class MediaCreation(Creation): original_language = models.ForeignKey(Language, on_delete=models.SET_NULL,blank=True, null=True) IMDb = models.CharField(max_length=10000,blank=True, null=True) commertial_editions = models.CharField('Ediciones comerciales', max_length=10000,blank=True, null=True) class Movie(MediaCreation): """Model representing a Movie.""" remastering = models.TextField('Reedición', null=True, blank=True) direction = models.TextField('Dirección', null=True, blank=True) producer = models.TextField('Producción', null=True, blank=True) genre = models.ManyToManyField(Genre, limit_choices_to={"type": "Movie"}) there are other models that inherit from Creation, such us Novel, Comin, etc. My code in admin.py is: class CreationInline(NestedStackedInline): model=Creation class CreationParentAdmin(PolymorphicParentModelAdmin): """Parent admin class for Creation model.""" base_model = Creation child_models = (Movie, Musica, TVSerie, Videogame, Theatre) @admin.register(Creation) class CreationAdmin(CreationParentAdmin, DisableAddButtonModelAdmin): """Admin class for Creation model.""" base_model = Creation readonly_fields = ('product',) child_models = (Movie, Musica, TVSerie, Videogame, Theatre, Novel, Comic, BoardGame) list_filter = (PolymorphicChildModelFilter, ) list_display = ('get_product_title', 'original_title', 'authorship', 'publication_year') def get_product_title(self, obj): return obj.product.title # Obtiene el título … -
Printing to thermal printer in python
I have been trying to print on a POS printer and a label printer, depending on the running function. Here is where I am at: import win32print, win32ui, win32con # X from the left margin, Y from top margin # both in pixels X=50; Y=50 # Separate lines from Your string # for example:input_string and create # new string for example: multi_line_string # @@@@@@@ lable = Lable.objects.all().last() # @@@@@@@ multi_line_string = label_text.splitlines() the_name_will_appear_on_printer_spool = str(f"print_job{lable.id}") hDC = win32ui.CreateDC () # Set default printer from Windows: # hDC.CreatePrinterDC (win32print.GetDefaultPrinter ()) hDC.CreatePrinterDC(win32print.OpenPrinter(printers.label)) hDC.StartDoc (the_name_will_appear_on_printer_spool) hDC.StartPage () for line in multi_line_string: hDC.TextOut(X,Y,line) Y += 50 print(hDC.TextOut.text()) hDC.EndPage () hDC.EndDoc () message.success(request, 'Test printer job send') I have been using p = win32print.OpenPrinter("EPSON LX-350") to grab a specific printer but in this case i need to use something like this: hDC.CreatePrinterDC (win32print.OpenPrinter("EPSON LX-350")). The problem is I'm getting this error: Objects of type 'PyHANDLE' can not be converted to Unicode. Since i grabbed this from a 2013 answer there may be a better way to do this, I'm open to suggestions. Thank you in advance -
DJango Left join issues
LEFT JOIN ISSUE Model1 KPI_ID KPI_Name 1 KPI1 2 KPI2 3 KPI3 4 KPI4 Model2 Emp_Name KPI_ID Amount Mr. A 1 100 Mr. A 3 200 Mr. B 2 300 Mr. B 4 400 Output For Employe : Mr. A KPI_ID KPI_Name Amount 1 KPI1 100 2 KPI2 NULL 3 KPI3 200 4 KPI4 NULL For Employe : Mr. B KPI_ID KPI_Name Amount 1 KPI1 NULL 2 KPI2 300 3 KPI3 NULL 4 KPI4 400 Django left join issue -
best practice for dynamic filtering
I want to filter with keywords the user can enter. for example: models.py: class Product(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() now I want to let the user enter "category": "teapot" or "name": "IKEA Glas 0.5L" and the code should in the get_queryset method execute: def get_queryset(self): VALUE = self.request.GET.keys(SOMEPARAM) return Product.objects.filter(SOMEPARAM__contains=VALUE) how can this be done (I know I can do a lot of if clauses, but my model is quite large in terms of fields that can all be handled equally. so for example for the IKEA example that would be: Product.objects.filter(name__contains="IKEA Glas ...") -
Getting CORS error after adding Dockerfile to my Django project
So to keep it brief, I have a fullstack application which is deployed on Railway. Everything worked perfectly. Then I decided to integrate celery so I can run some tasks in background. Now in order to use celery in production I wanted to containerize my Django app where it can also run celery. So I followed some tutorials and added Dockerfile to my Django app. Dockerfile: FROM python:3.9.7 WORKDIR /app COPY . /app RUN pip install -r requirements.txt ENV DJANGO_SETTINGS_MODULE=backend.settings ENV CELERY_BROKER_URL=redis://default:***********************-43.railway.app:**** ARG RAILWAY_ENVIRONMENT ENV PORT = 8080 EXPOSE 8080 CMD ["python", "-m", "celery", "-A", "backend", "worker", "--loglevel=info","--pool=solo"] Everysince I added this, my application is facing this CORS issue..I dont know why and I searched thru google and I couldnt find any answers, I am new to Docker so I hope to get some insight on this. Here is my CORS config in Django: CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'https://checkout.stripe.com', 'https://sendit-frontend-production.up.railway.app' ] CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
How to get a prefilled authorization key in swagger with drf-specatular
I use django, drf and drf-spectacular. I create swagger documentation. Some endpoints require authentication. I can authenticate in swagger by pressing authorize and filling in the token. I would like that this filled in automatically for me. How do I do that? I tried to add preauthorizeApiKey to my settings, like this: SPECTACULAR_SETTINGS = { 'SWAGGER_UI_SETTINGS': { 'preauthorizeApiKey': 'Token my-secret-token' } } It doesnt work. -
after implementing serial number the sorting of serial number is not working.answer will be appreciated
after implementing serial number the sorting of serial number is not working.answer will be appreciated. i did serial number of jquery datatable.i used django and jquery datatable and after implementing serial number the sorting of serial number is not working.answer will be appreciated. -
Why do get requests to amazon.nl work but not to amazon.com / amazon.de?
Currently I am trying to build an amazon web scraper which scrapes some information of an item from the product page. For this I am using LXML and parsing the data using xpath. The main problem I am facing is that when I make a get request to amazon.nl only about 1/10 of them are successfull, but when I try to make one to amazon.de, or amazon.com, it takes a very long time for it to return an answer(if it ever does). HEADERS = ({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/117.0.0.0 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5'}) while True: response = requests.get(URL, HEADERS) if response.status_code != 503: break currently this is all the code I am using to make the get requests. Can someone help on how this could be improved (better success ratio) or explain why I cant seem to make get requests to amazon.de / amazon.com also as I side not I am living in the netherlands which could play a part on why I can access amazon.nl -
Django logging filter used at startup, but not during HTTP events
I have a Django project which produces a lot of useless log messages when static entities are fetched via HTTP GET. I tried this in settings.py LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { # <-- I added this 'skip_static_media': { '()': 'django.utils.log.CallbackFilter', 'callback': do_skip_static_media } }, "handlers": { "console": { "class": "logging.StreamHandler", "filters": ['skip_static_media'], # <--- I added this }, }, "root": { "handlers": ["console"], "level": "WARNING", }, } with def do_skip_static_media (record): # This is for debugging only import sys sys.stderr.write (">>>do_skip_static_media:" +repr(record)) msg = record.args[0] if msg.startswith ("GET /debughistory_sidebar/") \ or msg.startswith ("GET /static/"): return False return True What happens is that the log shows this during startup Watching for file changes with StatReloader >>>do_skip_static_media:<LogRecord: django.utils.autoreload, 20, /django-template-venv/lib/python3.10/site-packages/django/utils/autoreload.py, 668, "Watching for file changes with %s">Watching for file changes with StatReloader Performing system checks... but do_skip_static_media is not used during any HTTP requests. How do I catch every HTTP event and filter those? -
Error message "WebSocket HANDSHAKING - WebSocket REJECT - WebSocket DISCONNECT" in Django Channels
I recently followed the official Django Channels documentation (version 4.0.0) to set up WebSockets in my Django project. I've gone through the documentation tutorial and configured my project correctly. However, when I attempt to test the service using websocketking, I'm encountering a handshaking issue. Here are some details about my configuration: My asgi.py file looks like this: import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "schatai.settings") django_asgi_app = get_asgi_application() import schatai.routing application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(schatai.routing.websocket_urlpatterns)) ), } ) My consumers.py file looks like this: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class WsTestConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "chat_message", "message": message} ) # Receive message from room group def chat_message(self, event): message = event["message"] # Send message to WebSocket self.send(text_data=json.dumps({"message": message})) My routing.py file looks like this: from django.urls import re_path, path from . import consumers websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.SchataiConsumer.as_asgi()), path(r"ws/", consumers.WsTestConsumer.as_asgi()), ] I've also configured my settings.py file in accordance with the documentation. … -
I am creating an inventory mgt app, however when i try to return_item using_item Used i get an error # ValueError at /return_item/
I am creating an inventory mgt app, however when i try to return_item using_item Used i get an error # ValueError at /return_item/ when i try to return an item say x was give 5 bags of cement but ended up using 2.5 x returns the 2.5 items remainining but when i try to do this gives me an error AS stated above Django Model Definitions: IssueItem: class IssueItem(models.Model): id = models.BigAutoField(primary_key=true) person = models.ForeignKey(Person, on_delete=models.CASCADE) grouped_item = models.ForeignKey(GroupedItems, on_delete=models.CASCADE, related_name='issue_items') units_issued = models.DecimalField(max_digits=7, decimal_places=2, default=0) Date = models.DateField(default=timezone.now) def save(self, *args, **kwargs): self.grouped_item.calculate_totals() super().save(*args, **kwargs) return_item: python Copy code class return_item(models.Model): id = models.BigAutoField(primary_key=true) person = models.ForeignKey(Person, on_delete=models.CASCADE) grouped_item = models.ForeignKey(GroupedItems, on_delete=models.CASCADE, related_name='returned_items') units_returned = models.DecimalField(max_digits=7, decimal_places=2, default=0) Date = models.DateField(default=timezone.now) def save(self, *args, **kwargs): self.grouped_item.calculate_total() super().save(*args, **kwargs) def __str__(self): return self.Person GroupedItems: python Copy code class GroupedItems(models.Model): id = models.BigAutoField(primary_key=true) grouped_item = models.CharField(max_length=30, unique=true) total_units = models.DecimalField(max_digits=9, decimal_places=2, default=0) total = models.PositiveIntegerField(default=0) units_used = models.DecimalField(max_digits=8, decimal_places=2, default=0) units_available = models.DecimalField(max_digits=8, decimal_places=2, default=0) Units_returned = models.DecimalField(max_digits=8, decimal_places=2, default=0) def calculate_total(self): return_items = self.returned_items.all() self.Units_returned = return_items.aggregate(units_returned=Sum('units_returned'))['units_returned'] or 0 self.units_used = self.units_used - self.Units_returned def calculate_totals(self): issue_items = self.issue_items.all() self.units_used = issue_items.aggregate(units_issued=Sum('units_issued')['units_issued'] or 0 self.units_used = self.units_used - self.Units_returned self.units_available … -
Cannot Email By GoDaddy Office365 in Django ([Errno 101] Network is unreachable)
I have deployed my Django project on GoDaddy hosting. I have a problem while emailing by SMTP server using the provided Office365 mail on GoDaddy. The config which I set for emailing is code below. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST_USER = 'no-reply@domain.com' EMAIL_HOST_PASSWORD = 'password' But while sending an email by the send function from an instance of Django EmailMessage class, error “[Errno 101] Network is unreachable” is being returned (I have also tried different ports none of them has solved the problem yet). I thank anyone to guide me with the solution. Thanks, -
How to make Model QuerySet from a Django model instance
I have a model instance in Model's clean() method, and I want to add it to a QuerySet like below. def clean(self) -> None: #here self == model instance I need to add to queryset if self.id: from django import forms g=dag.DAG() g.create(self) if not g.validate_DAG(): self.custom_exception="Check hierarchy of users, cyclic dependency being created" raise forms.ValidationError(f"{self.custom_exception}") return super().clean() def create(self, update_cashback_relation): try: # Create a directed graph from catalog.models import UserRelationCashback self.G = nx.DiGraph() # # Add nodes to the graph user_relations_data=UserRelationCashback.objects.all() user_relations_data.get(id=update_cashback_relation.id).delete() user_relation_updated=user_relations_data.get(id=update_cashback_relation.id) print(user_relations_data.get(id=update_cashback_relation.id).__dict__) user_relations_data = user_relations_data | update_cashback_relation #this won't work as we must have both queryset, but i have a model instance and a queryset user_relations=user_relations_data.values("user", "manager", "product_group_category_warranty") users=user_relations.distinct().values_list("user", flat=True) # Add nodes to the graph for user in users: self.G.add_node(user) # Add directed edges to the graph for user_relation in user_relations: self.G.add_edge(user_relation.get('user'), user_relation.get('manager')) # Visualize the directed graph pos = nx.spring_layout(self.G) matplotlib.use('Agg') fig, ax = plt.subplots() # Draw the directed graph with arrows nx.draw(self.G, pos, with_labels=True, node_size=500, node_color='skyblue', font_size=10, font_color='black', arrows=True, ax=ax) # Save the graph as an image plt.savefig('directed_graph.png', format='png') plt.show() except Exception as e: raise Exception(f"{e}") -
why i use enctype='application/json' but CONTENT_TYPE still be application/x-www-form-urlencoded
<form enctype='application/json' action="{% url 'xxx' %}" method="post"> {% csrf_token %} <input type='number' name='bottle-on-wall' value='1'> <input type='number' name='bottle-on-wall' value='2'> <input type='number' name='bottle-on-wall' value='3'> <button type="submit">send</button> </form> CONTENT_TYPE 'application/x-www-form-urlencoded' how can i send the form data as json to server