Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is Viewflow for superusers only?
I'm learning django viewflow (non-Pro) and the all processes that I've been creating works for superuser users only Is that normal? Thanks, José.- -
Use Django_compressor ES6Compiler under Windows
I tried to run a Django App I developed under Linux on an Windows setup. The Application starts, but when I enter a page with a template which uses the compressor like this ("index.js" imports npm packages): {% load static %} {% load compress %} <html> ... <body> ... {% compress js %} <script type="module" src="{% static 'index.js' %}"></script> {% endcompress %} </body> </html> .. I get this Error: Traceback (most recent call last): File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\neuz8t\Downloads\cs_viewer_server\cs_viewer\views.py", line 19, in index return render(request,'cs_viewer/index.html',{'graph_elements':tmp_graph_elements_json}) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\compressor\templatetags\compress.py", line 131, in render return self.render_compressed(context, self.kind, self.mode, forced=forced) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\compressor\templatetags\compress.py", line 107, in render_compressed rendered_output = compressor.output(mode, forced=forced) File "C:\Users\neuz8t\AppData\Local\Programs\Python\Python37\lib\site-packages\compressor\js.py", line 50, in … -
ModuleNotFoundError: No module named 'django' when creating project with mkproject
I am trying to create a django project using virtualenvwrapper. I have installed virtualenvwrapper and virtualenvwrapper.django template. But whenever I try to create a django project using mkproject command I get the error mentioned in the title. Here is my terminal output: $ mkproject -t django todolist Using base prefix '/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7' New python executable in /Users/tanmay/.virtualenvs/todolist/bin/python3.7 Not overwriting existing python script /Users/tanmay/.virtualenvs/todolist/bin/python (you must use /Users/tanmay/.virtualenvs/todolist/bin/python3.7) Installing setuptools, pip, wheel... done. virtualenvwrapper_cd:cd:6: no such file or directory: /Users/tanmay/django-code/todolist Creating /Users/tanmay/django-code/todolist Setting project for todolist to /Users/tanmay/django-code/todolist Applying template django Requirement already satisfied: django in /Users/tanmay/.virtualenvs/todolist/lib/python3.7/site-packages (2.1.7) Requirement already satisfied: pytz in /Users/tanmay/.virtualenvs/todolist/lib/python3.7/site-packages (from django) (2018.9) virtualenvwrapper.django Running "django-admin.py startproject todolist" Traceback (most recent call last): File "/Users/tanmay/.virtualenvs/todolist/bin/django-admin.py", line 2, in <module> from django.core import management ModuleNotFoundError: No module named 'django' (todolist) ➜ todolist python Python 3.7.0 (default, Oct 2 2018, 09:18:58) [Clang 10.0.0 (clang-1000.11.45.2)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from django import get_version >>> get_version() '2.1.7' Also the list of pip packages in that environment: (todolist) ➜ todolist pip list Package Version ---------- ------- Django 2.1.7 pip 19.0.3 pytz 2018.9 setuptools 40.8.0 wheel 0.33.1 As you can see, Django is installed. Also, I … -
Build a website using two tables in django
I want to create a website. I work in Python and I use django framework. In my database, I have two tables - the first is containing texts and the second containing images. I want to replace an image in the middle of the text, but I do not know how to use the command inside the page content. Of course, I can write {{ Page.text|safe }} {{ Image.code|safe }} but it very important for me it's important for me to have the picture in the middle of the content. I specially created two tables, because I did not want to mix the content with the code describing the picture. Could you help me? -
Celery task/retry never executes try else block
I have a celery shared_task setup to retry up to 10 times if it doesn't succeed the first time. The initial log statement is only executed once. None of the exceptions ever get raised nor does the try/else. The statement after the try does execute and it shows the from log entries that it succeeded. So what I would like to happen is the try/else to be executed when it finally succeeds. What's going on here? @shared_task(bind=True, default_retry_delay=15, max_retry=10) def host_accepted(self, data, username, version): from .api.views import LdapHostGroupView name = data.get('name', '') version = Decimal(version) log.debug("name: %s, version: %s, version type: %s, data: %s", name, version, type(version), data) try: obj = Transaction.objects.get(endpoint_name=name) except Transaction.DoesNotExist as e: msg = "Could not find transaction '{}'".format(name) log.critical(msg) syslog.critical(msg) else: try: result = LdapHostGroupView().start(data, username, version) except RealmBundleDoesNotExist as e: log.debug("Bundle does not exist yet.") obj.job_summary += str(e) + '\n' obj.job_status = Transaction.INPROGRESS obj.save() self.retry(exc=e) # ** self.request.retries) except (RealmCriticalException, ValidationError) as e: error = e.get_full_details() log.debug("Host Accepted error: %s", error) if isinstance(error, dict): for field, values in error.items(): for value in values: ed = value.get('message') if isinstance(ed, ErrorDetail): item = str(ed) else: item = value msg = "Field '{}' has error: {}\n".format(field, item) … -
Django - counting foreign keys in models
I know how I can count things with annotate (in my view) but I would like to do the same in model (so it would be more reusable). For example (lets take an example from django documentation) I have this model: class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Publisher(models.Model): name = models.CharField(max_length=300) class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) pubdate = models.DateField() class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) and I can use in view this: from django.db.models import Count pubs = Publisher.objects.annotate(num_books=Count('book')) But how I do that in model? I know this question is pretty basic (probably) but I'm pretty much beginner in django. Thanks for answers! -
Nested action in a GenericAPIView
How can I create a new nested route in GenericAPIView in django rest framework for enable a API URL like 'report/tasks/export_excel' Viewset class TaskReportViewSet(generics.GenericAPIView): queryset = TiempoOperacion.objects.all() pagination_class = StandardResultsSetPagination serializer_class = TiempoOperacionSerializer def get(self, request): """ Some code for 'get' request ... """ @action(detail=False, methods=['GET']) def export_excel(self, request): sheet = excel.pe.Sheet([[1, 2],[3, 4]]) return excel.make_response(sheet, "csv") Urls urlpatterns = [ url(r'^', include(router.urls)), url(r'^report/tasks/', TaskReportViewSet.as_view()), ] -
Datetime print time without offset
I am currently trying to convert times from UTC and the problem that i am having is that the offsets seem to be backwards. As you can see when i convert the UTC to EST, it shows an offset of -4:56 yet when i print the time, it seems to add 4:56 as opposed to the way it should be. I would really like to be able to convert a UTC time to any other timezone and have it display the local time there without the offset so the UTC here would be converted to something along the lines of 2019-03-06 9:12 EST. >>> example.created datetime.datetime(2019, 3, 6, 14, 8, 49, 841881, tzinfo=<UTC>) >>> original_utc = example.created >>> original_utc datetime.datetime(2019, 3, 6, 14, 8, 49, 841881, tzinfo=<UTC>) >>> conv_est = original_utc.replace(tzinfo=pytz.timezone('US/Eastern')) >>> conv_est datetime.datetime(2019, 3, 6, 14, 8, 49, 841881, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>) >>> print(conv_est) 2019-03-06 14:08:49.841881-04:56 >>> print(conv_est.astimezone()) 2019-03-06 19:04:49.841881+00:00 -
Django Braintree if result.success
How do I create a view, that checks if the transaction is complete and then only proceeds to do its function else takes you back to index Can’t take from result.success as Django is unable to get it directly,throws an error saying not defined -
PyCharm | Problems with import package in django project
J have a directory with algorithm. In that directory I`m added directory with django project. So structure of project is: |--Django app |--Algorithm After in directory with django I'm import some packages from algorithm directory. When in terminal I'm run py manage.py runserver I get an error: "ModuleNotFoundError: No module named [module from directory Algorithm]" But I have no errors when importing. -
Optimize a squashed migration in Django
I have a newly created squashed Django migration that looks similar to this: add field "name" run sql "CREATE FUNCTION x" add field "age" remove field "name" run sql "DROP FUNCTION x" Since Django cannot fully optimize the code between the run sql blocks, this is expected. However, I know that the two SQL runs affects nothing relevant, so I can manually delete the run sql parts. Is there any way to tell Django to automatically optimize this squashed migration now before I deploy it to all applicable database instances? The idea is to have Django automatically generate something like simply: add field "age" -
CSRF token missing in Django form submission
I am trying to submit a form via ajax.My template is as follows:- <form method="POST" id="form1" class="SignUP signupform"> <div class="classheading">Sign-up</div> {% csrf_token %} <input type="text" name="user" placeholder="Username" class="sinput" required="true" /> <input type="text"name="email" placeholder="Email" class="sinput" required="true"/> <input type="password"name="password"placeholder="Password" class="sinput" required="true"/> <input type="password"placeholder="Re-enter Password" class="sinput" required="true"/> <button type="submit" class="subform">Sign Up</button> </form> while ajax view submitting this form is:- $(document).ready(function(){ $('#form1').submit(function(){ console.log('form is submitted'); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); var formdata={ 'username':$('input[name=user]').val(), 'email':$('input[name=email]').val(), 'password1':$('input[name=password]').val(), 'password2':$('input[name=password1]').val(), }; console.log("Formvalue is taken"); $.ajax({ type:'POST', url:'/Submit/signingup', data:formdata, dataType:'json', encode:true, headers:{ "X-CSRFToken": csrftoken }, }) .done(function(data){ console.log(data); }); event.preventDefault(); }); }); On backend, i'm submitting this form using Django.Corresponding View is as follows:- @csrf_protect def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse("Confirm your email.") else: return JsonResponse({'success': False,'errors': [(k, v[0]) for k, v in form.errors.items()]}) But it's showing 403 error.In command prompt, it's showing "CSRF_TOKEN missing or incorrect". What could be the possible error? -
django default context variable
I'm new to Django web dev, managed to setup a toy project following this tutorial. However I found the Django official documentation as well as this tutorial are quite confusing, hard for me to follow, especially the template context variables. For example, in xxapp/views.py we defined a few views as follows, from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from catalog.models import Author class AuthorCreate(CreateView): model = Author fields = '__all__' initial = {'date_of_death': '05/01/2018'} class AuthorUpdate(UpdateView): model = Author fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death'] class AuthorDelete(DeleteView): model = Author success_url = reverse_lazy('authors') Then in templates, we have this {% extends "base_generic.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} <!-- WHERE IS THIS "FORM" FROM? --> </table> <input type="submit" value="Submit"> </form> {% endblock %} I understand this template file, except for one thing, where is the form.as_table from, and what is it?? I'm aware that, if we use some built-in class views or models, we might have some context data for free, but where do I lookup them, I searched on Django but found nothing. -
Configuring django_python3_ldap with test server failures
I am having trouble using django_python3_ldap to connect to this test server: https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/ It wont recognize the username or password for any user and was wondering if anyone can see an error in my implementation AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django_python3_ldap.auth.LDAPBackend', ] LOGIN_URL = '/login' LOGOUT_REDIRECT_URL = '/logout' LDAP_AUTH_URL = "ldap://ldap.forumsys.com:389" LDAP_AUTH_SEARCH_BASE = 'dc=example,dc=com' LDAP_AUTH_USER_FIELDS = { "first_name": "givenName", "last_name": "sn", "email": "mail"} LDAP_AUTH_USER_LOOKUP_FIELDS = ("user",) LDAP_AUTH_CONNECTION_PASSWORD = "password" LDAP_AUTH_USE_TLS = False LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_openldap" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = 'ldap.forumsys.com' LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } INSTALLED_APPS = [ 'django_python3_ldap', 'kpi.apps.KpiConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] So this test server doesnt have a connection user name but a connection password it looks like. I know having the logging information would help, but i am unsure how to log the action in my views.py function below: class LoginView(TemplateView): template_name = 'KPI/login.html' def post(self, request): email = password = "" state = "" if request.POST: email = request.POST.get('email') password = request.POST.get('password') print(email, password) user = authenticate(username=request.POST.get('email'), password=request.POST.get('password')) if user is not None: login(request, user) … -
Single sign-on authentication on Django and Grafana
I'm using grafana iframes in my HTML page running in Django / python, but every time I open my page to view the embedded graphs I need to access grafana and thus login to authenticate my user, my Django application already has a login page, I would like to use only one login on my page and send a proxy request to grafana, so I do not need to perform two logins every time I open my application. View class GraphanaProxyView(ProxyView): upstream = 'http://172.30.3.141:3000/' def get_proxy_request_headers(self, request): headers = super(GraphanaProxyView, self).get_proxy_request_headers(request) headers['X-WEBAUTH-USER'] = request.user.username return headers Urls url(r'^grafana/(?P<path>.*)$', views.GraphanaProxyView.as_view(), name='graphana-dashboards'), Config Grafana grafana: image: grafana/grafana:latest container_name: grafana restart: always ports: - "3000:3000" volumes: - "./grafana/datastore:/var/lib/grafana" environment: - GF_SMTP_ENABLED=true - GF_SMTP_HOST=smtp.gmail.com:587 - GF_SMTP_USER=user@domain.com.br - GF_SMTP_PASSWORD=password - GF_SMTP_FROM_NAME=Grafana Snipped - GF_SMTP_SKIP_VERIFY=true - GF_AUTH_ANONYMOUS_ENABLED=true - GF_AUTH_ANONYMOUS_ORG_NAME=View - GF_AUTH_ANONYMOUS_ORG_ROLE=View - GF_USERS_ALLOW_SIGN_UP=false - GF_AUTH_PROXY_ENABLED=true - GF_AUTH_PROXY_HEADER_NAME = X-WEBAUTH-USER - GF_AUTH_PROXY_HEADER_PROPERTY=username - GF_AUTH_PROXY_AUTO_SIGN_UP=true - GF_AUTH_PROXY_LDAP_SYNC_TTL=60 - GF_AUTH_PROXY_WHITELIST = 172.30.3.207 - GF_SERVER_DOMAIN = 172.30.3.141 I'm getting this error when accessing URL: If you're seeing this Grafana has failed to load its application files This could be caused by your reverse proxy settings. If you host grafana under subpath make sure your grafana.ini root_path setting includes subpath If … -
Storing custom data types in Django
I have a custom class (and possibly more soon), that I would like to neatly store on some of my models in Django. The class roughly looks like so: class BBOX(object): def __init__(self, min_x, min_y, max_x, max_y, srs_code, **kwargs): self.min_x = min_x self.max_x = max_x self.min_y = min_y self.max_y = max_y self._srs_code = get_srs_code(srs_code) self._srs_identifier = 'EPSG:{}'.format(self.srs_code) self._srs = SRS(self.srs_code) The class has a great many properties and helper functions that we use for safe handling of bounding box objects in our geospatial based application. In code, we pass these around safely knowing they will be easy to use and interact nicely with the rest out our code. As a rule, we do not ever want to be working with a bounding box in our code that isn't represented by an instance of this class, except when we absolutely must pass a list or something similar (e.g. when we serialize the values to JSON, YAML, or something similar). Several of our Django models have BBOX related values. Currently, these disparate models all must manually define the fields they need in order to represent a BBOX. For convenience we added some helper properties to some of them to transform to our … -
running Domain, Site and the links
The html based menu comes with the {% show_menu ... %} tag and this is the only case where links working reliable (especially menu links in this case). When I try to manually put links onto a page in cms editor and I'd like them to be internal (pointing to other cms based pages), I am regularly stumbling over the automatically prefixed domain, which is coming from the SITE_ID in my prject settings and does not match with the running domain (the domain specified when doing runserver) which in most cases is localhost. The domain behind the SITE_ID = 1 is pointing to the future staging domain, which does not exist yet and anyway is out of scope during local development. What is the secret behind the {% show_menu ... %} mechanism compared to the manual created links during design time? I was trying to put links with the bootstrap4 plugin and the feature coming with the editor out of the box. None of them respect the running domain. But {% show_menu ... %} always work, regardless of the running domain and SITE_ID configuration. Btw. I wanted to try out putting a link from the djangocms-link plugin, but this anyhow … -
AJAX call fails with Django. No response or error message
Here's my code: $.get("register/email", function(data,status){ alert(data); }); and my views.py file from django.http import HttpResponse, Http404 from django.shortcuts import render def registerEmail(request): if request.is_ajax(): email = request.POST['email']; return HttpResponse(email) else: return HttpResponse('Game') and my urls.py urlpatterns = [ path('', homePageView, name='home'), path('register/email/', registerEmail, name='verifyEmail'), ] I get no alert message when executing the page. Plus, no error message in ajax or django. So i tried adding alert('hello') outside the ajax get function, inside $(document).ready, and i got a hello message as expected. So my js files are linked correctly in django. my js files are located in myproject/currentapp/static/currentapp/js. I am new to django, so please suggest me if i need to add more information before asking for a solution. -
How to reduce quantity of an item in main table when it is being used in another table - django
I am creating my model in Django and I have a many to many relationship between supplies and van kits. The idea is that an "item" can belong to many "van kits" and a "van kit" can have many " items. I created an intermediary model that will hold the relationship, but I am struggling to figure out a way to relate the quantity in the van kit table to the quantity in the main supplies table. For example, if I wanted to mark an item in the van kit as damaged and reduce the quantity of that supply in the van kit, I would also want to reduce the total count of that supply in the main "supplies" table until it has been replenished. I am thinking that maybe I'll have to create a function in my views file to carry out that logic, but I wanted to know if it could be implemented in my model design instead to minimize chances of error. Here's my code: class supplies(models.Model): class Meta: verbose_name_plural = "supplies" # limit the user to selecting a pre-set category choices = ( ('CREW-GEAR','CREW-GEAR'), ('CONSUMABLE','CONSUMABLE'), ('BACK-COUNTRY','BACK-COUNTRY') ) supplyName = models.CharField(max_length=30, blank=False) # if they go over … -
Token Authentication In Django Restframework Using Django-rest-auth
I'm using vue.js for the front end of my application which is made on Django-restframework. I am using django-rest-auth for social authentication via Google. On the front end, I am using the vue-google-oauth2 library. The two work fine. I send an auth code from the front end and the backend responds with a token key. However, when I use curl on my terminal with the key curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' I get the error: {"detail":"Authentication credentials were not provided."} With my terminal showing: [06/Mar/2019 15:38:54] "GET /newsfeed/ HTTP/1.1" 401 58 What is it that I am supposed to do to ensure that the cookies or whatever it is at the backend to maintain my session isn't lost? Similarly, when I login on the front end using the oauth2 library, I refresh my page and that too shows that I am no longer logged in. What exactly am I missing out on? -
Django - How to create a slug url that works?
I'm a newbie and I've been battling with an error while trying to display the detail page of a post. I've checked other answers relating to this question but the solutions still don't work for me. This is the error I'm getting: Reverse for 'blog_post' with no arguments not found. 1 pattern(s) tried: ['blog\\/post/(?P<slug>[-\\w]+)/$'] This is my model: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique_for_date='publish') author = models.ForeignKey('auth.User', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post', args=[str(self.slug)]) View functions: class BlogHomePageView(ListView): model = Post template_name = 'blog/index.html' class PostDetailView(DetailView): model = Post template_name = 'blog/post.html' slug_url_kwarg = 'slug' query_pk_and_slug = True Urlpatterns: path('', BlogHomePageView.as_view(), name='blog_home'), re_path(r'post/(?P<slug>[-\w]+)/$', PostDetailView.as_view(), name='blog_post'), Templates for the detail page and list page respectively: {% extends 'blog/base.html' %} {% block title %}Post{% endblock %} <!-- Page Header --> {% block page_header %} <div class="post-heading"> <h1>{{ post.title }}</h1> <h2 class="subheading">Problems look mighty small from 150 miles up</h2> <span class="meta">Posted by <a href="#">{{ post.author }}</a> on {{ post.publish }}</span> </div> {% endblock %} <!-- Post Content … -
What are different methods to scale django channels?
Do having multiple cores gives any advantage to django-server? Basically, what i am looking is do django internally uses multiple threads or multiple cores to scale horizontally on a machine? Do running multiple instances of django server on same machine helps? This is for the case when django is not utilising the cores on a machine. So, running multiple cores might help take advantage of those cores? I am also reading how to scale django server that is also using Redis as a communication layer. How do I scale it? I have been reading about it and it comes out that I need to cluster redis to maintain consistency between different django server instances on different machines, basically how to use same redis instance. Also, if there is any source where i can refer it(basically how to scale redis), that will be great. Also, what changes do i need to do in django settings.py file to get it working. -
DJANGO REST Framework - API call returns only 20 entities out of many more fetched
Django 1.1.3 , python 3.6, coreapi 2.3.3 I execute an API call to my website code from the client. listProducts = self.amyClient.getProducts() On the website side it executes queryset = Product.objects.all(), no filters. len(queryset) before return queryset gives me 52 entries. On the client side len(listProduct) is 20. I added couple of entries just to see what happens - in the API call the quantity of the returned entities changes (so it's not a "connecting to a wrong DB" issue), on the client side it's always 20. Casting queryset to list ( i.e . queryset = list(Product.Objects.all())) does not change anything, and I don't really expect it to, just because in the API call code it's correct already. Something must be truncating it on the receiving (client) side. What? Thanks. -
Djano. Pass file from one view acyion to another
I have a view with two actions. First one renders FileInput for csv. After submit, I read csv header and render the template for second action with dropdown containing header items. After dropdown items are selected and submitted, I want to read csv file, saving selected columns to db in second action. How can I pass file from one action to another? -
Django logged_out.html page problem that redirect administration pages
http://127.0.0.1:8000/accounts/login/ This page is created successfully and working nice: And Problem with these pages: http://127.0.0.1:8000/accounts/logout/ This page redirect me Django Administration Pages that message to login again but I don't want this. I have placed my HTML file in ..templates/registration/logged_out.html And checked spelling error multiple time to see why not working. My urls files: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('catalog.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and my logged_out.html is: {% extends 'base.html' %} {% block content %} <p>Logged out!</p> <a href="{% url 'login' %}">Click here to login again.</a> {% endblock %} Can any tell me what's wrong with it? How to fix this?