Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to ensure that users can only access/update data created by them
I wish to create an API that allows a user to access/update details of Books only uploaded by them. The user should not have permission to access/update a book that has been created by someone else. This is my models.py: from django.contrib.auth.models import User class Project(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=200) class Book(models.Model): project = models.ForeignKey(Project,on_delete=models.CASCADE) name = models.CharField(max_length=200) total_pages = models.IntegerField() This is my serializers.py: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = "__all__" Here is my views.py: class BookDetails(generics.RetrieveUpdateDestroyAPIView): serializer_class = BookSerializer queryset = Book.objects.all() How do I modify the views.py such that the user can only access/update books created by him? -
How to use jmeter to test django web?
django web use @login_required .when I post a login request with jmeter , I got "invalid" instead of logining success. How can I use Jmeter to test Django web. -
Django 2.1 - CSRFToken change
Im having a problem migrating my DJANGO application from 1.11 to 2.1 During development, I have a node.js server (frontend) on port 3000 and DJANGO dev server on 8000. Frontend makes Ajax call protected by CSRFtoken. I have a view called at the fronted start with the @ensure_csrf_cookie decorator. The first time I usually had to go to chrome://net-internals/#events start the frontend, taking the csrftoken value returned from server and then create the relative cookie. Unfortunally the cookie is not automatically create with this configuration. The problem is. Django 1.11 generate the same CSRFToken even after a full refresh so after the first time, the cookie will be equal to generated token. Django 2.1 change the csrftoken every time so I'm not able to create a cookie becase it will always equals to the previous value. WHy Django 2.1 change the csrftoken even if default duration is 1 year? -
Use value of one dictionary as key of another dictionary in Django?
Consider these two dictionaries: a = {'f': 'foo'} b = {'bar': 20, 'foo': 10} In Python, should I want to use the value of one dictionary as a key to another, I can do: print(b[a['f']]) >>>10 However, in Django, I haven't been able to implement the same. I have tried using these: {{ b.{{a.f}} }} which result in Could not parse the remainder: '{{a.f from 'b.{{a.f' Similarly I have tried using these: {{ b.{{a['f']}} }} {{ b[a['f']] }} {{ b[a.f] }} None of them seem to work. What should I do to implement the above said python code in Django Template Language -
Django: How to decode the url to get the variable value?
I'm trying to do django api. Here is the code in urls.py url(r'^edit/(?P<name>[\w-]+)/$',UpdateView.as_view(),name="update") views.py class UpdateView(RetrieveUpdateView): queryset = Book.objects.all() serializer_class = BookUpdateSerializer lookup_field = "name" The name variable might include '|' symbol. When i type 127.0.0.1:8000/edit/api/ABCD|1234 , which ABCD|1234 is one of the variable name, the url will automatically encode it become 127.0.0.1:8000/edit/api/ABCD%7C1234. It can't find this name from my database. How can I decode it and retrieve data from my database? Thanks a lot. -
Django JSONField, default, blank and null
I have a few JSONField fields in a Django model, like this: func_args = JSONField( _('arguments'), blank=True, default=list, help_text=_('*args of the function call'), ) func_kwargs = JSONField( _('keyword arguments'), blank=True, default=dict, help_text=_('**kwargs of the function call'), ) output = JSONField( _('JSON output'), blank=True, default=None, help_text=_('The output of the function call converted to JSON') ) With this definition, when the user does not fill any of the fields in the admin, I expect Django to save the func_args field as [], func_kwargs as {} and output as null. However, when the user saves it, I get errors like this: null value in column "func_kwargs" violates not-null constraint Why is Django trying to save an empty field as null and not the default {}? I use Django 1.11 with a PostgreSQL database. -
Django 1.9 How do you filter child's child's model?
I have a parent model Catalog and its child model Product and Product's child model Options. Catalog and Product's relationship is OneToOne and Product and Options's relationship is OneToMany I'd like to filter if one of Options is met a condition, return Catalog model here is my code below class Catalog(models.Model): product = models.ForeignKey(models.Product) class Product(models.Model): objects = ProductManager() class ProductOptions(models.Model): product = models.ForeignKey(Product, related_name = 'options') class ProductManager(models.Manager): def get_queryset(self): queryset = super(ProductManager, self).get_queryset() queryset = queryset.prefetch_related('options') return queryset and What I've tried so far is catalog_query = models.Catalog.objects.all().filter(product__options__date=datetime(2018,10,24) and the result is that it returns all the data no filtered -
Getting current location of user using Azure maps
I'm working on a Django project where I need the current location of the user when the user presses a certain button. I need to do this with the help of Azure Maps. I have read their documentation. Still, I'm unable to find a way to get the user's location. What I want is when the user presses the button the Azure maps API must return me the user's location. 1. Is it possible to get the user's location using Azure maps? 2. If yes, how can I get started ( any resource/documentation )? -
Handling real time Graph data
I'm showing real time graph data from MySQL. The Graph is used to show data for several time periods(ex. one day, one month, six months).Front-end is calling API every second.And the data which is being fetched from MySQL is also being called from other API services, which means there is a huge amount of request getting generated almost 50k requests per minute.Now while there will be around like 50k - 1 million data on that table the response will be quite slow. Please clear my doubts: Should I go for socket? If socket what should be the architecture for high availability? Should I go for NoSQL or realtime database like influx db? P.S. High Availability and resilience to failure in distributed architecture. kindly suggest me the solution of this problem. -
How to increase (Object ID) PostgreSQL Auto Increment (xx_xx_pkey) manually?
I'm using django and postgresql. I tried to generate data with Copy (sql). Django does the auto increment of id. Presumably, the bi id value is kept in a table. I can't figure out which table this is. I want to update it manually. I get the error in the following way. IntegrityError: duplicate key value violates unique constraint "conversations_message_pkey" DETAIL: Key (id) = (153226) already exists. I think the conversations_message_pkey value is in a table in pg_catalog. -
Automatically update model relationship after saving to the DB
Let's say I have the following two Django models A and B: class A(models.Model): pass class B(models.Model): a = models.ForeignKey('reval.A', on_delete=models.CASCADE) I would like to instantiate both of them and then save them to the DB in the following way: # Code sample 1 a = A() b = B() b.a = a # Do something with b.a, e.g. b.a.some_method() a.save() b.save() Although a has been saved to the DB before b and therefore already has an ID, b.save() will fail with an IntegrityError: IntegrityError: null value in column "a_id" violates not-null constraint DETAIL: Failing row contains (1, null). As a "workaround", it is possible to re-assign a to b before calling b.save(): # Code sample 2 a = A() b = B() b.a = a # Do something with b.a, e.g. b.a.some_method() a.save() b.a = a b.save() This works but it seems redundant having to assign a to b twice. It feels like b should know about a having changed or having been saved to the DB. Is there a way to make code sample 1 work? -
How to get all groups which is associated by user?
I am new in python & django. I have a users list where i want to get particular user assigned groups list in comma separated. Thanks -
Is there a way not to use the default tables in DJango?
I am going to make a very simple Restful API. So there is no reason to use the default tables in Django. auth_group auth_group_permissions auth_permission django_admin_log etc.. Of course there is a way to use Flask, but now I do not have time to study Flask. Is it possible to define and use only the model(table) I want without using the default tables provided by DJango? Thanyou!! -
Getting dictionary key values in django template
I have a dictionary created with Counter() in django. I have a list named studentlist. I fill this list with some elements. Then i get the repeating elements number with Counter(). In my view : studentlist = [] for stu in studentslatetoclassthissemester: student = str(stu['student__std_no']) studentlist.append(student) studentsum = Counter(studentlist) So studentsum is a dictionary as below. Counter({'0247': 4, '0044': 1, '0050': 1, '0241': 1, '0854': 1, '0245': 1, '0076': 1, '0234': 1}) In the django template i am trying to get specifi key and values as below : {% for key, value in studentsum.items %} {{key}} - {{value}} {% endfor %} But i get below error : Exception Type: TypeError Exception Value: 'int' object is not iterable -
Identify the table dependencies graph from django models
I am using Django for my project and I came across a case where I need to identify the table dependencies by considering all the django models created in the project. It should cover all types of relationships including Many to Many Many to One One to One Table inheritance Currently, I am trying it using _meta attribute, I am including my approach here. def build_table_dependecy_graph(models: [Model]) -> DependencyGraph: graph = DependencyGraph() for model in models: for dependency in _find_foreignkey_references(model): graph.add_dependency(dependency, _get_table_name(model)) for dependency, table in _find_many_to_many_relations(model): graph.add_dependency(dependency, table) return graph def _find_foreignkey_references(model: Model): return [_get_table_name(foreign_related_field.model) for field in model._meta.fields if hasattr(field, 'foreign_related_fields') for foreign_related_field in field.foreign_related_fields] def _find_many_to_many_relations(model: Model): many_to_many_relationships = [field for field in model._meta.get_fields(include_hidden=True) if field.many_to_many and field.auto_created] for many_to_many_model in many_to_many_relationships: yield (_get_table_name(many_to_many_model.model), _get_table_name(many_to_many_model.through)) yield (_get_table_name(many_to_many_model.related_model), _get_table_name(many_to_many_model.through)) I don't know whether there is a better way of doing this in Django. Please help. -
How to inspectdb for 2 or more tables in django for legacy database in one execution?
Is there a way to inspect multiple tables from the existing database. There is a way to get all the tables or one of the table from the existing database. But how to do it for say 2-30 tables from a database containing 400 tables -
CannotPullContainerError on Deploying Multi-container App on ElasticBeanstalk
I have a multi-container app which I want to deploy on ElasticBeanstalk. Below are my files. Dockerfile FROM python:2.7 WORKDIR /app ADD . /app RUN apt-get update && \ apt-get upgrade -y && \ apt-get install -y \ apt-utils \ git \ python \ python-dev \ libpcre3 \ libpcre3-dev \ python-setuptools \ python-pip \ nginx \ supervisor \ default-libmysqlclient-dev \ python-psycopg2 \ libpq-dev \ sqlite3 && \ pip install -U pip setuptools && \ rm -rf /var/lib/apt/lists/* RUN pip install -r requirements.txt EXPOSE 8000 RUN chmod +x entry_point.sh docker-compose.yml version: "2" services: db: restart: always container_name: docker_test-db image: postgres:9.6 expose: - "5432" mem_limit: 10m environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=docker_test redis: restart: always image: redis:3.0 expose: - "6379" mem_limit: 10m web: # replace username/repo:tag with your name and image details restart: always build: . image: docker_test container_name: docker_test-container ports: - "8000:8000" environment: - DATABASE=db - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=docker_test mem_limit: 500m depends_on: - db - redis entrypoint: ./entry_point.sh command: gunicorn docker_test.wsgi:application -w 2 -b :8000 --timeout 120 --graceful-timeout 120 --worker-class gevent celery: image: docker_test container_name: docker_test-celery command: celery -A docker_test worker -l info links: - db - redis mem_limit: 10m depends_on: - web cbeat: … -
when I type <django-admin startproject mysite> in terminal I get the else message bellow. I do have python3 and django==2.1 installed. any thoughts?
if command -v python3 > /dev/null && test -e /usr/lib/python3/dist-packages/django/bin/django-admin.py then exec python3 "$0" "$@" elif command -v python2.7 > /dev/null && test -e /usr/lib/python2.7/dist-packages/django/bin/django-admin.py then exec python2.7 "$0" "$@" else echo "Cannot find installed version of python-django or python3-django." >&2 exit 1 -
Django ORM for SQL query with multiple left joins
I have a SQL query which I am trying to make it as a Django ORM, tried many ways but didn't get the exact solution for it. select c.* from product p left join voucher v on v.id = p.voucher_id left join customer c on c.id = v.customer_id where p.id=3; -
Queryset fetched in view and passed to template
What happens if a queryset that was already evaluated in view, is passed to a template? Iterating through it would use the cache or it trigger another db query? views.py books = Books.objects.all() len (books) #from db template for book in books: #uses cache or db? .... -
Django data saving and presenting
My django project need to acquire one list after processing in one function of setting.py. def acquire(request): import sys n = [] for topic in Topic.objects.filter(owner=request.user).order_by("date_added"): entries = topic.entries.all() q = entries.text n.append(q) return render(request, "projects/topics.html", n) The list "n" above need to be transferred to another function of setting.py for the information in another "results.html" page. def results(request): data = XXXX return render(request, "projects/results.html", {"datas": data}) How could I edit "XXX" in results function to transfer the "n" list? Thx! -
ImproperlyConfigured: Requested setting INSTALLED_APPS
I'm trying to run PyDoc on a models.py file and I keep getting the following error message: problem in models - ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. How can I resolve this? -
Cannot import ASGI_APPLICATION module error while using channels
I am using channels==2.1.5 and django==2.1.2. While configuring routing I am getting an error Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f3a960631e0> Traceback (most recent call last): File "/home/anoop/Training/django-sample-channels/venv/lib/python3.6/site-packages/channels/routing.py", line 33, in get_default_application module = importlib.import_module(path) File "/home/anoop/Training/django-sample-channels/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/anoop/Training/django-sample-channels/example_channels/example_channels/routing.py", line 4, in <module> from exapmle.routing import websocket_urlpatterns File "/home/anoop/Training/django-sample-channels/example_channels/exapmle/routing.py", line 2, in <module> from django.conf.urls import path ImportError: cannot import name 'path' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/anoop/Training/django-sample-channels/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/anoop/Training/django-sample-channels/venv/lib/python3.6/site-packages/channels/management/commands/runserver.py", line 101, in inner_run application=self.get_application(options), File "/home/anoop/Training/django-sample-channels/venv/lib/python3.6/site-packages/channels/management/commands/runserver.py", line 126, in get_application return StaticFilesWrapper(get_default_application()) File "/home/anoop/Training/django-sample-channels/venv/lib/python3.6/site-packages/channels/routing.py", line 35, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'example_channels.routing' In my settings file, I configured ASIG as follows ASGI_APPLICATION = 'example_channels.routing.application' where example_channels is root project directory. And my root routing file is as follows from channels.auth … -
Django, I can't pass float/integer to my templates
Thank for helping me I'm trying to pass Floats data form the model to a table in templates Now the problems: nothing show up in templates this my models.py Class number(models.Model) Alpha =models.FloatField() Alpha = ((1.8,7.7,19), (1.9,7.3,20), (1,7,6.9,19)) This my vies.py Def get (request): data = number.object.all,{} return render(requset, 'Webapp/body.html',{'data':data}) this my template = body.html {%block content%} <div> {%for data in content%} {{data}} {%endfor%} </div> {%endblock%} It will be best if you could write me a example code -
a few questions about Python
I am a student at college. Recently I want to make an interface on the phone, and then I can execute and terminate a program on the server through the phone. On the server, I use Flask(app.py) as backend, taking the parameters from the front end and building the command string (such as "python test.py -para=1"), and then I use os.system(command) to execute the command. But there are several problems: I moved the return value of the os.system(cmd) to the right by 8bits (as if 8bits were PID), saved as PID, and then executed "kill -9 "+PID, but the result was a restart of the server. What's going on here? And how do I get the PID executed by the program and terminate the program through PID? Python on the server has two environments, one is the global environment, and the other is the virtual environment created by anaconda. If I want to use Python in the virtual environment, how do I build the command string? When the server executes the test.py program, I want to send the value of a variable in test.py bask to the front end in real time. What should I do? My idea is to …