Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am geting internal server error in django rating
i an new in django i am trying to make star rating app by using django and javaScript but when i am clicking on star in console i am getting internal server error. actually I am also getting error message which i already have provided in javascript else condition. i have mainly problem in views.py because its not saving data in server. i also trying to add studentProfile model objects in view bu gating same error please help me? views.py def sendMessageView(request): object = sendMessage.objects.filter(score=0).order_by('?').first() return render(request, 'messages.html', {"object":object}) def rate_student(request): if request.method == 'POST': el_id = request.POST.get('el_id') val = request.POST.get('val') obj = sendMessage.objects.get(id=el_id) obj.score = val obj.save() return JsonResponse({'success': 'true', 'score': val}, safe=False) return JsonResponse({'success': 'false'}) models.py class studentProfile(models.Model): name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(unique=True) rollNumber = models.IntegerField(unique=True) class Meta: ordering = ('name',) verbose_name_plural = 'Student Profile' def __str__(self): return self.name class sendMessage(models.Model): name = models.ForeignKey(studentProfile, on_delete=models.CASCADE) message = models.TextField(null=True, blank=True) score = models.IntegerField(default=0, validators=[ MaxValueValidator(5), MinValueValidator(0), ] ) def __str__(self): return str(self.pk) message.html {% extends 'base.html' %} {% block content %} <h1>message and ratting page</h1> <div> <form class="rate-form" method='POST' action="" id="{{object}}"> {% csrf_token %} <button type="submit" class="fa fa-star my_btn" id="first"></button> <button type="submit" class="fa fa-star my_btn" id="second"></button> … -
Django Admin Login page got messed up. (After git pull maybe? I am not sure)
I am not sure when did this happen, I seldom check my admin page while coding. I have been messing around with github and git bash to be familiarized with things so that I can work with a team environment. Is this because someone messed with this page on another branch and pushed changes to master branch? Anyone knows how to fix this? -
Django No matching serviceworker detected
Thanks for your time. I've been trying to set a PWA on a django project of mine: I've set the pwa files through urls and TemplateViews, and seems to be working. i'm able to run the sw.js code. get the manifest.json on tab application(Chrome dev) but ain't understanding why keeps getting the same error: no matching service worker detected. you may need to reload the page or check that the scope of the service worker for the current page encloses the scope and start url from the manifest i know that are a thousand of questions about that, but none with django that i could find. manifest.json: { "short_name": "Mega", "name": "MegaMagazine", "icons": [ { "src": "/static/m1.png", "type": "image/png", "sizes": "144x144" } ], "start_url": "/", "background_color": "#3367D6", "display": "standalone", "scope": "/", "theme_color": "#3367D6" } sw.js console.log('ok') install_sw.html <!doctype html> <head> <link rel="manifest" href="{% url 'manifestjson' %}"> </head> <title>installing service worker</title> <script type='text/javascript'> if ('serviceWorker' in navigator) { navigator.serviceWorker.register("{% url 'sw.js' %}").then(function (registration) { console.log('Service worker registrado com sucesso:', registration); }).catch(function (error) { console.log('Falha ao Registrar o Service Worker:', error); }); } else { console.log('Service workers não suportado!'); } </script> Files: enter image description here urls.py: urlpatterns = [ path('admin/', admin.site.urls), … -
Form.errors not rendering in TemplateView
Upon submitting a form, the desired outcome is to display validation error messages in the template if the form is not valid. When it comes to what I'm actually getting, no error messages are showing up in the template at all even though the form does in fact catch the errors. I'm trying get the desired outcome using just TemplateView. class TestUserRegisterPage(TestCase): '''Verify that a message is flashed when attempting to create a new account with a username already taken.''' @classmethod def setUpTestData(cls): user = User.objects.create_user("Mock") cls.payload = { "username": "Mock", "password1": "secret", "password2": "secret" } def test_new_user_registeration_fail(self): response = self.client.post( reverse("users:register"), data=self.payload ) self.assertEqual(response.status_code, 200) print(response.content) self.assertTemplateUsed(response, "users/register.html") self.assertContains(response, "A user with that username already exists") AssertionError: False is not true : Couldn't find 'A user with that username already exists' in response -> form = self.get_context_data()['register_form'](payload) (Pdb) n > users\views.py(30)post() -> if form.is_valid(): (Pdb) form.errors {'username': ['A user with that username already exists.'], 'password2': ['This password is too short. It must contain at least 8 characters.', 'This password is too common.']} (Pdb) class UserRegisterPage(TemplateView): template_name = "users/register.html" def get_context_data(self): context = super().get_context_data() context['register_form'] = NewUserForm return context def get(self, request): context = self.get_context_data() context['register_form'] = context['register_form']() return self.render_to_response(context) … -
how to get nested objects in django
models.py class BuyNotes(models.Model): student = models.ForeignKey(to=Student, on_delete=models.SET_NULL, null=True) note = models.ForeignKey(to=Notes, on_delete=models.SET_NULL, null=True) buy_at = models.DateField(auto_now_add=True) amount = models.IntegerField(default=0, null=True) class Meta: unique_together = [['note', 'student']] views.py def allNotesStudent(request): user = User.objects.get(username=request.session['user']) student = Student.objects.get(user=user) buy_notes = BuyNotes.objects.filter(student=student).get(note) I know last line is wrong. how to get all objects of note that current login student bought -
'DatabaseOperations' object has no attribute 'geo_db_type'. When migrate
I am building a WebApp . AND I am stuck on an Error. What i am trying to do I am making a Location Based BlogApp and I am using PointField in models. The Problem 'DatabaseOperations' object has no attribute 'geo_db_type' This error is keep showing when i migrate. When i go into admin then this error is keep showing. settings.py This is the DataBase i am using. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '---------', 'HOST': 'localhost', 'PORT': '', } } What have i tried I also tried chaning 'django.db.backends.postgresql_psycopg2' to 'django.contrib.gis.db.backends.postgis'. BUT it is showing django.db.utils.OperationalError: could not open extension control file "C:/Files/PostgreSQL/13/share/extension/postgis.control": No such file or directory I also tried many answers but nothing worked for me. I have installed pip install psycopg2. -
Django Filtering Model from User Input on Query Result
I have a purchase form, where the user can lookup a customer by name in the database and have a result returned in an HTML table. The user than clicks on an element in the table to autocomplete (Javascript) immutable name fields in a form to reduce input errors. I want to also display any fraud related to the selected customer, which would come from filtering the fraud table which was loaded in the context variable ['fraud']. I want to filter this new HTML table based on the customer ID selected, which changes as the user clicks on elements in the table derived from the first query. I'm having trouble understanding how I can filter this new table, considering that the customer ID input comes from the client-side. I've thought about having a hidden div with an input field that takes the customerID and performs another query. The problem with that solution is that I lose the URL params of my first query every time the second query is performed. Is there any convention for how to properly set this up within Django? Thank you views.py @method_decorator(login_required, name='dispatch') class CustomerResultsView(ListView): model = CustomerName template_name = 'parent/child.html' context_object_name = 'filtered_customers' @method_decorator(login_required) … -
exclude many-to-many with specific value
I have a model: class Rent(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) bikes = models.ManyToManyField(Bike) when I create a new rent in the admin site, I would like to exclude the bikes that have the value of 1 for their status integer field from showing in the list to choose from. Is this possible? Thanks -
How to log messages from django websocket functions to a file?
I have an application that uses linux + ngnix + gunicorn + websockets + django. The app opens a websocket connection on a specific url with a specific configuration. However, if configuration changes, it does not connects and shows the error: WebSocket connection to 'wss://my.url/ws/tool/5283cb7b-215d' failed: Error during WebSocket handshake: Unexpected response code: 500 I am trying to log code to check what are the differences between the data sent from one to another so I can reproduce the working configuration. I already found some data and am sending same data (access_data, and so on), however I cannot see what data sockets are receiving. I tried to use django log, no success. asgi.log also doesn't shows the info too. My log calls are on consumers.py file under class ChatConsumer(AsyncWebsocketConsumer): class and functions (connect, disconnect and receive). I am trying to check which data are being received by these functions. Log files doesn't contains the messages from this functions, neither from the url that is connecting correctly to the websocket. When I access the url, I see it connects correctly but I don't see any messages in my logs. asgi.log also shows only WSCONNECTING and WSDISCONNEC messages. How to log messages … -
How to automatically generate a field based on the choice of a previous field
I have a model and some serializers in Django Rest Framework. I would like to have choices for the "service_interval" field and then based on what they choose it generates the date correctly in the database. How would I do this? Here's my code. class Snippet(VIPSnippet): title = models.CharField(max_length=100, blank=True, default='') service_interval_choices = [ (3, '3 Months'), (6 , '6 Months'), (9, '9 Months'), (12, '1 Year'), ] service_interval = models.IntegerField(choices=service_interval_choices) next_service = models.DateTimeField() Serializers class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') class Meta: model = Snippet fields = ['url', 'service_interval'] next_service = datetime.datetime.now() + datetime.timedelta(3*365/12) When I do it this way I get the following error NOT NULL constraint failed: snippets_snippet.next_service I plan to replace the '3' in datetime.timedelta(3*365/12) with service_interval or whatever variable I would need so that it generates the date however may months in the future as needed. -
View.py won't get ajax but I can update the database by passing JSON directly in the url, Django
I'm following this tutorial https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json I'm trying to update my database with the CreateCrudUser class, but when I click submit the data goes to the end of the url and it doesn't update the databse. If i add the word "create" in front of the JSON it puts in the url it will update the database. View.py class CrudView(ListView): model = models.CrudUser template_name = 'newsfeed/crud.html' context_object_name = 'users' class CreateCrudUser(View): def get(self, request): name1 = request.GET.get('name', None) address1 = request.GET.get('address', None) age1 = request.GET.get('age', None) obj = models.CrudUser.objects.create( name = name1, address = address1, age = age1 ) user = {'id':obj.id,'name':obj.name,'address':obj.address,'age':obj.age} data = { 'user': user } return JsonResponse(data) url.py from django.urls import path, include from social_method.apps.newsfeed import views app_name = "newsfeed" urlpatterns = [ #path('observation-feed/', views.ObservationFeed, name='observation-feed'), path('', views.ObservationFeed, name='observation-feed'), path('observation/<str:pk>/', views.ObservationThread, name='observation'), path('new-social-method/<str:pk>/', views.SocialMethod, name='new-social-method'), path('crud/', views.CrudView.as_view(), name='crud_ajax'), path('ajax/crud/create/', views.CreateCrudUser.as_view(), name='crud_ajax_create'), ] models.py class CrudUser(models.Model): name = models.CharField(max_length=30, blank=True) address = models.CharField(max_length=100, blank=True) age = models.IntegerField(blank=True, null=True) html <div class="container"> <h1>Django Ajax CRUD</h1> <h2>{% url "newsfeed:crud_ajax_create" %}</h2> <div class="row"> <div class="col-md-4 "> <h3>ADD USER</h3> <form id="addUser" action=""> <div class="form-group"> <input class="form-control" type="text" name="name" placeholder="Name" required> </div> <div class="form-group"> <input class="form-control" type="text" name="address" placeholder="Address" required> </div> <div class="form-group"> <input … -
Django Form: django-autocomplete-light is showing empty dropdown
I am building a web app in Django trying to use django-autocomplete-light(v.3.8.2) to create an auto-complete field. I have form that allows users to create a Trade record. I'm trying to add an auto-complete field for Trade.owned_game (a lookup field). I am just getting an empty dropdown field for the auto-complete field (screenshot attached at bottom of this post) Below is my code: models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Game(models.Model): name = models.TextField() # Unrestricted text platform = models.CharField(max_length=100) # character field created_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name # return game name when game.objects.all() is called class Trade(models.Model): name = models.TextField() # Unrestricted text created_date = models.DateTimeField(default=timezone.now) is_trade_proposed = models.BooleanField(default=False) user_who_posted = models.ForeignKey(User, on_delete=models.CASCADE) owned_game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='owned_game', db_column='owned_game') def __str__(self): return self.name # return game name when game.objects.all() is called urls.py: from django.urls import path from django.conf.urls import url from .views import ( PostListView, TradeListView, PostDetailView, TradeCreateView, GameAutoComplete, PostUpdateView, PostDeleteView, UserPostListView ) from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('post/new/', views.trade_new, name='trade-create'), url( r'^game-autocomplete/$', GameAutoComplete.as_view(), name='game-autocomplete') , ] views.py: from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, … -
django AuthenticationForm how to remove error messages
I created a custom error message for auth form, however, I'm not sure how to remove the error message from django AuthenticationForm? Any help is appreciated, thank you! form: class CustomAuthForm(AuthenticationForm): class Meta: model = UserCreationForm fields = ['username','password'] def __init__(self, *args, **kwargs): super(CustomAuthForm, self).__init__(*args, **kwargs) self.fields['username'].widget = forms.TextInput(attrs={ 'placeholder': 'email'}) self.fields['username'].label = False self.fields['password'].widget = forms.PasswordInput(attrs={ 'placeholder':'password'}) self.fields['password'].label = False -
DRF - render SerializerMethodField in serializers.Serializer
I have a little problem with getting value from SerializerMethodField when using serializers.Serializer views.py: class StaticDataView(generics.RetrieveAPIView): serializer_class = serializers.StaticDataSerializer def retrieve(self, request, *args, **kwargs): serializer = self.get_serializer() return Response(serializer.data) serializer.py class AnimatorStaticDataSerializer(serializers.Serializer): data = DataSerializer(data=Data.objects.all(), many=True) user = serializers.SerializerMethodField() def get_user(self, obj): return UserSerializer(self.context['request'].user).data When I call to my API view, at the response I get only data key, user isn't rendered. I found that could be because SerializerMethodField is read_only=True and for this reason get_initial() from rest_framework/serializers.py doesn't render it. But how can I write it differently when I need to pass context with the user as an instance to UserSerializer. DataSerializer is also using request from context. -
Django How can I solve NoReverseMatch error?
I'm making the website using Django. I have a problem for url. I tried to access the website, but an error occurred. Error is NoReverseMatch. Reverse for 'add' with no arguments not found. 1 pattern(s) tried: ['purchase/order/(?P<CAT_ID>[^/]+)/$'] How can I solve this problem? # urls.py {% for value in object_list %} <tr> <form action="{% url 'purchase_order:add' value.CAT_ID %}" method="get"> <td scope="row">{{ value.CAT_ID }}</td> <td scope="row">{{ value.INFOR }}</td> <td scope="row"> <input type="submit" value="CREATE" class="btn btn-outline-secondary btn-sm"> </td> </form> </tr> {% endfor %} # urls.py app_name = 'purchase_order' urlpatterns = [ # CREATE URL path('order/<str:CAT_ID>/', views.Order_add_View.as_view(), name='add'), ] # views.py class Order_add_View(LoginRequiredMixin, CreateView): model = Purchase_Request # template_name = 'purchase_order/add.html' fields = ['CAT_ID', INFOR] def get(self, request, *args, **kwargs): CAT_ID = self.kwargs['CAT_ID'] return render(request, 'purchase_order/add.html', {'CAT_ID':CAT_ID}) def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form) -
Dynamically end div class=row/start new div row HTML using mako template
I am trying to display a list of courses using a Mako for loop on my HTML page. Each course has it's own card, and I'm trying to end the row once there are three cards. I tried to use this loop % if (loop.index % 3): </div> <div class="row"> % end if But it would put two cards on the row, then one card on the next row, then 2, then 1, etc. I would like to use a loop because the number of courses to be displayed can change as more courses are added to the database. Here's my template file: (Technically, the language I'm using for my app is Django-Mako-Plus, so maybe this is a Django problem?) <div class="container"> <!-- TODO if using this style, figure out how to dynamically start/end bootstrap rows or similar solution --> <div class="row"> % for a in allcourses: <div class="col-md-4"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="${ STATIC_URL }homepage/media/courseimg/${a.coursephoto}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">${a.coursetitle}</h5> </div> <ul class="list-group list-group-flush"> <li class="list-group-item" style="text-align: center; font-style:italic; text-size:small;"><strong>${a.instructorid.instructorname} - Instructor</strong><br>${a.credithours.normalize()} Training Hours / 0.${a.credithours.normalize()} CEU</li> </ul> <div class="card-body"> <p class="card-text">${a.coursedescription|truncatewords:15}</p> <a href="/homepage/checkout/" class="btn btn-primary stretched-link">Learn More</a> </div> </div> </div> % if (loop.index % … -
Best approach to enrich User model in Django pluggable app
I am currently working on expanding https://github.com/suutari/drf-jwt-2fa, which provides two-factor authentication over jwt for rest-framework. I would like to make the two-factor auth non-enforced; that is, users should be able to choose if they want this extra security. For that purpose, I would like to add a boolean field (lets call it two_auth) to the user model. What is the best approach to add this field? I am currently thinking on some possibilities, but none of them seems to be neat enough: Create a relation table (user_id, two_auth) without foreign-key enforcement: I should use signals for user deletion Create a relation table (user_id, two_auth) with foreign-key enforcement: The foreign key should point to the model specified at settings.AUTH_USER_MODEL. I generally like model declaration parameters to be explicit, not patchable. -
Generate a random time for model queryset every ten minute
I am trying to generate random time beetween 20 hours a go and now, and assign it to a all queryset pass 24H. here what i make: from faker import Faker fake = Faker() from blogs.models import Post from django.utils import timezone import datetime def rotate_time(): now = timezone.now() day_pass = now - datetime.timedelta(hours=24) qs = Post.objects.filter(created__lt=day_pass) number = qs.count() lst = [] for _ in range(number): for t in [fake.date_time_between(start_date='-20h', end_date='now')]: lst.append(t) for i in lst: print(i) # this work fin until now <== x = 0 while x < len(lst): time = i[x+1] if qs.exists(): for item in qs: item.pud_date_rotation = time item.save() TypeError: 'datetime.datetime' object is not subscriptable -
Django vs Opencart, etc
What are advantages of using Django instead E-commerce/CMS systems on php? I want to make an e-commerce site for a clothing store with Django, but I'm interested to know why should I use the framework -
Dynamically update table when creating new enty using HTMX
After recent success in some simple HTMX tasks I wanted to extend adamchainz django-htmx example by a modal field that updates a table dynamically. I am not sure if I am returning the right thing in render ... but my problem is, the table is not being updated. Only when I hit reload. view: class CreateProductView(TemplateView): template_name = "app/product_create.html" form_class = OrderForm def get(self, request, *args, **kwargs): return render(request, self.template_name, {'form': self.form_class()}) def post(self, request): Product.objects.create(name = request.POST["name"], price = request.POST["price"]) part_template = "app/partial-rendering.html" return render(request, part_template, {"base_template": "app/_partial.html"}) urls.py: path("create/", views.CreateProductView.as_view(), name = 'create'), This is my index.html with the table in it: <div class="..."><button class="btn btn-primary" id="showButton" hx-get="/create" hx-target="#modal-create">create</button</div> <main role="main" id="main">{% include "app/orders_table.html" %}</main> <div id="modal-create"></div> I also have a partial-rendering.html in place: {% extends base_template %} {% block main %} {% include "app/product_table.html" %} {% endblock %} and a _partial.html: <main id="main"> {% block main %}{% endblock %} </main> I will not post the whole product_table.html here, I guess it is straight forward ... mainly: <table class="table table-striped table-hover"> <thead> <tr> <th>product name</th> <th>price</th> </tr> </thead> <tbody> {% for product in page.object_list %} <tr> <td>{{ product.name}}</td> <td>{{ product.price }}</td> </tr> {% endfor %} </tbody> </table> The … -
How to set X-FRAMES_OPTIONS to any other value than deny for Django media files embedding purposes?
I am developing a procedure where an already uploaded/generated file gets displayed in the user's dashboard through embed/iframe HTML tags. These files are HTML divs generated by plotly (Python, server-side generated). So when I try to view these files through iframe like this: <iframe width="100%" height="100%" frameBorder="0" src="http://127.0.0.1:8000/media/plots/20/plot-x-a-1.html" /> I get the following error through developers tools: Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'. As you are aware that usually it is solved by either disabling the XFramesOptions middleware entirely or to set it as ALLOWALL. The issue is, neither disabling this middleware nor adding these lines: X_FRAME_OPTIONS = 'ALLOWALL' XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE'] helped prevent the error. My guess is, media stream requires x_frames_options to be set to AllowAll or sameorigin but there is no documentation about how to do that. Is my reasoning correct? why would the browser still reject my iframe requests after such changes? Note: development is totally local at the moment. -
How to send a second (distinct) model instance to a template
Problem - I am displaying a form allowing a user to add a comment regarding an existing post. I also want to display the existing post (instance) on this same page (rendered template). The model for the template is the one accepting the comment (distinct from the post). How do I pass a model instance for the post data to the template so I can display the post too? Note - I also need the post instance because in order to store the comment in the database, it needs to be linked to the specific post id. This is probably easy and I'm missing something obvious - pointers to the right documentation welcome. I am just learning Django so I'm still learning my way around. Details: I have my model as follows (models.py): class Post(models.Model): type = models.ForeignKey( PostType, on_delete=models.PROTECT, related_name='posts', default=1 ) title = models.CharField(max_length=100) body = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.PROTECT, related_name='posts' ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments', ) body = models.TextField(max_length=1000) author = models.ForeignKey( get_user_model(), on_delete=models.PROTECT, ) def __str__(self): return f'{self.body[:75]}...' def get_absolute_url(self): return reverse('post_detail', args=[str(self.post.id)]) I have my URL routing in urls.py: urlpatterns … -
Django perform actions after oauth callback
I have a project and I want to enable users the option to use their Google/Facebook account in order to sign up/in. Also whenever a new user signs up another model (Account) is created and connected with that user. All of that works fine, but now I have a problem. When users who use the Continue with Google sign up they should be redirected to the view where I will create an Account with the user that was just created (probably not the best way to do it but I can't find any examples for better ones) Now this is where the problem occurs: If the email already exists in Users table then the user is not being transferred to the redirect url where I will perform the checks and if the account with that email exists I will show the warning back on the login/register page but rather they get redirected to allauth's ...accounts/social/signup/ url This is what I have: settings.py LOGIN_REDIRECT_URL = "/account_user/checkouath/" views.py def checkouath(request): user = request.user oauthUser = SocialAccount.objects.get(user=user) # Actions to create new Account and check if User exists are going to be here return redirect(reverse("homepage")) And this is redirect that I have set … -
What is the best way to dynamically add fields to my SearchIndex (django-haystack)?
Currently I see two possibilities, with using locals() and using setattr() after definition of SearchIndex class: 1. class TestIndex(indexes.SearchIndex, indexes.Indexable): for name in fields: locals()["attr_%s" % name] = DescriptionSearchField(boost=3, **{"d_attr": name, "name": "attr"}) locals()["slug_%s" % name] = DescriptionSearchField(**{"d_attr": name, "name": "slug"}) 2. class TestIndex(indexes.SearchIndex, indexes.Indexable): pass for name in fields: setattr(JobTestIndex, "attr_%s" % name, DescriptionSearchField(boost=3, **{"d_attr": name, "name": "attr"})) setattr(JobTestIndex, "slug_%s" % name, DescriptionSearchField(**{"d_attr": name, "name": "slug"})) I am using Django-haystack with ElasticSearch. I know that using locals() is not the best practice. What then is the correct approach to my issue? Any suggestions are greatly appreciated. Thanks. -
Secure file upload in Django - CSV/Excel files
Similar question: File upload security in Django-2.x I'm new to Django in particular, and to web development in general. I'm developing a web application in Django, which lets the user upload files. The files that are supposed to be supported are only Excel and CSV. But I concern about the security of this feature - I wonder if someone can somehow exploit this feature to remotely execute code, or causing another damage to the server running the app? Notice: the path of the uploaded files is at the level of the virtual-environment directory, that is, above the project directory itself (which contains all the Python files, etc). In case you think there are some counter-measures available to protect this kind of feature, I'd be glad to see it.