Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to use GraphQL query the mptt tree with single request?
I can query the MPTT whole tree with Django REST using serializer. Now I am upgrading my service to support GraphQL as well. But the only single way I can do with iGraphQL is supply the deep down at most to get the last child node of tree Here is my DRF and my common technique to query tree models.py from mptt.models import MPTTModel class Question(MPTTModel): answer = models.TextField(null=True, blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') serializers.py from rest_framework import serializers from questions.models import Question class QuestionTreeSerializer(serializers.ModelSerializer): class Meta: model = Question fields = [ 'id', 'parent', 'children', ] def get_fields(self): fields = super().get_fields() fields['children'] = QuestionTreeSerializer(many=True) return fields And here is my current GraphQL implementation from graphene import relay from graphene_django import DjangoObjectType from questions.models import Question class QuestionType(DjangoObjectType): class Meta: model = Question interfaces = (relay.Node,) fields = [ 'id', 'name', 'children', 'parent', ] class QuestionConnection(relay.Connection): class Meta: node = QuestionType class Query: questions = relay.ConnectionField(QuestionConnection) @staticmethod def resolve_questions(root, info, **kwargs): return Question.objects.all() Here is my current query query{ questions{ edges{ node{ id name children { edges { node { id name children { edges { node { id children { edges { node { id } … -
Keycloak integration with Django
I need help on keycloak integration with django. Here i am trying to achieve whenever user login i want to check keycloak authentication. please any one help me on that scenario Thankyou -
How to connect React with Django?
In team project, our team decided to use React and Django, and I decided to take the backend through Django. As I known, Django associates a view with a template html file that shows the view, and today I know that React returns a js not html. Does it work if I put the set of files that React returns into the Django template folder? Or is there another way? -
Django handling post request on URL
Total newbie here. I am trying to handle POST request in Django and parse some values from JWT to insert into database. However, I do not know what to use to process the POST request. For example, json file will be sent with the POST request to the URL "http://example.com/post". For Parsing json I have no problem. Thanks in advance. -
How to find django static files in production
I am trying to get a django web site into production. The dev version works fine, but in production the application does not seem to find my css files. I know that there are a lot of queries similar to mine and I have perused many and tried the suggested solutions. The production version seems to work perfectly apart from the static files issue In settings.py I have DEBUG=False and STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_files') I have run python manage.py collectstatic and the css and js directories are copied correctly into my_app/static_files I have restarted the server but it still does not function correctly. My tree on the production server is: . ├── my_app │ ├── __init__.py │ ├── settings.py │ ├── static │ │ ├── css │ │ │ ├── main.css │ │ └── js │ ├── templates │ │ ├── base.html │ ├── urls.py │ └── wsgi.py ├── boards │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── templates │ │ └── boards │ │ ├── about.html │ │ ├── contact.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── passenger_wsgi.py … -
Django processing data in different process
I am currently planning a django project which consists of two parts. The normal django application and an additional application which uses MQTT to read sensors. For better loading times for the HTTP responses, I planned to receive the MQTT publish messages in an external process or thread and write it into the database used by django. The sensor data in this database then is always used whenever a HTTP request is made. Do you guys have any better architectural solutions to my problem? Best regards -
django postgres integration error, no such table - auth user
After updating the django settings.py default database to correct values. i am able to run makemigrations and migrate command and also create super user. but when i login to the admin it gives me error of “no such table - auth user, OPERATIONAL ERROR”. I noticed that even if i delete db.sqlite3 file, it comes back when i try to login, i think django looks for table in db.sqlite3 and not postgres. why db.sqlite3 file re appear after deleting ? how do i correctly configure my settings.py ? i am integration using digitalocean managed database services with django installed in one droplet, i have integrated both preciously without error but i installed postgres, this is the first time using managed database service. Thanks -
Djano reverse relations serialization
I have many to many relations and i want to serialize reverse relation. Here are my models: class Nutrition(models.Model): name = models.CharField(max_length=30, blank=False) def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=30, blank=False) nutritions = models.ManyToManyField(Nutrition, blank=True, related_name="companyID") def __str__(self): return self.name And here are my serializers: class NutritionSerializer(serializers.ModelSerializer): companyID = CompanySerializer(read_only=True, many=True) class Meta: model = Nutrition fields=('id', 'name', 'companyID') class CompanySerializer(serializers.ModelSerializer): nutritions_list = NutritionSerializer(source="nutritions", read_only=True, many=True) class Meta: model = Company fields = ('id', 'name', 'nutritions_list') And i'm getting an error: NameError: name 'CompanySerializer' is not defined -
How to insert data in to multiple table using django orm
i have created 2 table, ie table1 and table2 i want to insert data in to both tables using django ORM , how can i achieve it models.py class Table1(models.Model): name = models.CharField(max_length=20,null=True) class Table2(models.Model): name = models.CharField(max_length=20,null=True) views.py class Test(ListAPIView): def get(self,request): obj1 = Table1(name="jasir") obj2 = Table2(name="shibin") obj1.save() obj2.save() return Response(True) im saving like this but i want to save it using single save() instance is there any possiblity the equivalent sql query i found is BEGIN TRANSACTION INSERT INTO Table1 (name) VALUES ('jasir') INSERT INTO Table2 (name) VALUES ('shibin') COMMIT TRANSACTION how to do the same with django ORM -
What is the right way to learn Django?
I am familiar with Python and Flask, but now I want to learn Django. What should I focus on? I want to build web applications with Python, so Django seems adapted to what I want. This is a short list of why I want to use Django: develop a web app or API backend. move fast, deploy fast secure app from vulnerabilities and attacks: CSRF, SQL Injection... need ORM support -
Django: What does {{ secret_key}} mean?
I am trying to learn Django. I am setting up a small project structure by following the recommendation in the Django TwoScoops Project (https://github.com/twoscoops/django-twoscoops-project). In the settings file, I see some code like this: ########## SECRET CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Note: This key should only be used for development and testing. SECRET_KEY = r"{{ secret_key }}" ########## END SECRET CONFIGURATION Is the {{secret_key}} supposed to represent some placeholder or what? If it is a placeholder, where is the value picked up from? If I use django-admin startproject foo to create a project, I see there is a long SECRET_KEY value that is present. -
Django Deserialization Error Problem installing Fixture?
Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/serializers/json.py", line 69, in Deserializer yield from PythonDeserializer(objects, **options) File "/usr/local/lib/python3.7/site-packages/django/core/serializers/python.py", line 91, in Deserializer Model = _get_model(d["model"]) TypeError: string indices must be integers The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) for obj in objects: File "/usr/local/lib/python3.7/site-packages/django/core/serializers/json.py", line 73, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture '/app/src/add.json': This is the above error showing when I am trying to push my json file into the database. My json file looks like this: [ { "pk": "51", "model": "landings.Product", "fields": { "name": "mirrorcheck", "merchant_id": "9", "category": "retail", "has_many_subs" : "True", "mnp_service_name": "1", "sub_service_name":"1", "operator_id": "1", "partner_id": "1", "mnp_service_name_card":"1", "sub_service_name_card":"1", "defenition":"kek" } } ] P.S. I saw a similar question, like there are no errors. -
Django - SimplerXMLGenerator - add an attribute to an element?
I'm Using the SimplerXMLGenerator in Django to create an xml document, however I can't find the documentation that shows how to add an attribute to a tag. I have the below xml created thus far <subnet> <from>192.168.1.1</from> <mask>255.255.255.0</mask> </subnet> but my desired output is <subnet from="192.168.1.1" mask="255.255.255.0"/> I found the below code which creates the current output and ive tried amending to create my desired output. def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: print('item:{}'.format(item)) xml.startElement(self.item_tag_name, {}) self._to_xml(xml, item) xml.endElement(self.item_tag_name) elif isinstance(data, dict): for key, value in six.iteritems(data): xml.startElement(key,{}) self._to_xml(xml, value) xml.endElement(key) I tried to modify startElement as a test to the below but was prompted with a too many arguments message. how do I add element attributes to a tag? xml.startElement(key, "from", {}) -
Django admin saves the form when condition is false because of inline connected images form when i select an image
This image check the condition if the user has selected the end date greater then the start date If the user selects the image in this form which is inline tabular the upper condition fails and form is submitted I am overriding the save_model method which checks the condition , goes inside the condition but takes me to options.py which check the form.is_valid() function and inline form is valid and ignores the error. This Error Comes and says the save() method is prevented because primary key is None so it is reverting back it to previous state can any body HELP These are the steps i am doing while submitting a form from django admin. -
Checking record owner before editing in Django
I’m learning Django, but it’s hanging on such a seemingly simple moment. I need to check and allow the user to edit only his posts, and if he clicks the link for editing someone else’s - render a specific page. I can not form a condition for user verification, please help: views.py @login_required def blogs_edit_text_post(request, post_id): post_form = PostForm(instance=TextPost.objects.get(id=post_id)) owner = TextPost.objects.get(pk=1) if request.user == owner: if request.method == "POST": post_form = PostForm(request.POST, instance=TextPost.objects.get(id=post_id)) if post_form.is_valid(): post = post_form.save() return redirect(blogs_blog) return render(request, 'blogs/edit_text_post.html', { 'post_form': post_form }) else: return render(request, 'blogs/error_page.html', {}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile_user_id') blog_title = models.CharField(max_length=300, verbose_name='Название блога') blog_description = models.TextField(max_length=500, verbose_name='Пара слов о себе', blank=True) profile_pic = models.ImageField(default='nophoto.jpg', upload_to='user_pics/', blank=True, verbose_name='Аватар') class TextPost(models.Model): author = models.ForeignKey(Profile, on_delete=models.CASCADE) title = models.CharField(max_length=300, verbose_name='Заголовок') post = models.TextField(max_length=500, verbose_name='Текст поста', blank=False) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) urls.py path('blogs/blog/', views.blogs_blog, name='blogs-blog') -
AM working on a site using django framework and i got this AttributeError
enter code hereAttributeError at /polls/ enter code here'str' object has no attribute 'get' enter code hereRequest Method: GET enter code hereRequest URL: http://127.0.0.1:8000/polls/ enter code hereDjango Version: 2.0.2 enter code hereException Type: AttributeError enter code hereException Value: ``'str' object has no attribute 'get' enter code hereException Location: C:\Python34\lib\site-packages\django-2.0.2-py3.4.egg\django\middleware\clickjacking.py in process_response, line 26 enter code herePython Executable: C:\Python34\python.exe enter code herePython Version: 3.4.1 enter code herePython Path: ['C:\Users\WUESE PHILIP\Desktop\vibezt', enter code here'C:\Python34\python34.zip', enter code here'C:\Python34\DLLs', enter code here'C:\Python34\lib', enter code here'C:\Python34', enter code here'C:\Python34\lib\site-packages', enter code here'C:\Python34\lib\site-packages\setuptools-33.1.1-py3.4.egg', enter code here'C:\Python34\lib\site-packages\django-2.0.2-py3.4.egg', enter code here'C:\Python34\lib\site-packages\pytz-2019.3-py3.4.egg']` enter code herepolls urls.py` enter code herefrom django.urls import path enter code herefrom . import views enter code hereurlpatterns = [ enter code herepath('', views.index, name='index'), enter code here]` enter code hereviews.py` enter code herefrom django.shortcuts import render enter code herefrom django.http import HttpResponse enter code heredef index(request): return("Welcome to my First Python Django Project") enter code herevibezt urls.py` enter code herefrom django.contrib import admin enter code herefrom django.urls import include, path enter code hereurlpatterns = [ enter code herepath('polls/', include('polls.urls')), enter code herepath('admin/', admin.site.urls), enter code here]` -
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