Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I made the polling app in the basic django_tutorial. I want to restrict users to one choice per question
https://docs.djangoproject.com/en/2.2/intro/tutorial01/ link for tuto. i completed the tutorial and now I want to restrict the user to answering only once, that is if he changes his option his previous vote will not be counted. -
How to implement a fast search(2-3 sec) in django containing large dataset?
I'm working on a project in Django, where I have to find a solution to create a fast search which takes roughly 2 - 3 seconds to load the search result instantaneously. I'm using Django REST API for handing the queries. Currently, I'm getting the result, but it tends to take a lot of time going through the entire database containing a lot of data. I need a solution that I can implement, so that I can reduce the search time to maximum of 3 seconds. PS. I'm using PostgreSQL as the database. -
Django url arg cannot contain NUL (0x00) characters
I'm currently testing our site for security vulnerabilities with a very limited background in security myself. When running the following request: http://127.0.0.1:8000/stuff/?template=%2Fe%00 I see the error (full stack trace below): Exception Type: ValueError at /stuff/ Exception Value: A string literal cannot contain NUL (0x00) characters. This would seem to be a problem with validating url args, and that the character 0x00 (null) shouldn't be allowed. I'm fairly sure that in google's gruyere i saw that some characters should be escaped, but it seems odd to escape null. I could of course just try/except line 92 in /code/stuff/views.py, but this will no doubt crop up elsewhere. My questions are thus: In django what is the best practice for avoiding XSS attacks via the URL? Is this alredy handled (i cant see it in the resolver) somewhere? Should this be handled elsewhere completely? Stack trace: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 97. return handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/list.py" in get 157. context = self.get_context_data() File "/code/stuff/views.py" in get_context_data … -
django installations using command prompt
Collecting django==2.2 Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x038A4EF0>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x038A42D0>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x038C2530>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x038C2730>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x038C2690>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))': /simple/django/ Could not find a version that satisfies the requirement django==2.2 (from versions: ) No matching distribution found for django==2.2 -
Sending Django form using Ajax undefined data
I am trying to send data from Django form using Ajax. I have two inputs (main category and sub category). I implemented dependent dropdown list on sub category using Ajax. When I try to submit this form using Ajax, I receive the whole html page instead of form data. Below is the code. testing.html {% block content %} <div> <form method="POST" class="testing-form" data-url="{% url 'testing' %}" data-ajax = "{% url 'ajax-test' %}"> {% csrf_token %} <p>Main Category</p> {{ form.main_category }} <p>Sub Category</p> {{ form.sub_category }} <input type="submit" value="submit" class="submit-btn" name="submit"> </form> </div> <script> $("#id_main_category").change(function() { var url = $(".testing-form").attr("data-ajax"); var mcatId = $(this).val(); console.log(url); console.log(mcatId); $.ajax({ url: url, data: { 'main_category': mcatId }, success: function(data) { $("#id_category").html(data); console.log(data); } }); }); </script> <script> $(document).ready(function(){ var $myForm = $('.testing-form'); $myForm.submit(function(event){ event.preventDefault(); var $formData = $myForm.serialize(); var $thisURL = $myForm.attr('data-url'); $.ajax({ method:'POST', url: $thisURL, data:$formData, success: handleSuccess, error: handleError, }); function handleSuccess(data) { console.log(data.message); // <- undefined } function handleError(ThrowError) { console.log(ThrowError) } }); }); </script> {% endblock content %} category_dropdown.html <option value="">---------</option> {% for cat in categories %} <option value="{{ cat }}">{{ cat }}</option> {% endfor %} views.py def testajax(request): # get main category mcat_id = request.GET.get('main_category') # cat_group is a … -
Rendering a "<class 'django.template.response.TemplateResponse'>" Object in Django
I have a requirement to incorporate my existing working openstack horizon with our SSO using py-SAML. Hence i referred to demo docs which is written here: https://github.com/onelogin/python-saml/blob/master/demo-django/demo/views.py#L113 So here as per the guide, I need to render the page as mentioned. return render(request, 'auth/login.html', {'errors': errors, 'not_auth_warn': not_auth_warn, 'success_slo': success_slo, 'paint_logout': paint_logout, 'SSO': True}) When I am trying the same I am not getting the expected result on page, Page is broken. hence I tried to return the object as our existing code setup. During analysis, I can see that template object, Which is of type: class 'django.template.response.TemplateResponse' that is the one being returned as per existing setup. When i try to return the object instead of the html file. I am getting an error. return render(request, res_ret, {'errors': errors, 'not_auth_warn': not_auth_warn, 'success_slo': success_slo, 'paint_logout': paint_logout, 'SSO': True}) Getting an error as follows: ContentNotRenderedError at /auth/login/ The response content must be rendered before it can be accessed. Someone please help me to figure out how we can resolve. Note: This is the core issue which i am facing, Let me know in case full code need to be pasted. -
Check django form validity and javascript
I'm using a django model form and I want to protect me from malicious user input. From my understanding django form are enough secure: .is_valid() check user input, csfr protect from cross site forgery. But this time my form isn't using action='/path/to/my/view' to call a django view, instead my submit button calls a javascript function and this function takes the data and calls a django view using ajax to access the database and then shows the results on screen. So I don't think to be protected anymore (.is_valid() is not called, csfr is not sent). I'm right? and if so what I should do? I think: 1) This is not a problem, the form is reasonable secure (why?) 2) Refactor the code and using a django view 3) Neither the django form validation is enough secure so anyway I should do something more (what?) 4) My javascript function is sending the data to a django view using ajax. I should use that data to instantializate a bound form and use .is_valid() on that, but anyway I'm not using csfr, right? 5) Using html validators (to me they don't look adapt to check against malicious input data) 6) Other? Some code, … -
Django Providing fixture data with filter?
I want to add some data to the database. But on production and test some data is different. Therefore, I need to make a request and substitute this data on its basis. How to do it? -
is possible call execute_from_command_line(sys.argv) inside a class?
How I must do for call in manage.py an instance o a class Initialize and execute_from_command_line(sys.argv) inside? import os import sys class InitializeService(): def __init(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RMT.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) InitializeService() I have this Error : django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. where i must insert this class? thanks -
Get image based on category django drf
i want to fetch image on particular category like if i make get request localhost/api/image/3/ i get 3rd category image view.py: class ImageView(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] pagination_class = None queryset = Image.objects.all() serializer_class = ImageSerializer api output: [ { "title": "aka", "category": 5, "image": "http://localhost:8000/media/home/tboss/Desktop/image/logo.png" }, { "title": "aka", "category": 7, "image": "http://localhost:8000/media/home/tboss/Desktop/image/DSC_9314.JPG" }, { "title": "test", "category": 3, "image": "http://localhost:8000/media/home/tboss/Desktop/image/Pillars_Outdoor_OR_RD_50003619_1280x640_DQMyGuR.jpg" } ] -
django filter returns infinite loop
When I filter the storehouses of a company, it returns the error: RecursionError: maximum recursion depth exceeded in comparison def destroy(self, request, *args, **kwargs): company = Company.objects.get(owner=self.request.user) stores = Store.objects.filter(company=company.id) if len(stores) <= 1: return Response(data={'detail': 'At least one storehouse is required'}, status=status.HTTP_400_BAD_REQUEST) return self.delete(request, *args,**kwargs) -
Blank input, hide next form-group
i have problem with JS/Jquery I will make hide .form-group in form when previous input field is empty and show show .form-group when input field have some text. I have problem with .parents(), this is not possible to use in my case pls help -
django.core.exceptions.ImproperlyConfigured: WSGI application 'auth.wsgi.application' could not be loaded; Error importing module
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'auth.settings') application = get_wsgi_application() that is the wsgi file that think results in the error above -
The class fuction to retrive photolist not working . Event the print statement is not working or logging in console
class BasicUploadView(LoginRequiredMixin,TemplateView): login_url = 'accounts/login/' redirect_field_name = 'redirect_to' def get(self, request, **kwargs): photos_list = Photo.objects.all().count() print('done') return render(request, 'upload/doc_upload.html',context= {'photos': photos_list}) def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) -
Django - Using function in template
I'm trying to figure out how to create a progress tracker for my users so they can see how many % of the form they have filled out. I'm stuck not sure how to create the function and then use it / call it in the template. Views - calculate progress function My function within my class currently looks like this (I've deliberately excluded the form in the class to avoid cluttering): class OpdaterEvalView(ModelFormMixin, DetailView): template_name = 'evalsys/evalueringer/evaluering_forside.html' model = Evaluation form_class = OpdaterEvalForm def calculate_progress(self, evaluation=None): value = [evaluation.communication, evaluation.motivate_others, evaluation.development, evaluation.cooperation] count = 0 if value[0]: count += 1 if value[1]: count += 1 if value[2]: count += 1 if value[3]: count += 1 return count * 25 The idea is that it will check the array for which values exist in the database and if 0,1,2,3 values exist it will show 25%, 50%, 75%, 100%. I just don't really know how to make this function work in my template? How do I call it? And maybe the function be outside the class? But how do I then target the specific pk of the evaluation. -
Execute Django custom command from django admin dashboard
I was wondering that if its possible to run custom django commands like startapp sampleapp from admin dashboard. I have a app registered in my project and i created the management and commands folder in that app and run want to know that how i pro-grammatically create the another app by going into django dashboard and in specific app. Something like trigger functionality like on button, when button click it execute the command which create the another djangoapp. Your suggestions are appreciated. -
DRF: Create instances of ManyToMany Relations
My models: class Order(models.Model): order_items = models.ManyToManyField('Product', through='OrderItem') class OrderItem(models.Model): order = models.ForeignKey('Order', null=True, on_delete=SET_NULL) product = models.ForeignKey('Product', null=True, on_delete=SET_NULL) class Product(models.Model): title = models.CharField(max_length=1000) The corresponding serializers: class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ('id', 'product', 'order', ) class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(source='orderitem_set', many=True, read_only=True) class Meta: model = Order fields = ('id', 'order_items') When I perform a GET-request I get the following result. Every order contains an array order_items which has a relation to a product and an order which is fine. "results": [ { "id": 1, "order_items": [ { "id": 1, "product_variation": 1, "order": 1 } ], }, ] However, I have problems creating a new order. I tried to overwrite the create method from my OrderSerializer but order_items is not in the validated data. What would be a good and appropriate way to solve this / what am I doing wrong? -
Selenium with Python- Message: 'operadriver' executable needs to be in PATH
for checking whether a website loads in opera using selenium with python, using the code def test_opera_compatability(self): driver = webdriver.Opera("functional_tests/operadriver") driver.get("https://www.google.com/") driver.quit() It returns the following error Message: 'operadriver' executable needs to be in PATH. -
Admin user is still using "old" authentication even if this one is override - Django 2.2.6
I would like to know if there is a way to persist a user in my django website. I am using SAML authentication in order to authenticate my users and make sure they have access to this application using Centrify (this is maybe too much details...) I have a custom authenticate backend which is returning a user or creating one if it does not exists (for now as a super user): def authenticate(self, request, username=None): if request.user and request.user.is_authenticated: return request.user saml_user_email = None if username: saml_user_email = username elif 'samlNameId' in request.session: saml_user_email = request.session['samlNameId'] try: user = User.objects.get(username=saml_user_email) except: if saml_user_email: user = User.objects.create_superuser(username=saml_user_email, password='simplePassword', email=saml_user_email) else: user = None request.user = user return user I know I can override the admin login page and make one. But do you know why the admin page still use the "old" authentication process even if in my settings.py I have specify AUTHENTICATION_BACKENDS = [ 'project.authentication.saml.SamlAuthentication'] . I was thinking that the admin page should be using my authentication process. Currently, when I try to connect to the admin page, I am getting redirected to the login page (which I also removed...) Is there a way for me to make sure … -
Django output csv file, filename is not setting as the value of Content-Disposition
I want to download a csv file with custom filename in a django project, but somehow the downloaded filename just display as "download.csv" instead of using the value of filename in Content-Disposition. And I also tried to print it out, but getting a very strange string =?utf-8?b?YXR0YWNobWVudDsgZmlsZW5hbWU9Iuivvueoi+aKpeWQjeaDheWGtV8yMDE5MTEyODA3NDI0Ny5jc3Yi?= the code snippet is : @action(detail=False, methods=['GET']) def download(self, request): registrations = self.filter_queryset(self.get_queryset()) csv_response = HttpResponse(content_type='text/csv') csv_response['Content-Disposition'] = 'attachment; filename="some_custom_name_{time}.csv"'.format( time=time.strftime("%Y%m%d%H%M%S", time.localtime()) ) print("asas",csv_response['Content-Disposition']) writer = csv.writer(csv_response) writer.writerow([ some content, ]) for registration in registrations: term_title = '{order} th'.format(order=registration.term.order) course_title = registration.course.title writer.writerow([ registration.user.email, course_title, term_title, str(registration.confirmation_code), str(registration.payment_due), str(registration.payment_paid), str(registration.source), str(registration.created_at), str(registration.updated_at), str(registration.payment_source), ]) return csv_response the django I am using is 2.2 any ideas why this is happening? I am a newb. Thx in advance -
corss domain login problem sessionid cookie not set in a django-graphql backend api on aws eb
I have setup a django-graphene application on aws eb successfully but there are authentication problems from cross domain. Logins are working on same domain but when trying to login from cross domain it do not work. Using session based authentication (Cookies) My django-graphql api is on a url something like: http://foo.bar.elasticbeanstalk.com/graphql/ When I login from Insomnia (similar to postman) the login works. This is the response I receive Date: Thu, 28 Nov 2019 06:36:39 GMT Server: Apache/2.4.41 (Amazon) mod_wsgi/3.5 Python/3.6.8 Vary: Cookie,Origin X-Frame-Options: SAMEORIGIN Set-Cookie: csrftoken=1FTnBwp8b3OlVVf1NXZqZtWBoZkA1xh4ihryPtvZeTRZj3od5mHn3tDxFhgFvGl9; expires=Thu, 26 Nov 2020 06:36:39 GMT; Max-Age=31449600; Path=/; SameSite=Lax Set-Cookie: sessionid=vv9e1o2m92ekwcaq8xhzoedf9uhues4u; expires=Thu, 12 Dec 2019 06:36:39 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax Content-Length: 190 Content-Type: application/json In insomnia it works the user is logged in. On the frontend I am using gatsby and apollo. The front end is currently running on http://localhost:3000. This is my Apollo client: import ApolloClient from "apollo-boost" import { fetch } from "isomorphic-fetch" const client = new ApolloClient({ uri: "http://foo.bar.elasticbeanstalk.com/graphql/", credentials: "include", fetch, }) export default client When I perform the login mutation no sessionid cookie is set. There is also no csrftoken. Login mutation response: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://localhost:3000 Connection: Keep-Alive Content-Length: 271 Content-Type: application/json Date: Thu, 28 Nov 2019 … -
How to filter a nested serializer's field in Django DRF
I have two models named 'School' and 'Student'. I've created each's serializers and the nested serializer for School having a student serializer as a nested field. Here I want to apply filters on the fields of the serializers using 'django-filters' and it is almost working, BUT ...the problem is that when I filter the nested field, i-e 'students's field' , It doesn't show me the required result. My models are : class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) is_government = models.BooleanField(default=True) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School,related_name='students',on_delete = models.CASCADE) is_adult = models.BooleanField(default=True) def __str__(self): return self.name and my serializers are: class SchoolSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass # Instantiate the superclass normally super(SchoolSerializer, self).__init__(*args, **kwargs) allow_students = self.context.get("allow_students",None) if allow_students: self.fields['students'] = StudentSerializer(many=True, context=kwargs['context'], fields=['name','age','is_adult']) class Meta(): model = School fields = '__all__' class StudentSerializer(DynamicFieldsModelSerializer): class Meta(): model = Student fields = '__all__' and these are the filters that i am using in my views: from django_filters.rest_framework import DjangoFilterBackend from django_filters import FilterSet from django_filters import rest_framework as filters class SchoolStudentAPIView(generics.ListAPIView, mixins.CreateModelMixin): queryset = School.objects.all() serializer_class = SchoolSerializer … -
AuthenticationForm valid Unknown every time in DJANGO
VIEWS.py: def login_user(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): return redirect(user_details) else: form = AuthenticationForm() return render(request, 'django_app/loginuser.html', {'form': form}) `` `please see the below screenshot for the code execution `please see the below screenshot for the code execution i am unable to login with my crdentials -
After Django page refresh Seaborn plot legend have been copy and append
I am try to use Django with Seaborn. First time plot is show perfact but after page refresh plot is ok but same legend copy. I have attached my output image. My code is def complete_application(request, *agrs, **kwargs): sns.countplot(x='licensefor', hue='licensestatus', data=licenses_complete) plt.legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.) plt.tight_layout() figfile = BytesIO() plt.savefig(figfile, format='png') figfile.seek(0) # rewind to beginning of file figdata_png = base64.b64encode(figfile.getvalue()) content_data = { 'result':figdata_png.decode('utf8'), } return render(request, 'complete_application.html', content_data) I have find solution in stackoverflow but i can not get any answer related to this. Thanks -
makemigrations for a model that is created via inspectdb
I have a database in microsoft sql server. I created tables and views in it. I ran py manage.py inspetdb view_Name > Models.py and populated my models.py file with managed=false. I also dont want my model to alter my database. I just want it for data retrieval. After inspectdb should i apply makemigrations on my app or is just migrate enough? And also what are the points to remember while using inspectdb on an existing database. Also I have something like the below in my models.py file for all columns created = models.DateTimeField(db_column='Created', blank=True, null=True) # Field name made lowercase Is having the fieldname in lowercase safe ? Or should I change it as it is in my column? And what are those db_column='Created', blank=True, null=True fields. Not all my views have such fields. Only a few have such values.