Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
deploy two django projects with apache2 and mod_wsgi under windows server 2016
I am deploying two projects on Django, one of the two is going well but when I want to access the second, I have NOT FOUND on the browser here is my wsgi.py code from the first application: `import os,sys sys.path.append('C:/Apache24/htdocs/MEKAMBO') from django.core.wsgi import get_wsgi_application #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MEKAMBO.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "MEKAMBO.settings" application = get_wsgi_application()` here is my wsgi.py code for the second application: `import os,sys sys.path.append('C:/Apache24/htdocs/log_audit') from django.core.wsgi import get_wsgi_application #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'log_audit.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "log_audit.settings" application = get_wsgi_application() ` here is the httpd.conf code: `LoadFile "C:/Users/HELPDESK/AppData/Local/Programs/Python/Python312/python312.dll" LoadModule wsgi_module "C:/Users/HELPDESK/AppData/Local/Programs/Python/Python312/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp312-win_amd64.pyd" WSGIPythonHome C:/Apache24/htdocs/MEKAMBO/env WSGIPythonPath C:/Apache24/htdocs/MEKAMBO <VirtualHost *:80> ServerName www.mekambo.com DocumentRoot "C:/Apache24/htdocs/MEKAMBO/MEKAMBO" WSGIScriptAlias /mekambo "C:/Apache24/htdocs/MEKAMBO/MEKAMBO/wsgi.py" Alias /media/ C:/Apache24/htdocs/MEKAMBO/media/ Alias /static/ C:/Apache24/htdocs/MEKAMBO/static/ <Directory C:/Apache24/htdocs/MEKAMBO/static> Require all granted </Directory> <Directory C:/Apache24/htdocs/MEKAMBO/media> Require all granted </Directory> <Directory "C:/Apache24/htdocs/MEKAMBO/MEKAMBO"> <Files wsgi.py> Require all granted </Files> </Directory> <VirtualHost *:80> ServerName www.log_audit.com DocumentRoot "C:/Apache24/htdocs/log_audit/log_audit" WSGIScriptAlias /log_audit "C:/Apache24/htdocs/log_audit/log_audit/wsgi.py" <Directory "C:/Apache24/htdocs/log_audit/log_audit"> <Files wsgi.py> Require all granted </Files> </Directory> ` -
Extract the textContent of an element using hyperscript
I have 2 elements in the DOM <script id="info-length-lower" type="application/json">6</script> <script id="info-length-upper" type="application/json">6</script> And I need to get these in some hyperscript on one of the form fields, but nothing seems to give me a value. I've tried several variations: set lowerBound to the textContent of #info-length-lower set lowerBound to #info-length-lower.textContent ... and a few others along the way that I've forgotten now. How can I get this information out using hyperscript? -
Refer to another model and count its ManytomanyField
I have two models: class Post(models.Model): content = models.TextField(blank=False) author = models.ForeignKey("User", on_delete=models.CASCADE, related_name="author") timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): likes_count = self.liked_by.all().count() return { "id": self.id, "content": self.content, "author": self.author.username, "author_id": self.author.id, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "likes": likes_count } and class Liking_System(models.Model): users_who_like = models.ManyToManyField("User", related_name="users_liked") post = models.ForeignKey("Post", on_delete=models.CASCADE, related_name="liked_by") def __str__(self): return f"Post {self.post.id} is liked by {', '.join([user.username for user in self.users_who_like.all()])}" I want in my Post model, it linked to the Liking_System and count how many users that has liked the post and return it. How can I do that? How do I modify the "likes_count = self.liked_by.all().count()". For example my post#1 is liked by two users A and B, but it returned only 1? -
Method Not Allowed: /music/add/ "POST" Error 405 for Django rest Framework
I am creating a spotify like backend and I am trying to create a track So it would take a POST request I tried bunch of different approaches through stack overflow and any resource I could get to. POST http://127.0.0.1:8000/music/add/ Content-Type: application/json Authorization: token 3e356c812614c3d4344e0d06773c27387b1e4c12 { "title": "Evil Ways", "duration": "00:03:47", "release_date": "2023-09-03", "audio_file": "/media/tracks/Music_Library.musiclibrary.zip", "artist": 2, "album": 2, "genre": 1 } I am sending the request through a .rest file and I get the response HTTP/1.1 405 Method Not Allowed Date: Thu, 08 Feb 2024 09:11:56 GMT Server: WSGIServer/0.2 CPython/3.9.0 Content-Type: application/json Vary: Accept, Cookie Allow: OPTIONS, GET X-Frame-Options: DENY Content-Length: 41 { "detail": "Method \"POST\" not allowed." } the end point is in urls.py file from django.urls import path from . import views urlpatterns = [ # other paths # all get requests work path('add/', views.add_track) ] In my views.py file I have from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from .models import Track, Artist, Genre, Album from .serializers import TrackSerializer from rest_framework.decorators import api_view, authentication_classes , permission_classes from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated # ... other views @api_view(['GET', 'POST']) @authentication_classes([SessionAuthentication, TokenAuthentication]) @permission_classes([IsAuthenticated]) def add_track(request): if … -
How to call multiple variables in send_mail() function
enter image description here How do I call multiple variables in send_mail() message parameter function like employeeid,name, email,fromplace,toplace,vehicle,duration (see image). Also, I have stored all the data in the Script tag with the names given above and not in the views.py file. -
Django django-bootstrap-v5 works locally but failed with ModuleNotFoundError: No module named 'bootstrap5' on AWS Elastic beanstalk
I have a project that use the package: django-bootstrap-v5==1.0.11 everything works OK, but when I try to deploy to AWS Elastic Beanstalk server I get the error: ModuleNotFoundError: No module named 'bootstrap5' And when I delete the 'bootstrap5' from my INSTALLED_APPS the server is up... I'm new to Amazon EC2 service so not sure what is the write approach - Are all packages allowed? If not how can I check which one allowed and how to manually use others? will appreciate any help, Thanks! -
Django render_to_string not working on fieldname.help_text
I’m creating an app for a questionnaire and making use of the model fields help_text attribute, which represents the question of each data field. For this, I wrote some custom model form: class CustomModelForm(forms.ModelForm): """A customized ModelForm for Django. This class extends the base ModelForm class from Django's forms module. It provides additional functionality to handle errors and help text for form fields. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.errors: attrs = self[field].field.widget.attrs attrs.setdefault("class", "") attrs["class"] += " is-invalid" for field in self.fields: try: self.fields[field].help_text = self._meta.model._meta.get_field( field ).help_text except Exception: pass additionally I created a template tag together with a .html: @register.inclusion_tag("../templates/snippets/radioInlineField.html") def render_radioInlineInput_field(formfield): return {"formfield": formfield} {% with field=formfield %} <div class="col-sm-6 text-start"> {% if field.help_text %} <p class="mb-0">{{ field.help_text }}: </p> {% endif %} </div> <div class="col-sm-6 mt-0 "> {% for radio in field %} <div class="form-check form-check-inline"> {{ radio.tag }} <label class="form-check-label" for="id_{{ radio.id_for_label }}">{{ radio.choice_label }}</label> </div> {% endfor %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} </div> {% endwith %} Now everything works good with it, but if I have Form A (only consisting of the above mentioned type of fields) and … -
How to validate data when insert using raw SQL query
class Queue(models.Model): name = models.CharField(max_length=255, unique=True) api_token = models.CharField(max_length=255, default=secrets.token_hex(16)) class Message(models.Model): queue = models.ForeignKey(Queue, on_delete=models.CASCADE) subject = models.CharField(max_length=255) message = models.TextField() api_token = models.CharField(max_length=255) These are my models and I want to insert Message data using raw SQL query. But I want to match the api_token from the Message table to the selected Queue api_token when Insert. How to do that? -
Django ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS settings not fully understood
My Django server is running on 127.0.0.1:8001. I use nginx to reverse proxy my django server to port 80. The nginx config looks like this: server { listen 80; location / { proxy_pass http://127.0.0.1:8001; } location /static { root STATIC_ROOT; } } I got confused when I try to understand ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS settings. These 2 settings all don't work: ALLOWED_HOSTS = ["example.com"] CSRF_TRUSTED_ORIGINS = ["https://example.com"] Or ALLOWED_HOSTS = ["127.0.0.1"] CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1"] Only this works ALLOWED_HOSTS = ["127.0.0.1"] CSRF_TRUSTED_ORIGINS = ["https://example.com"] Can anybody explains why I need to set them differently? If possible, how does nginx reverse proxy work generally? -
(React-Django) Getting 403 Forbidden for uploading file to google cloud storage using signed url
I created signed url to upload files (mp3 video file upto 1GB) from the client side directly on cloud storage. But when I try to upload the file, I am getting following error: ` SignatureDoesNotMatch Access denied. The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method. ` This is how the URL was generated: https://storage.googleapis.com/bucket-name/filename ?X-Goog-Algorithm=GOOG4-RSA-SHA256 &X-Goog-Credential=something.iam.gserviceaccount.com%2xyz%2Fauto%2Fstorage%2Fgoog4_request &X-Goog-Date=20240207T120631Z &X-Goog-Expires=900 &X-Goog-SignedHeaders=content-type%3Bhost &X-Goog-Signature=21... Front end is in react and I am first making a call to get the signedurl and then uploading the file. React code : const responseForSignedUrl = await axios.get( `${baseUrl}/api/posts/getuploadurl/` ); if (responseForSignedUrl.status !== 200) { throw new Error("Failed to obtain signed URL."); } const signedUrl = responseForSignedUrl.data.url; // Upload video file to Cloud Storage using the signed URL const videoFormData = new FormData(); videoFormData.append("file", video_file); const uploadResponse = await axios.put(signedUrl, videoFormData, { headers: { "Content-Type": "video/mp4", }, onUploadProgress: (progressEvent) => { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); setProgress(percentCompleted); }, }); if (!uploadResponse.ok) { throw new Error("Failed to upload video file."); } Backend code for signed url generation: def generate_upload_signed_url_v4(request): """Generates a v4 signed URL for uploading a blob using HTTP PUT. Note that … -
How do I combine identical cells in a column using python xlwt?
I use python xlwt to generate an excel file (report). I can't combine the cells of the column with the same values (column A and column with totals) in any way. For example, I have attached screenshots of how I get the output now and what kind of output it needs to be brought to. My function generates a report of the following type: enter image description here Please help me to make it look like this: enter image description here Report generation function: def export_excel(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = ("attachment; filename=Numbers_" + str(datetime.datetime.now().strftime("%d/%m/%y")) + '.xls') wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Numbers', cell_overwrite_ok=True) row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Подразделение', 'Номер', 'Сумма', 'Итог (Сумма+ндс+абон.плата)', 'Итог по подразделению'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = ReportFilter(request.GET, queryset=Parser.objects.all().values_list( 'attachment__attachment', 'number', 'pay', 'result')).qs rows1 = Numbers.objects.filter(is_enabled=True).values_list('attachment__attachment', 'number') res = 0 temp = [] for item1 in rows: temp.append(item1) res += item1[3] for item2 in rows1: if Parser.objects.filter(number=item2[1]): None else: item2 = list(item2) item2.append(250) item2.append(250) res += item2[3] item2 = tuple(item2) temp.append(item2) temp.sort() temp = tuple(temp) for row in temp: row_num += 1 for col_num in range(len(row)): if isinstance(row[col_num], datetime.datetime): date_time = … -
Assistance Needed with Python/Django Backend Development for Portfolio Website [closed]
I'm new to backend development and currently working on my portfolio website using Python, Django, MongoDB, and APIs. However, I'm facing some issues and could use some assistance. If anyone experienced with these technologies could lend a hand, I'd greatly appreciate it. Thanks! -
is it safe to create django-allauth confirmation email table manually?
I am building a web app using Django, and I am using Django-Allauth for the authentication. Somehow when I was inspecting the database in mysql workbench I though a saw a duplicate table named account_EmailConfirmation and before I think about it I dropped the table and both of them dropped. Idk exactly know why they appeared as 2 tables and when I dropped one the other was deleted but anyway, i decided then to create the table again manually. operations = [ migrations.CreateModel( name='EmailConfirmation', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('sent', models.DateTimeField(null=True, blank=True)), ('key', models.CharField(max_length=64, unique=True)), ('email_address_id', models.ForeignKey(to='account.EmailAddress', on_delete=models.CASCADE)), ], options={ 'db_table': 'account_emailconfirmation', }, ), ] My question is this: Is this safe and okay to do, or is it going to cause issues later on? -
CKEditor update notification
Want to remove "This CKEditor 4.22.1 version is not secure. Consider upgrading to the latest one, 4.24.0-lts." from appearing in my Django admin's RichTextUploadingField. Currently using Django CKEditor 6.7.0m all settings are in settings.py only. Configs: CKEDITOR_CONFIGS = { "default": { "skin": "moono", "toolbar": "Custom", "allowedContent": True, "extraAllowedContent": "object\[id,name,width,height\];", "extraPlugins": "iframe", "iframe_attributes": { "sandbox": "allow-scripts allow-same-origin allow-popups allow-presentation allow-forms", "allowfullscreen": "", "loading": "lazy", "referrerpolicy": "no-referrer-when-downgrade", }, "toolbar_Custom": \[ { "name": "document", "items": \[ "Source", "-", "Save", "NewPage", "Preview", "Print", "-", "Templates", \], }, { "name": "clipboard", "items": \[ "Cut", "Copy", "Paste", "PasteText", "PasteFromWord", "-", "Undo", "Redo", \], }, {"name": "editing", "items": \["Find", "Replace", "-", "SelectAll"\]}, { "name": "forms", "items": \[ "Form", "Checkbox", "Radio", "TextField", "Textarea", "Select", "Button", "ImageButton", "HiddenField", \], }, "/", { "name": "basicstyles", "items": \[ "Bold", "Italic", "Underline", "Strike", "Subscript", "Superscript", "-", "RemoveFormat", \], }, { "name": "paragraph", "items": \[ "NumberedList", "BulletedList", "-", "Outdent", "Indent", "-", "Blockquote", "CreateDiv", "-", "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock", "-", "BidiLtr", "BidiRtl", "Language", \], }, {"name": "links", "items": \["Link", "Unlink", "Anchor"\]}, { "name": "insert", "items": \[ "Image", "Flash", "Table", "HorizontalRule", "Smiley", "SpecialChar", "PageBreak", "Iframe", "Embed", \], }, "/", { "name": "styles", "items": \["Styles", "Format", "Font", "FontSize"\], }, {"name": "colors", "items": \["TextColor", "BGColor"\]}, {"name": "tools", … -
Update with save() method doesn't work in django
I'm using multiple connections to different databases. But nothing happen when I'm trying to update data in db using save() method. I mean everything's works but data still not updated. How can I fix it? def save_object_using_dynamic_db(model, obj_id, db_alias, **kwargs): """ Save an object into the specified database alias. """ connection = connections[db_alias] print(f"{connection = }") try: obj_to_save = model.objects.using(connection.alias).get(id=obj_id) except model.DoesNotExist: # If the object doesn't exist, you may want to handle this case accordingly print(f"Object with id {obj_id} does not exist in the database.") return None for field, value in kwargs.items(): if hasattr(obj_to_save, field): print(f"{obj_to_save = }, {obj_id = }, {field = }: {value = }") setattr(obj_to_save, field, value) try: # obj_to_save.full_clean() # Check model validation obj_to_save.save(using=connection.alias) print(f"Object saved: {obj_to_save}") return obj_to_save except ValidationError as e: print(f"Validation error: {e}") return None except Exception as e: print(f"Unexpected error: {e}") return None # obj_to_save.save(using=db_alias) # print(f"{obj_to_save = }") # return obj_to_save -
IntegrityError CHECK constraint failed on Django
this is my error: IntegrityError at /caja_chica/comprobantes/9/editar/ CHECK constraint failed: caja_chica_cajachica Request Method: POST Request URL: http://127.0.0.1:8000/caja_chica/comprobantes/9/editar/ Django Version: 3.2.5 Exception Type: IntegrityError Exception Value: CHECK constraint failed: caja_chica_cajachica the problem is on my model, when i tried to save a Comprobante object trying before making an operation. This is my model Comprobante: class Comprobante(models.Model): TIPO_A = 1 TIPO_B = 2 TIPO_C = 3 TIPO_T = 4 TIPO_X = 5 TIPO_CHOICES = ( (TIPO_A, 'A'), (TIPO_B, 'B'), (TIPO_C, 'C'), (TIPO_T, 'T'), (TIPO_X, 'X'), ) caja_chica = models.ForeignKey(CajaChica, on_delete=models.PROTECT) lote = models.ForeignKey(Lote, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='lote_comprobantes') numero = models.CharField(max_length=13) tipo = models.PositiveSmallIntegerField(choices=TIPO_CHOICES, default=TIPO_T) ente = models.ForeignKey(Ente, on_delete=models.PROTECT) fecha = models.DateField() partida_presupuestaria = models.ForeignKey(PartidaPresupuestaria, on_delete=models.PROTECT) detalle = models.CharField(max_length=100) importe = models.DecimalField(max_digits=7, decimal_places=2) history = HistoricalRecords() def __str__(self): return self.numero def save(self, *args, **kwargs): super(Comprobante, self).save(*args, **kwargs) self.caja_chica.disponible -= self.importe self.caja_chica.save() def get_absolute_url(self): """ Devuelve la url para acceder a una instancia particular de Comprobante. """ return reverse('caja_chica:comprobante_update', args=[str(self.id)]) this is the function that broke my model: def save(self, *args, **kwargs): super(Comprobante, self).save(*args, **kwargs) self.caja_chica.disponible -= self.importe self.caja_chica.save() and this is my model CajaChica: class CajaChica(models.Model): FUENTE_11 = 11 FUENTE_12 = 12 FUENTE_13 = 13 FUENTE_CHOICES = ( (FUENTE_11, FUENTE_11), (FUENTE_12, FUENTE_12), (FUENTE_13, … -
Django and nginx connected via a bridge network.How to parse domain and pass it to the proxy_pass?
I am working on a multi tenant app. I have nginx as a rev-proxy When a tenant registers I create a docker image and name it based on his subdomain Lets call tenant1 t1 and tenant2 t2. So t1.localhost.web to should be routed to t1.web:8000 where t1 is extracted from url in nginx by regex and concatenated to ".web:8000" and it becomes t1.web:8000 and set to proxy_pass in nginx.conf These dockers containers also have a bridged network and they can be reached by their names. So if you bash into one of these containers you can ping or curl each other by their names it worksm so they are reachable by name curl http://t1.web:8000 actually works given if you are "bash"ed into nginx container this is my config file events { worker_connections 4096; ## Default: 1024 } http { # Redirect HTTP to HTTPS server { server_name ~^(?<subdomain>.+)\.app\.dev; listen 80; location / { set $domainweb "http://$subdomain.web:8000"; proxy_pass $domainweb; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } } to debug I tried to exclude the subdomain variable and tried location / { set $domainweb "http://t1.web:8000"; proxy_pass $domainweb; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } that also did not work but when … -
Troubles AJAX Integration with Django
When I save products from ajax to db, it always redirects me to failed page and saying 500 server error views.py from cart.cart import Cart from django.http import JsonResponse from django.shortcuts import render from .models import Order, OrderItem, ShippingAddress # Create your views here. def checkout(request): if request.user.is_authenticated: try: shipping_address = ShippingAddress.objects.get(user=request.user.id) context = {'shipping': shipping_address} return render(request, 'payment/checkout.html', context=context) except: return render(request, 'payment/checkout.html') else: return render(request, 'payment/checkout.html') def complete_order(request): if request.POST.get('action') == 'post': name = request.POST.get('name') email = request.POST.get('email') address1 = request.POST.get('address1') address2 = request.POST.get('address2') city = request.POST.get('city') state = request.POST.get('state') zipcode = request.POST.get('zipcode') print(name) shipping_address = (address1 + "\n" + address2 + "\n" + city + "\n" + state + "\n" + zipcode ) cart = Cart(request) total_cost = cart.get_total() if request.user.is_authenticated: order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address, amount_paid=total_cost, user=request.user) order_id = order.pk for item in cart: OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'], price=item['price'], user=request.user) else: order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address, amount_paid=total_cost) order_id = order.pk for item in cart: OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'], price=item['price']) order_success = True response = JsonResponse({'success':order_success}) return response urls.py from django.urls import path from . import views urlpatterns = [ path('checkout', views.checkout, name='checkout'), path('complete-order', views.complete_order, name='complete-order'), path('payment-success', views.payment_success, name='payment-success'), path('payment-failed', views.payment_failed, name='payment-failed'), ] checkout.html {% include "store/base.html" %} {% … -
"Waiting list" or delay when sending emails with Django and the win32 library
I have just discovered something in the provided code, and I would like to explain it to you. During my tests with the email sending using this code, everything seemed to work correctly, but a specific issue arose. Let's say I have three emails to send: email 1, email 2, and email 3. When I send email 1, the console returns a 200 OK status, but the email doesn't reach my inbox. Then, when I proceed to send email 2, the console again returns a 200 OK status, and although a new email appears in my inbox, it turns out to be email 1. After waiting several minutes without receiving any updates or new emails, I proceed to send email 3. At this point, the console once again shows a 200 OK status, and, surprisingly, I receive a new email in my inbox, but now it is email 2. ` class ApiSendMailCreateNewReporter(APIView): def get(self, request, id_headerRequest): try: # Obtener el objeto HeaderRequest o devolver un error 404 si no existe header_request = get_object_or_404(HeaderRequest, id=id_headerRequest) # Serializar el objeto HeaderRequest serializer_header_request = HeaderRequestSerializer(header_request) usuario_id = serializer_header_request.data['id_user_id'] require_date = serializer_header_request.data['require_date'] customer = serializer_header_request.data['customer'] # Obtener la instancia de Engineers con role='admin' o … -
Why Is a migration file created (over and over) when i run makemigrations
Am facing a somehow funny issue...every time i migrate,i get this description Your models in app(s): 'organization_app' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. so i follow what django says and i makemigrations,this migration file is created # Generated by Django 4.2.3 on 2024-02-07 20:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("organization_app", "0002_alter_penaltymodel_tenant_penalty_choice"), ] operations = [ migrations.AlterField( model_name="penaltymodel", name="tenant_penalty_choice", field=models.CharField( choices=[("PERCENT", "Percent"), ("AMOUNT", "Amount")], default="AMOUNT", max_length=20, ), ), ] when i migrate,i get the same description i stated earlier 'manage.py makemigrations' and when i migrate, the same migration file is created over and over..is this a #bug -
error to show week name django-jalali-date and django
I have developed a website using Django for appointment scheduling purposes. This website utilizes Persian dates and the Jalali date library from Django Jalali. However, I am encountering an issue where on my local system, it displays correctly, showing Persian month names, but when deployed on the server, it displays month names in English and day names in English as well.Could someone provide guidance on resolving this matter? See these pictures: on server : img 1 on site - img 2 on site on my system: img 1 on site - img 2 on site However, I am encountering an issue where on my local system, it displays correctly, showing Persian month names, but when deployed on the server, it displays month names in English and day names in English as well. -
how to solve JSONDecodeError
i made a edit function to edit the post which works fine i can see that in the console when the post button is clicked and when i refresh page the value is being updated but i am getting this error for some reason and i am not able to solve it. def edit_post(request, post_id): if request.method == 'POST': data = json.loads(request.body) post = Post.objects.get(pk=post_id) post.content = data['content'] post.save() return JsonResponse({"message": "Post edited successfully.", "data": data['content']}) getCookie = (name) => { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length == 2) return parts.pop().split(';').shift(); } update = (id) => { const updatedValue = document.getElementById(`textarea_${id}`).value fetch(`/edit_post/${id}`, { method: "POST", headers: { "Content-type": "application/json", "X-CSRFToken": getCookie("csrftoken") }, body: JSON.stringify({ content: updatedValue }) }) .then(response => response.json()) .then(result => console.log(result) ) } JSONDecodeError at /edit_post/18 Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: http://127.0.0.1:8000/edit_post/18 Django Version: 5.0 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: C:\Program Files\Python312\Lib\json\decoder.py, line 355, in raw_decode Raised during: network.views.edit_post Python Executable: C:\Program Files\Python312\python.exe Python Version: 3.12.0 -
The problem of using the Arabic language in django links
I am programming a website in Django I want to put the Arabic language in my link, but when I make the link in Arabic and when I choose it, it takes me to the page page not found Note: This only happens on the hosting server, meaning it does not happen on localhost urls.py from django.urls import path, re_path from . import views urlpatterns = [ # pages path('',views.index,name='index'), path('الصفحة/',views.listArticle,name='listArticle'), path('TravelTips/',views.TravelTips,name='TravelTips'), # view article path('الصفحة/<str:slug_url>/', views.view_article, name='Page_Article'), path('TravelTips/<str:slug_url>/',views.view_article,name='Page_Article'), ,] I expected that the problem was in the slug, but it turned out that Django in general did not accept Arabic letters -
CDN imports for PDF.js viewer.html in Django templates
I am trying to add the PDF.js viewer as it appears in the official demo in an HTML iframe of my Django template. I do not want include any of the assets of PDF.js in my repository and I want all my script and stylesheet HTML tags to refer to a CDN resource. Since the documentation contains a note that users of the library should not just copy/paste the web/viewer.html, I have created my own modified version named custom_viewer.html, which includes a subset of the features of the official demo. The prebuilt version of the library includes the following four tags in the demo web/viewer.html: <link rel="resource" type="application/l10n" href="locale/locale.json"> <script src="../build/pdf.mjs" type="module"></script> <link rel="stylesheet" href="viewer.css"> <script src="viewer.mjs" type="module"></script> My question is what are the corresponding CDN links to get this working without downloading the PDF.js library on the server? I have managed to replace the pdf.mjs file reference with a CDN link. More specifically, I have verified that when I copy the prebuilt PDF.js (version 4.0.379) in my static folder and I modify the paths as follows: {% load static %} <link rel="resource" type="application/l10n" href="{% static 'my-django-app/pdfjs-4.0.379-dist/web/locale/locale.json' %}"> <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@4.0.379/build/pdf.mjs" type="module"></script> <link rel="stylesheet" href="{% static 'my-django-app/pdfjs-4.0.379/web/viewer.css' %}"> <script src="{% static … -
Django, Subquery, more than one row returned by a subquery used as an expression
Here is my model structure class ContentFlag(models.Model): user = models.ForeignKey( User, verbose_name="user", related_name="object_flags", on_delete=models.CASCADE, ) flag = models.CharField(max_length=30, db_index=True) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class Article(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("owner"), null=True, blank=True, editable=True, on_delete=models.SET_NULL, related_name="owned_pages", ) flags = GenericRelation(ContentFlag, related_query_name="%(class)s_flags") title = models.CharField(max_length=255) class User(index.Indexed, AbstractUser): email = EmailField(verbose_name="email", unique=True, null=True, blank=True) name = models.CharField( blank=True, max_length=100, ) flags = GenericRelation(to="core.ContentFlag") I need to calculate User rating based on Flags number. Here is what I do for that subquery_plus = ContentFlag.objects.filter( Q(article_flags__owner_id=OuterRef("id")), flag=LIKEDIT_FLAG, ).values("id") top_users = ( User.objects.annotate( rating_plus=Count(Subquery(subquery_plus)), ).order_by("-rating_plus") ) But I got an error django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression How can I fix that?