Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nginx is returning 403 status code for non existing django static file path instead of 404
For Public Directories like /static/ and /media/ in django, if we hit non-existing path it return 403 Status instead of 404. How to get 404 for invalid static or media file paths ? E.g https://example.com/static or https://example.com/media It does return 404 if we hit it like https://example.com/static/some_random_words But i want it should return 404 for below path too https://example.com/static -
How to add allow response header to all django views?
How can I add the allow header that specifies the allowed HTTP methods to the response headers of all Django views? -
How to Secure Django Media Files in Production
In my localhost server, I was able to restrict users from accessing pdf media files which they are not supposed to access given that they are not the uploader of the file or the admin of the system. The problem is that when I tried to deploy my application, the restriction on my media files no longer works. This is my urls.py urlpatterns = [ path('media/pdf/<str:path>', views.pdf, name='pdf'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) And my MEDIA_URL and MEDIA_ROOT in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Also my debug is still set to TRUE in deployment, could this also be the problem? -
can Django listen to html events like javascript?
I have a html page with a datalist like this <input list="areas" placeholder="type option here"> <datalist id="areas"> <option>TV</option> <option>LAPTOP</option> <option>PHONE</option> </datalist> My objective is to create another list of selectable options using the information the user selected on this one, for example, if he chooses TV I'd like to either a) send a request to django and get the JsonResponse and render the next datalist using that Json. b) send a request to django and get the JsonResponse and make it return another page just like the previous but with the next data I learned that when Django renders and HTML page, I can send a context python Dict, so html has access to those variables. However, I am struggling to make the HTML call Django view functions and either render their result on the same page or open a new page with those results. I heard that HTML has some events that can be "listened" (don't know how that works) and the listener can make things happen, Javascript seems to be built exactly for this purpose since so many intuitive funtions like (onclick("makeSomething") / onchange("makeSomething")/ onhover("makeSomething")) Can I do something like this using only Django and HTML ? -
Show secondary foreign key values in the inline django admin
models.py class FarmerAdvisory(BaseModel): id = models.AutoField(db_column='id', primary_key=True) title = models.CharField(db_column='title', max_length=200, null=True, blank=True) description = models.CharField(db_column='description', max_length=750, null=True, blank=True) farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE, null=True, db_column='farmer_id') class Meta: verbose_name = 'Farmer Advisory' verbose_name_plural = 'Farmer Advisories' managed = True db_table = 'farmer_advisory' class ReplyFarmerAdvisory(BaseModel): reply = models.CharField(db_column='reply', max_length=750, null=True, blank=True) label = models.CharField(db_column='label', max_length=100, null=True, blank=True) farmer_advisory_id = models.ForeignKey(FarmerAdvisory, on_delete=models.CASCADE, db_column='farmer_advisory_id') objects = models.Manager() class Meta: verbose_name = 'Reply Farmer Advisory' verbose_name_plural = 'Reply Farmer Advisories' managed = True db_table = 'reply_farmer_advisory' class AdvisoryMedia(models.Model): id = models.AutoField(db_column='id', primary_key=True) farmer_advisory_id = models.ForeignKey(FarmerAdvisory, on_delete=models.CASCADE, db_column='farmer_advisory_id', null=True, blank=True) reply_farmer_advisory_id = models.ForeignKey(ReplyFarmerAdvisory, on_delete=models.CASCADE, db_column='reply_farmer_advisory_id', null=True, blank=True) farmer_media_file = models.CharField(db_column='farmer_media_file', max_length=50, null=True, blank=True) is_active = models.BooleanField(db_column='is_active', null=False, default=True) reply_media_file = models.FileField(upload_to=content_file_name, null=True, blank=True, db_column='reply_media_file') class Meta: verbose_name = 'Advisory Media' verbose_name_plural = 'Advisories Media' managed = True db_table = 'advisory_media' admin.py class AdvisoryMediaInline(NestedStackedInline): model = AdvisoryMedia extra = 0 class ReplyFarmerAdvisoryInline(NestedStackedInline): model = ReplyFarmerAdvisory extra = 1 inlines = [AdvisoryMediaInline] class FarmerAdvisoryAdmin(NestedModelAdmin): inlines = [ReplyFarmerAdvisoryInline] I want to show the fields with respect to the farmer advisory. But when i am adding fk_name = 'farmer_advisory_id' inside AdvisoryMediaInline, i am getting error stating ValueError: fk_name 'farmer_advisory_id' is not a ForeignKey to 'farmer.ReplyFarmerAdvisory'. But i want to show … -
Django throws AttributeError: 'str' object has no attribute '_meta' when trying to migrate
I'm working on a small project on my own, and I have some problems with the migrations. I managed to migrate everything well so far, but I removed a field from my models.py and now there are problems somehow. I had a field called tags that was referencing to a model from taggit, but I decided to remove this field and do it on my own, so the field tags still exists but its not referencing to the tagablemanager of taggit anymore, but on my own tag model now Nevermind everytime I excecute python manage.py migrate to make the database, this error is thrown: Applying inventory_app.0014_item_tags...Traceback (most recent call last): File "/Users/ilianhaesler/Documents/Work/inventory/inventory/manage.py", line 22, in <module> main() File "/Users/ilianhaesler/Documents/Work/inventory/inventory/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/ilianhaesler/Documents/Work/inventory/inventory-env/lib/python3.10/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) … -
Union of non-model serializers in Django Rest Framework
Through serializers, I'm trying to describe that a field could be serialized as one of N options (similar to typing.Union). The goal of this is to use DRF Spectacular to generate Union Types. For example: From the following serializers class SerializerA(serializers.BaseSerializer): a_field = serializers.CharField() class SerializerB(serializers.BaseSerializer): b_field = serializers.CharField() I want to describe: class CombinedSerializer(serializers.BaseSerializer): combined_field = <either_serializerA_or_serializerB> Which, through DRF spectacular, I would be able to generate into export interface SerializerA = { a_field: string; } export interface SerializerB = { b_field: string; } export interface CombinedSerializer = { combined_field: SerializerA | SerializerB } I've looked into https://github.com/denisorehovsky/django-rest-polymorphic but that seems to support model serializers. https://github.com/tfranzel/drf-spectacular/issues/382 also doesn't seem to support this use case - any suggestions? -
Submit button is not working in html using django
HTML FILE in html page action is not added i wanted to know how i can submit the form without adding action attribute?? -
How to share memory using gunicorn+uvicorn workers or Daphne+supervisor
I have a Django web application that uses Daphne web server. I have a problem when running multiple instances of app using supervisor (that corresponds to running app with multiple uvicorn workers using gunicorn). I tried to solve it by sharing memory using Redis DB to save user instances so that every worker can access logged in users but then I came across the problem. There is threading inside of User class and I can't pickle _thread.lock object so I can't use Redis. If I separate threading from my User class, I don't profit from it at all because then worker has to do same job again, that is, make a thread, when I send request. Is there a workaround to this problem? I.e. using internal shared memory or something like that? -
Validating several objects at once, before saving
Is it possible to sum values in fields of several objects? class MyModel(model.Models): name = models.Charfield() amount = models.IntegerField() Model Object 1 Object 2 Object 3 Object 4 Object 5 Here i want the sum of "amount" in all the objects to use in my validation. If the total "amount" is correct, i want to save all objects. How do i do this? -
Persian URL in Cpanel Django
I have the url http://127.0.0.1:8000/shop/جکوزی-آپارتمانی/p/وان-جکوزی-مدل-L188/ in my development project and it's is working fine till i upload it to cpanel which returns Page not found (404) here is my urls.py: from django.urls import path , re_path from . import views as v urlpatterns = [ path('', v.index.as_view(), name="ShopView"), path('seach/' , v.SearchResultsView.as_view() , name="search_results"), re_path(r'c/(?P<categoriese>[-\w]+)/' , v.categoryView , name="ProShopView2"), re_path(r'(?P<namecate>[-\w]+)/p/(?P<namepro>[-\w]+)/', v.ProductDetailsView , name="productview"), path('products/<str:proname>/comment/' , v.commentView , name="commentviewshop"), ] first re_path is for category which the url is http://127.0.0.1:8000/shop/c/جکوزی-آپارتمانی/ second re_path is for category and product http://127.0.0.1:8000/shop/جکوزی-آپارتمانی/p/وان-جکوزی-مدل-L188/ here is my category model: class categories(models.Model): name = models.CharField(max_length=50, null=True,blank=True,unique=True) url_name = models.SlugField(unique=True , null=True , blank=True,allow_unicode=True) image = ResizedImageField(size=[1920,1920], crop=['top', 'left','bottom', 'right'],upload_to = upload_image_path , null=True , blank=True) def __str__(self): return self.name **here is my productmodel: ** *deleted some of the unnecessary fields. class productmodel(models.Model): Seller = models.ForeignKey(User , on_delete=models.CASCADE , null=True , blank=True) category = models.ForeignKey(categories ,blank=True, null=True, on_delete=models.CASCADE , related_name="categories_main") ProductName = models.CharField(max_length=60) slug = models.SlugField(unique=True , null=True , blank=True,allow_unicode=True) ProductBody = models.TextField(max_length=800) image = ResizedImageField(size=[1920,1920], crop=['top', 'left','bottom', 'right'],upload_to = upload_image_path , null=True , blank=True) def __str__(self): # return f'ProuctName:{self.ProductName} ProductAuthor:{self.author} ProductId:{self.id}' return self.ProductName def getsnippet(self): return self.ProductBody[0:30] **here is my category views: ** def categoryView(req , categoriese): if categories.objects.filter(url_name … -
Recursive "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext" development server log
I am working on a Django project and I implemented custom login and logout views for authentication. I am getting these weird development server logs below immediately after I open my site at 127.0.0.1:8000. [04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/favicon.ico HTTP/1.1" 302 0 [04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/login/%252525252525253Fnext%252525252525253D/favicon.ico HTTP/1.1" 302 0 [04/Jan/2023 11:36:30] "GET /login/?next=/login/%3Fnext%3D/login/%253Fnext%253D/login/%25253Fnext%25253D/login/%2525253Fnext%2525253D/login/%252525253Fnext%252525253D/login/%25252525253Fnext%25252525253D/login/%2525252525253Fnext%2525252525253D/login/%252525252525253Fnext%252525252525253D/login/%25252525252525253Fnext%25252525252525253D/favicon.ico HTTP/1.1" 302 0 Here are my two relevant url.py files from django.urls import path from .views import login_view, register_user, verify_user, verify_number from django.contrib.auth.views import LogoutView urlpatterns = [ path('accounts/login/', login_view, name="login"), path('accounts/<str:phone_number>/verify/', verify_user, name="verify_login"), path("accounts/logout/", LogoutView.as_view(), name="logout"), path('accounts/register/', register_user, name="register"), path('accounts/<str:phone_number>/verify/', verify_number, name="verify_user"), ] from django.urls import path, re_path from django.conf import settings from django.conf.urls.static import static from apps.home import views from apps.authentication import views as auth_views app_name = 'home' urlpatterns = [ # Main Application URLS path('', views.home, name='home'), ... ... ... ] I am thing setting in my settings.py ... LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'home:index' LOGOUT_REDIRECT_URL = 'home:home' ... And finally, this is my home function (snippet of my views.py) ... def home(request): context = {} return render(request, "home.html", context) ... I have tried removing the LOGIN_URL setting but not luck. I am only getting these weird logs on my home page at 127.0.0.1:8001 Anyone … -
Django doesn't save ManyToManyField field. Why?
I have been searching for the answer everywhere but haven't managed to find it. Django doesn't save a ManyToManyField (Categories). Please let me know why if you know. So, it saves everything except the Category - ManyToManyField. Everything other works well. There is no any errors. Here is the code: Views.py: def adminpanel(request): categories = Category.objects.all() if request.method == "POST": if 'apost' in request.POST: form = PostForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.save() form.save_m2m() images = request.FILES.getlist('image') for image in images: picture = Image.objects.create( name = instance.name, post = instance, image = image, ) return render(request,'adminpanel.html',{'categories':categories}) Adminpanel.html: <form method = "POST" action = "{% url 'adminpanel' %}" enctype = "multipart/form-data"> {% csrf_token %} <label>Name:</label> <input id = "post_name" type = "text" class = "admin-field" placeholder = "Name" name = "name"><br><br> <label>Category:</label> {% for category in categories %} <input type="checkbox" id="{{category.name}}" name="{{category.name}}" value="{{category.id}}"> <label for="{{category.name}}">{{category.name}}</label><br> {% endfor %} <br><br> <label>Thumbnail:</label> <input id = "post_thumbnail" type = "file" id = "file" name = "thumbnail" accept = "image/png, image/jpeg"><br><br> <label>Images:</label> <input id = "post_images" type="file" name="image" accept = "image/png, image/jpeg" multiple><br><br> <label>Slug:</label> <input id = "post_slug" type = "text" class = "admin-field" placeholder = "Slug" name = "slug"><br><br> <label>Body:</label> <input id = … -
Django Rest Framework - What to return from a custom filter function for Django Rest Multiple Models
I am using the module DjangoRestMultipleModels so I can post multiple models on a page. I need to filter the objects by the user that created them but I need help as I'm struggling to figure this out. The URL contains the user's id path("posts/user/<int:user>/posts/", UserPostsList.as_view(), name="users posts"), This is the view to show the objects: def get_user(queryset, request, *args, **kwargs): id = kwargs['user'] return #Don't know what to return here class UserPostsList(ObjectMultipleModelAPIView): permission_classes = [IsAuthenticated] def get_querylist(self): querylist = [ {'queryset':Post.objects.all(), 'serializer_class': UserPostSerializer, 'filter_fn': get_user}, {'queryset':Question.objects.all(), 'serializer_class': QuestionSerializer, 'filter_fn': get_user}, ] return querylist I tried using def get_querylist(self): user = self.request.user querylist = [ {'queryset':Post.objects.all()filter(user=user), 'serializer_class': UserPostSerializer}, {'queryset':Question.objects.all(), 'serializer_class': QuestionSerializer, 'filter_fn': get_user}, ] return querylist but because I am logged in as two different users. Admin as 1 user and the front end sending the request as another user I get the wrong results. I must use the user id from the URL -
Django allauth facebook utf-8
I`m using django allauth for social login and i get this resulst in extra_data "first_name": "\u041a\u0438\u0440\u0438\u043b\u043b", "name": "\u041a\u0438\u0440\u0438\u043b\u043b \u0412\u0438\u043d\u044e\u043a\u043e\u0432", How can i get these field in normal view? -
I Need A Python Program To Find whether the photo was taken in front camera or back camera
I Have committed in a project . I'am Locked in a phase and i cant move further. i need a python program to find whether the photo is taken from front camera or back camera if so it should show the picture and say this photo is taken from front camera or back camera I Completed one phase of the program still need an exact program to find the image taken by specific camera -
How to pass pk in reverse() for generics.DestroyAPIView?
I'm writing test for my endpoint responsible for deleting objects. I'm struggling with passing proper pk of object. It is keeping me prompting with django.urls.exceptions.NoReverseMatch. My url: router = routers.DefaultRouter() router.register( prefix="questions-api/delete", viewset=views.QuestionDelete, basename="questions_delete" ) urlpatterns = router.urls The way I'm calling reverse: response = api_client.delete( reverse("questions_delete-list", kwargs={'pk':1}), ) Appreciate any hint :) -
the checking out doesnt work properly , the error is always != 0 but it cannot be so
the idea is that while checking out, if you dont fill in the info, you will get stuck there until you fill in all the info and then you can continue I suppose that the problem is that the error is constantly != 0. However, it cannot be. here is the code that I have problem with: var form = document.getElementById('form') form.addEventListener('submit', function(e) { e.preventDefault() }) document.getElementById('make-payment').addEventListener('click', function(e){ const form = document.getElementById('form') let error = formValidate(form); if (error != 0) { alert('smth typed in') }else { submitFormData() } }) function formValidate(form) { var error = 0; let formReq = document.querySelectorAll('._req'); for(let index = 0; index < formReq.length; index++) { const input = formReq[index] formRemoveError(input); if(input.classList.contains('_email')) { if(emailTest(input)){ formAddError(input); error++; } } else { if (input.value === '') { formAddError(input); error++; } } } } function formAddError(input) { input.parentElement.classList.add('_error') input.classList.add('_error'); } function formRemoveError(input) { input.parentElement.classList.remove('_error') input.classList.remove('_error'); } function emailTest(input) { return !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,8})+$/.test(input.value); } -
Django docker doesn't hot reload for the updates in some folders somehow
I run Django docker and hot reload works normally in most folders. But it doesn't work in some folders. Here are my basic folder structure. whaleserver (Django project) api (app) migrations ... v1 v2 .. Any change inside v1 triggers hotreload but v2 change doesn't somehow. Need help to diagnose this. I already researched but couldn't find proper solution for this. Much appreciated if anyone can give me helpful suggestion on it. Thanks in advance. -
Trim_whitespace=True is not working in Django Serializer
I am trying to trim whitespace from API input before writing to DB. I am using >>> class A(object): ... def __init__(self, name, email, phone_number): ... self.name = name ... self.email = email ... self.phone_number = phone_number ... >>> class ASerializer(serializers.Serializer): ... name = serializers.CharField(max_length = 200, trim_whitespace=True) ... email = serializers.EmailField() ... phone_number = serializers.RegexField("[0-9]{10}") >>> obj = Geeks("Aditi ", "abc@gmail.com", "1234567890 ") >>> serializer = ASerializer(obj) >>> serializer.data {'name': 'Aditi ', 'email': 'abc@gmail.com', 'phone_number': '1234567890 '} why is it not removing space in name? Any idea? -
Safely remove a field from django model
I removed some fields from my database lately and they are still in the older migration files of my project. I don't want to delete all the migration files, since they are in the git and it's not my project. But when I remove a field, the migration has problem because old migration files still have a "connection" to the deleted field. Is there a way to delete a field without deleting migration files and without having any problems? Thank you -
Django additional fields in TabularInline
I have such structure: #admin.py class OrderProductInline(admin.TabularInline): model = OrderProduct extra = 0 template = "admin/edit_inline/tabular_order.html" @admin.register(Order) class OrderAdmin(admin.ModelAdmin): ... inlines = [ OrderProductInline ] #models.py class OrderProduct(models.Model): ... order_id = models.ForeignKey(Order, on_delete=models.CASCADE, blank=False, null=False) to_product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=False, null=True, verbose_name=_('Product')) On the attached image I show some custom inputs (red rectangles) for each product item in inline form. This inputs depends on additional queryset based on Foreign Key, but I cant`t find the correct way how to display this fields there. -
How to remove 'dist' from path while subfolder import from component library using rollup?
I have created a component library and trying to consume the library in my other project using the github repo url. I am able to import the complete library right now. import {component} from 'library'. But when i am trying to import subfolders like this import {component} from 'library/component'. I am not able to do so for that I have to do like this import {component} from 'library/dist/component'. Expected : import {component} from 'library/component'. Current: import {component} from 'library/dist/component' How to achieve this ? -
Calendar in (form) html template like in Django admin panel
I thought it might be useful to someone. How to make a calendar widget like in the Django admin panel. INSTALLED_APPS = [ 'django.forms', ] header.html <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link rel="stylesheet" href="{% static 'css/widgets.css' %}"> <script type="text/javascript" src="/admin/jsi18n/"></script> footer.html <script src="{% static 'js/calendar.js' %}"></script> <script src="{% static 'js/DateTimeShortcuts.js' %}"></script> <script src="{% static "js/core.js" %}"></script> forms.html {{ form.date_production }} {% if form.date_production.errors %} {% for error in form.date_production.errors %} {{ error|escape }} {% endfor %} forms.py from score.models import Score from django import forms from django.contrib.admin.widgets import AdminDateWidget class CreateScoreForm(forms.ModelForm): date_production = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Production'}), required=False) date_shipping = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Shipping'}), required=False) date_payment = forms.DateField(widget=AdminDateWidget(attrs={'placeholder': 'Payment'}), required=False) class Meta: model = Score fields = ['date_production', 'date_shipping', 'date_payment',] models.py from django.db import models from django.urls import reverse_lazy class Score(models.Model): date_production = models.DateField(blank=True, null=True, verbose_name='Production') date_shipping = models.DateField(blank=True, null=True, verbose_name='Shipping') date_payment = models.DateField(blank=True, null=True, verbose_name='Payment') def get_absolute_url(self): return reverse_lazy('delete_score', kwargs={'pk': self.pk}) def __str__(self): return self.number class Meta: ordering = ['-date_creation'] -
How to consume url parameters in Django views
Getting an error always The current path, <code>api/det/1</code>, didn’t match any of these. My urls.py url(r'^api/det/<int:id>',views.DetailsAPI.as_view(),name='DetailsAPI') My views.py class DetailsAPI(APIView): def get(self,id): filter_list=Details.objects.all() #filter_list = Details.objects.get(id=id) envid = self.kwargs['id'] df = read_frame(filter_list) df_det = df.loc[df['Id'] == int(id)] df_final=df_det.to_json(orient='records') return HttpResponse(df_final, content_type = 'application/json') I'm sure there is some simple stuff that i'm missing and i can't get it to work with whatever syntax i try.. Any suggestions?