Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No Tag matches the given query. on localhost:8000/filter/en
I've been working on a project, where I want to filter a resource on a page by language. But everytime I use that filter, i'm getting redirected to a 404-Page. This is my View: class SomeView(LoggedUserWithOrganizationMixin, ListView): paginate_by = 12 def get_queryset(self): qs = Example.objects.all() selected_language = self.kwargs.get("selected_language",self.request.user.profile.language) return qs.filter(language = selected_language) This is my url in urls.py: path('<str:selected_language>/', views.SomeView.as_view(), name="list-lang-filter"), And this is my HTML-Code for the select where the user can pick the language: <div x-show="dropdownOpen" class="w-full absolute rounded border border-forblueshadow bg-white z-20 font-light text-brightblue pt-1"> {% for language in languages %} <a href="{% url 'list-lang-filter' current_organization.pk language.code %}" class="language_filter_dropdown rounded-t py-2 px-4 block whitespace-no-wrap"> {{ language.name }} </a> {% endfor %} </div> When choosing an option in the filter-menu, i get redirected to a url with the right language code in it, but it just shows a 404. The weird thing is i did the exact same thing on another resource and it worked just fine. Does anybody have an idea? -
Imports using SlugRelated Feilds are Not working
I am Trying To Json Parse the objects passed through the slugrelated Feilds in django serializer class ImportFinanceSaleSerializerField(serializers.JSONField): def to_representation(self, obj): user_serializer = ImportFinanceSaleSerializer(obj, many=False, ) return user_serializer.data class ImportFinanceSaleSerializer(serializers.ModelSerializer): interestpercentage = serializers.SlugRelatedField( required=False, allow_null = True, slug_field="code", queryset=PercentageInterest.objects.filter(status=1,)) guarantor = serializers.SlugRelatedField( required=False, allow_null = True, slug_field='code', queryset=Person.objects.filter(status=1,)) emi_date = serializers.IntegerField(required=False, min_value=1, max_value=30) Error:- It input is taken as PCI00002 <class 'str'> -
Display ckeditor in django without form.py
I am trying to build an application in which I want to add a rich text editor. I have added CKEditor and it is working fine on the admin panel. I want to know if there is any way to display the editor without form.py, just to save data from simple post requests. this is how it is looking but it should be the rich text editor. is there any alternative way except forms.py for adding that editor? Thank You in advance :) models.py from django.db import models from ckeditor.fields import RichTextField # Create your models here. class Profile(models.Model): name = models.CharField(max_length=255) email = models.EmailField(max_length=255) previous_work = RichTextField(max_length=2000) skills = RichTextField(max_length=2000) html <form class="container"> {% csrf_token %} {{ form.media }} <div class="mb-3"> <label class="form-label">Name</label> <input type="text" class="form-control" name="name" id="name"> </div> <div class="mb-3"> <label class="form-label">Email</label> <input type="email" class="form-control" name="email" id="email"> </div> <div class="mb-3"> <label class="form-label">Previous Work</label> <!-- <input type="number" class="form-control" name="summary" id="summary"> --> <textarea name="Previous_work" class="form-control" id="Previous_work" cols="30" rows="10"></textarea> </div> <div class="mb-3"> <label class="form-label">Skills</label> <!-- <input type="number" class="form-control" name="summary" id="summary"> --> <textarea name="skills" class="form-control" id="skills" cols="30" rows="10"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> -
How to use IntegerRange as part of unique constraint in a Django 2.2 model
I understand that Django 2.2 is outdated. I am in the midst of migrating. Having said, that I still need to temporarily add new constraints to prevent invalid data for time being. from django.contrib.postgres.fields.ranges import IntegerRangeField class ProjectStructureWbsIslandGap(): series = models.ForeignKey(ProjectStructureFasSeries, on_delete=models.CASCADE) is_island = models.BooleanField(default=True) # island or gap level_3_range = models.IntegerRangeField(default=(1, 9999)) # 1-9999 line_number_range = models.IntegerRangeField(default=(1, 9999)) # 1-9999 class Meta: constraints = [ models.UniqueConstraint( fields?? conditions?? ), ] so what i want is these two constraint, whenever create new or update existing ProjectStructureWbsIslandGap record, within the same parent series and of the same is_island value, no two records can have overlap in terms of the IntegerRangeField level_3_range. whenever create new or update existing ProjectStructureWbsIslandGap record, within the same parent series and of the same is_island value, no two records can have overlap in terms of the IntegerRangeField line_number_range. so under the unique constraint, how should i fill in fields, and conditions? -
Django - CSS File Not Loading In Production server (Debug: False)
Use : nginx,gunicorn,linode for server Debug=False When I keep debug=False in production the css file don't get loaded.I have also build 404.html page.Suppose some one visit mydomain.com/abcd then he/she will get the 404 page which I have designed.Its good.The issue is css file not loaded. Debug True When I keep debug=True in the production the css file get loaded.Everything goes right.But when someone visited the mydomain.com/abcd then he/she will get the django defaualt error page.If I keep debug=True in the production everything goes right but I have heard that keeping debug=True in production is not recommended and may cause the security issues in the sites Currently what I have in my settings.py and nginx cofig are : settings.py : DEBUG =True ALLOWED_HOSTS = ['ip','mydomain.com','www.mydomain.com'] Nginx config file : server { server_name mydomain.com www.mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location projectdir/static/ { autoindex on ; root /home/user/projectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } Please help me to solve the issue,since I am struggling from past 1 week. Currently the site is live and css is loaded by keeping debug=True.But I don't want to have any security issue later. -
gunicorn processes wont shut down
I am trying to kill my gunicorn processes on my server. When I run kill {id} they seem to shut down for maybe 1sec and then they start back up. $ ps ax | grep gunicorn 42898 ? S 0:00 /usr/bin/python3 /usr/bin/gunicorn cms_project.wsgi -b 0.0.0.0:8000 -w 1 --timeout 90 42924 ? S 0:00 /usr/bin/python3 /usr/bin/gunicorn cms_project.wsgi -b 0.0.0.0:8000 -w 1 --timeout 90 then I run pkill -f gunicorn the processes go away for maybe 1second and then start back up on session id's 43170 ? S 0:00 /usr/bin/python3 /usr/bin/gunicorn cms_project.wsgi -b 0.0.0.0:8000 -w 1 --timeout 90 43171 ? S 0:00 /usr/bin/python3 /usr/bin/gunicorn cms_project.wsgi -b 0.0.0.0:8000 -w 1 --timeout 90 I have also tried killing them individually using the kill process -
Django StreamingHttpResponse returns only a single yield result from generator to stream
I am trying to stream several large json files to the front end at a time (I need to stream all of them one by one, and can't split it into several requests): def stream_response_generator(response): yield json.dumps({ 'searchedVariants': response['searchedVariants']}) yield json.dumps({ 'genesById': response['genesById']}) yield json.dumps({ 'locusListsByGuid': response['locusListsByGuid']}) yield json.dumps({ 'genesQcData': response['genesQcData']}) @login_required(login_url=API_LOGIN_REQUIRED_URL) @csrf_exempt @log_request(name='query_variants_handler') def query_variants_handler(request, search_hash): ... return StreamingHttpResponse(stream_response_generator(response), content_type='application/octet-stream') Only the very first searchedVariants response is streaming to the front end but other 3 are omitted. I verified it printing out the response on the frontend: fetch(url, { method: 'POST', credentials: 'include', body: JSON.stringify(search), signal: signal, }).then((response) => { const reader = response.body.getReader() let decoder = new TextDecoder('utf8'); let read reader.read().then(read = (result) => { if (result.done) return let chunk = decoder.decode(result.value); console.log(chunk) reader.read().then(read) }) }) In some tutorials, e.g. https://andrewbrookins.com/django/how-does-djangos-streaminghttpresponse-work-exactly/ Its written that we should pass a function generator instead of calling a function like I do, however, when I do that: def stream_response_generator(response): def generator(): yield json.dumps({ 'searchedVariants': response['searchedVariants']}) yield json.dumps({ 'genesById': response['genesById']}) yield json.dumps({ 'locusListsByGuid': response['locusListsByGuid']}) yield json.dumps({ 'genesQcData': response['genesQcData']}) return generator @login_required(login_url=API_LOGIN_REQUIRED_URL) @csrf_exempt @log_request(name='query_variants_handler') def query_variants_handler(request, search_hash): ... return StreamingHttpResponse(stream_response_generator(response), content_type='application/octet-stream') I am getting an error: 2022-10-21 03:34:28,165 ERROR: Traceback (most recent call last): … -
HTTP Error 500.0 - Internal Server Error (Django-Pyodbc,Oracle Database,IIS+FastCGI)
I can python manage.py runserver local but when I run by IIS some of my page can accessible except the page that use data from oracle and pyodbc. All 32bit except IIS. -
Django exhaust all object with specific status before returning other status with pagination
I basically have a todo list that may or may not go up to a thousand and the requirement is to show all "unchecked/uncomplete" before showing those that are completed, that looks easy but the problem is that it is paginated and or on an unlimited scrolling UI. I have this piece of code which works fine for basic usage but is not working for the requirement since it orders it all the time. models.mytodo.objects.order_by("-status") -
When create django table dynamically, how can I set Meta class?
I have a Django abstract model class and want to create it dynamically with meta class. class AccountTransaction(models.Model): class Meta: abstract = True account_num = models.ForeignKey('Account', on_delete=models.CASCADE) tran_amt = models.PositiveBigIntegerField() tran_type = models.CharField() tran_detail = models.CharField() tran_time = models.DateTimeField(auto_now_add=True) for i in range(10): model_name = f'account_transaction_{i:02}' globals()[model_name] = type(model_name, (AccountTransaction, ), {'__module__': AccountTransaction.__module__}) I could create 10 tables with this code when execute makemigrations and migrate Is it possible to set different metaclasses for each tables? For example, account_transaction_01 class Meta: db_table: "table1" account_transaction_02 class Meta: db_table: "table2" -
Django, Is there a way to access additional custom fields to the default user model in the serializer?
I am trying to send current user information through an API endpoint. I am using the Django default user model, and adding additional fields through inline. (Please refer to the code below) I am wondering if there is a way that I can access the newly added fields in the User serializer? I tried a lot of ways to include the newly added data but all failed. (for example, I am trying to pass gender_identity to my serializer so that my frontend could access the information) Here is my serializer.py: from django.contrib.auth.models import User from accounts.models import Account class UserSerializer(serializers.ModelSerializer): # author = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field='username') class Meta: # gender_identity = User.objects.get(username = 'bucky').account.gender_identity model = User fields = ['username', 'email','first_name','last_name'] read_only_fields = ['username', 'email','first_name','last_name'] depth = 3 Here is my Views.py: from rest_framework import viewsets # from .serializers import UserSerializer from .serializers import UserSerializer from django.contrib.auth.models import User from rest_framework.generics import (ListAPIView, ListCreateAPIView, DestroyAPIView, UpdateAPIView) class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_object(self): # print(self.request.user.account.gender_identity) print(type(self.request.user)) return self.request.user def list(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) My models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Account(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) user = … -
Why does Bootstrap cards have cards all shifted to the left?
I am creating a page in which news articles get fetched using Python, and then formatted into cards. I have used pagination to have 12 cards per page, but for some reason, all my cards and pagination bar are shifted to the left, and everything is off-centered. I would like to have them centered and all have the same width and height. How would I do this? {% if not posts %} <p>No articles were found.</p> {% else %} <div class="card-columns"> <!--class="row" style="display: flex; flex-wrap: wrap; gap: 8px; max-width: 916px; width: calc(100% - 20px);"--> {% for result in posts %} <div class="card"> <!--style="height: 260px; width: 300px; border-radius: 10px;"--> <img class="card-img-top img-fluid" src="{{ result.img }}" alt="Article image cap"> <div class="card-body"> <a href="https://{{ result.link }}" target="_blank"><h5 class="card-title">{{ result.title }}</h5></a> <p class="card-text">{{ result.desc }}</p> </div> </div> {% endfor %} </div> {% endif %} {% if posts.has_other_pages %} <ul class="pagination justify-content-center"> {% if posts.has_previous %} <li class="page-item"> <a class="page-link" href="?page= {{ posts.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#!" tabindex="-1" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} {% for num in posts.paginator.page_range %} {% … -
copyleaks sent pdfReport to endpoint as binary on request.body, not as file
I have django view that gets request and I try to send pdf result of copyleak scan. I get file as request.body and request.FILES is empty. I have checked copyleaks docs to see if I could pass extra argument as we should pass enctype="multipart/form-data" in django form to get files in request.FILES, but I did not see anything related. I can read request body and write it to file, no problem here, but would be great if I directly get pdf file in request FILES. myobj = json.dumps( { "pdfReport": { "verb": "POST", "endpoint": "https://aa67-212-47-137-71.in.ngrok.io/en/tool/copyleaks/download/", }, "completionWebhook": "https://aa67-212-47-137-71.in.ngrok.io/en/tool/copyleaks/complete/", "maxRetries": 3, } ) response = requests.post( "https://api.copyleaks.com/v3/downloads/file4/export/export16", headers=headers, data=myobj, ) I tried to change Content-Type manually and got error django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None Bad request (Unable to parse request body): /en/tool/copyleaks/download/ -
how to check isSubsest in django orm
I'm using django rest framework. and from these models, I want to get a possible cooking queryset using ingredients in fridge. I want to get cookings that all ingredients in fridge. How can I filter? please help.. class Ingredient(models.Model): name = models.CharField() class Cooking(models.Model): name = models.CharField() class Fridge(models.Model): ingredient = models.ForeignKey(Ingredient) class CookingIngredient(models.Model): cooking = models.ForeignKey(Cooking) ingredient = models.ForeignKey(Ingredient) -
How to manually audit log in django-auditlog
How do you manually audit log in django-auditlog? There is no example in the documentation and there is still very limited sources about this. Should the model be registered? What i am really trying to achieve is to manually log data so that i can add additional data like remarks. But i am having problems in using the LogEntry.objects.log_create(). Thanks in advance. -
Passing Two Parameters Through URL in Django
I'm having difficulty passing parameters to a URL in Django. I am attempting to pass two parameters from calander.html -> succ.html. The URL looks like this: Click for Image of URL In that image I want to pass 11:00am as the Start Time and 12:00pm as the end Time. My urls.py file contains: path('calender', views.calender, name='calender'), .... .... path('succ', views.succ, name='succ'), My views.py file contatins: def calender(request): return render(request, 'calender.html') def succ(request): return render(request, 'succ.html') I attempted to add parameters to the views.py file and then add a new path in urls.py after watching several videos and I was never able to find a solution since I am passing two parameters (StartTime and EndTime). -
how to set a default value for a field model to another model field
here are models.py file class album(TimeStampedModel): #album_artist = models.ForeignKey(artist, on_delete=models.CASCADE) album_name = models.CharField(max_length=100, default="New Album") #released_at = models.DateTimeField(blank=False, null=False) #price = models.DecimalField( # max_digits=6, decimal_places=2, blank=False, null=False) #is_approved = models.BooleanField( # default=False, blank=False) #def __str__(self): # return self.album_name class song(models.Model): name = models.CharField(max_length=100,blank=True,null=False) album = models.ForeignKey(album, on_delete=models.CASCADE,default=None) # image = models.ImageField(upload_to='images/', blank = False) # thumb = ProcessedImageField(upload_to = 'thumbs/', format='JPEG') # audio = models.FileField( # upload_to='audios/', validators=[FileExtensionValidator(['mp3', 'wav'])]) # def __str__(self): # return self.name I want to make the default value of the song name equal to the album name which i choose by the album Foreignkey. (in the admin panel page) any help ? -
url is showing in page not found error in django?
I created an endpoint and registered it in urls.py. When I try to hit the endpoint I get a 404 error but on the 404 page the url is shown as one of the patterns django tried to match. Stumped. api.py class UpdateLast(viewsets.GenericViewSet, UpdateModelMixin): def get(self): return XYZModel.objects.all() def partial_update(self, request, *args, **kwargs): if request.user.is_superuser: with transaction.atomic(): for key, value in request.data: if key == 'tic': XYZModel.objects.filter(ticker=request.data['tic']).filter(trail=True).update( last_high=Case( When( LessThan(F('last_high'), request.data['high']), then=Value(request.data['high'])), default=F('last_high') ) ) urls.py (this is inside the app) router = routers.DefaultRouter() router.register('api/dsetting', DViewSet, 'dsetting') router.register('api/update-last-high', UpdateLast, 'update-last-high') urls.py (main) urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_app.urls')), When I hit the end-point api/update-last-high I get a 404 page. On that page the exact end-point is shown as a pattern that django tried to match. ^api/update-last-high/(?P[^/.]+)/$ [name='update-last-high-detail'] ^api/update-last-high/(?P[^/.]+).(?P[a-z0-9]+)/?$ [name='update-last-high-detail'] -
Java input ending in a Django regex pattern gets NoReverseMatch error [duplicate]
I just got this NoReverseMatch error: 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)\\Z']. That "\\Z" on the end is NOT part of my code. I plugged it into regex101 with my string and got no match. Then I took the "\\Z" off the end and instantly my string matched. According to regex101, "\\Z" is an escaped literal forward slash and a literal capital Z. These characters are nowhere in my code. They're not in views, urls, get_absolute_url, or the template. Googling for 'django url slug regular expression pattern "\\Z"' got nothing helpful. All I did for this in my url pattern was "<slug:slug>", so I assume Django actually wrote the pattern? But I've never seen this on Django patterns before, either. How do I get rid of this and keep it from making my regex not match? Thanks. -
Django Shell Command Does Not Execute For Loop
I have a Django project going on, containing some functions and creating/updating a database. From time to time, I need to update the staticfiles in the project therefore I created a .py file in the same folder as the project named updatefiles.py I am running the script as python manage.py shell <updatefiles.py. Inside this file there is a for loop but for some reason it does not execute the for loop. I have tried even with a simple for loop such as below but it doesn't execute that one as well. Anyone has any ideas? fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) The output is: (InteractiveConsole) >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> ... ... ... ... ... ... ... ... ... ... ... now exiting InteractiveConsole... Anyone has any ideas? -
How can I implement authentication in Django
I am new to Django. I am going to build simple register and login fullstack application by using React and Django. My problem is when I received register request with form data. Is it ok to create custom table for users? I am going to create another table related to user table. So in that case, there must be id in the users. That's why I am going to create custom table. Please help me it is good practice. -
Django job board, upload form data to database if payment is successful using stripe?
I am creating a django jobboard, where you can fill details(title, description, company logo etc). When submit, check for payment competition(stripe) , if successful, upload the job data to database and redirect to this newly created job data. My question is how to check for payment completion and how to pass form data(image, title, description etc) to database only if payment is complete. How to handle if payment is successful but data failed to upload (for example validation of image extension). Any open source project of django jobbord with payment system(stripe checkout or stripe payment intent method). Thanks. -
How can I calculate discount fields from another table's fielsd
I have a model like this: class InvoiceItem(models.Model): book = models.ForeignKey(Book, on_delete=models.PROTECT) invoice = models.ForeignKey(Invoice, on_delete=models.PROTECT, related_name='items') title = models.CharField(max_length=100, null=True, blank=True) price = models.IntegerField(null=True, blank=True) discount = models.IntegerField(blank=True, default=0) totalprice = models.IntegerField(null=True, blank=True) count = models.IntegerField(null=True, blank=True) and I want to calculate discount from book's discount table How can I do it? should I calculate it in models? -
'QuerySet' object has no attribute 'defer_streamfields' when accessing root in Wagtail page
I just encountered the problem: 'QuerySet' object has no attribute 'defer_streamfields' when trying to access the Wagtail page in Wagtail admin. image for wagtail page failure Accessing a single page (eg. page/527) is working fine. Some people suggested that the problem can be caused by content type mix up in the database, but I haven't done any database dump before. Can someone offer me some advice on this issue? Thanks! stack trace: File "C:\Users\env\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\env\lib\site-packages\django\template\defaulttags.py", line 311, in render if match: File "C:\Users\env\lib\site-packages\django\core\paginator.py", line 177, in __len__ return len(self.object_list) File "C:\Users\env\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "C:\Users\env\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\env\lib\site-packages\wagtail\query.py", line 528, in __iter__ pages = pages.defer_streamfields() AttributeError: 'QuerySet' object has no attribute 'defer_streamfields' I am using Django==3.2, wagtail==4.0.1. The problem occured after upgrading wagtail from 2.6.2 to 4.0.1 -
Python django, trying to make a sidebar, but it doesnt appear/show
so as the title says I'm trying to learn Django and create a sidebar, but it just doesn't appear. This is my home.html {% extends 'main.html' %} {% block content %} <style> .home-container{ display: grid; grid-template-columns: 1fr 3fr; } </style> <div class="home_container"> <div> <h3>Browse Topics</h3> <hr> </div> <div> <a href="{% url 'create-room' %}">Create Room</a> <div> {% for room in rooms %} <div> <a href="{% url 'update-room' room.id %}">Edit</a> <a href="{% url 'delete-room' room.id%}">Delete</a> <span>@{{room.host.username}}</span> <h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} </div> </div> </div> {% endblock content %} This is my main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Site</title> </head> <body> {% include 'navbar.html' %} {% block content %} {% endblock %} </body> </html> The problem I am having is with the style part it seems correct and is supposed to make a sidebar with the Browse Topics. This is probably a very dumb question, but I've been struggling for hours and reached a point where I had to make an account to find a solution. Any help would be greatly appreciated.