Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do I call specific function in views.py through ajax call in javascript file?
In Django we map URLs to functions in views.py. If we do an ajax call then we need to mention url in ajax call but that will call the function mapped to that url. I want to call specific function from views.py via ajax call? What should I do so that I can call any function in views.py via AJAX call without changing url? views.py def index(request): codes=Code.objects.all()[:10] context={ 'name': 'KD', 'codes': codes } return render(request,'coding/index.html',context) def details(request): code=Code.objects.get(1) context={ 'code': code } return render(request, 'coding/details.html', context) urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.index, name="index" ), path('details',views.details, name="details" ), ]; javascript <script type="text/javascript"> $(document).ready(function() { $("#tests").submit(function(event){ event.preventDefault(); $.ajax({ type:"POST", url:"/details/", // what changes should be done so that I can call other function in views.py? data: { 'video': $('#tests').val() }, success: function(){ $('#message').html("<h2>Code Submitted!</h2>") } }); return false; }); }); </script> -
Creating new model in Django with POST data from Python requests
I'm trying to take information from a POST request made from Python requests and add it to my model: def message(request): if request.method == 'POST': form = InputInfoForm(request.POST) #form models make validation easy if form.is_valid(): InputInfo.name = request.POST.get('name') InputInfo.conversation_id = request.POST.get('conversation_id') InputInfo.message_body = request.POST.get('message_body') return HttpResponse(status=200) return HttpResponse(status=200) Here's the request post_data = {'name': 'charles', 'conversation_id': '3', 'message_body': 'Ada Challenge'} r = requests.post('http://127.0.0.1:8000/message/', data=post_data) I'm not sure if I'm handling the requests right in the view -
Django Celery receiving and accepting tasks, but not executing them
I'm running a Django 1.11 server on Digital Ocean running Ubuntu 16.04, Gunicorn, Nginx, and am trying to set up Celery tasks using Redis. The service seems to work and receive periodic tasks fine when I do: celery -A config worker -B -l debug And the tasks are received and accepted, but they don't execute. To test, I'm sending this function: @shared_task(name="sum_two_numbers") def add(x, y, **kwargs): return x + y with: add.delay(1,3) And this is the complete printout of the console that Celery is running on: -------------- celery@myproject v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial 2018-02-19 23:18:12 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: myproject:0x7f2cd60dc9e8 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . . . . sum_two_numbers [2018-02-19 23:18:12,858: INFO/MainProcess] Connected to redis://127.0.0.1:6379// [2018-02-19 23:18:12,876: INFO/MainProcess] mingle: searching for neighbors [2018-02-19 23:18:13,910: INFO/MainProcess] mingle: all alone [2018-02-19 23:18:13,924: WARNING/MainProcess] /home/user/.virtualenvs/myproject/lib/python3.5/site-packages/celery/fixups/django.py:202: UserWarning: Using settings.DEBUG leads to a memory leak, never use … -
Django gives error "Select a Valid choice" . Django Version 1.11.5
My models.py is below: from django.db import models from extensions.models import SipExtension xmpp_users = SipExtension.objects.values_list('real_name',flat=True) xmpp_users_choices = [('', 'None')] + [(real_name,real_name) for real_name in xmpp_users] class xmpp_buddy_groups(models.Model): group_name = models.CharField(max_length=30) name = models.CharField(choices=xmpp_users_choices,max_length=100) def __str__(self): return '%s %s' % (self.group_name,self.name) my forms.py is below: from django import forms from .models import xmpp_buddy_groups from extensions.models import SipExtension class xmpp_buddy_groups_form(forms.ModelForm): xmpp_users = SipExtension.objects.values_list('real_name',flat=True) xmpp_users_choices = [('', 'None')] + [(real_name,real_name) for real_name in xmpp_users] name = forms.ChoiceField(xmpp_users_choices,required=True, widget=forms.SelectMultiple()) # name = forms.ModelChoiceField(widget=forms.CheckboxSelectMultiple,queryset=SipExtension.objects.values_list('real_name',flat=True),required=True) class Meta: model = xmpp_buddy_groups fields = ['group_name'] my views.py is below: from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from .forms import xmpp_buddy_groups_form @login_required def index(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = xmpp_buddy_groups_form(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: #return HttpResponseRedirect('/index.html') form.save() # if a GET (or any other method) we'll create a blank form else: form = xmpp_buddy_groups_form() print(form.errors) return render(request, 'xmpp/index.html', {'form': form}) My template index.html is below {% extends … -
unable to see my anything in database pycharm
I really am at a loss here. I am using Pycharm 5.0.4 and running a virtual env with Python3 and Django 2.0.1. I am trying to get my database up and running for my project, but no matter what I do I cannot seem to get anything to show up in the database tool window drop down in Pycharm. I have 'ENGINE': 'django.db.backends.sqlite3' set in my settings.py, and in Pycharm i am going to: Create New -> Data Source -> SQlite(Xerial). I then makemigrations and migrate but nothing shows up in the database. I can even go to the project website and succesfully add/create models in the admin site. But I cannot figure out where they are or see them... It was working at one point but I deleted my database because I was getting some errors and now I am trying to recreate it. -
Return specific wagtail setting for site
Just recently migrated domains to a single site but all settings are set per site. (navbar etc) Is tehre a way in wagtail to return a specific site's settings based upon the url? I tried monkey-patching the settings function in wagtail.contrib.settings.context_processors to return SettingsProxy(site) where site is the string of the appropriate site. But, this settings object contains nothing in the template. -
NOAUTH Authentication required - deploying with Heroku (Channel 2.0.2 - Django 2.0.2 - Heroku-Redis)
I am trying to run the multichat example of Channels 2.0.2 (Django 2.0.2) @ Heroku with heroku-redis. But I'm getting NOAUTH Authentication required (btw: I am able to run locally): 2018-02-20T02:16:34.648943+00:00 app[web.1]: 10.45.77.75:32339 - - [20/Feb/2018:02:16:34] "WSCONNECTING /chat/stream/" - - 2018-02-20T02:16:34.649549+00:00 app[web.1]: 2018-02-20 02:16:34,649 DEBUG Upgraded connection ['10.45.77.75', 32339] to WebSocket 2018-02-20T02:16:34.650407+00:00 app[web.1]: 2018-02-20 02:16:34,650 DEBUG Creating tcp connection to ('ec2-34-238-60-32.compute-1.amazonaws.com', 28169) 2018-02-20T02:16:34.659050+00:00 app[web.1]: 2018-02-20 02:16:34,658 DEBUG WebSocket ['10.45.77.75', 32339] open and established 2018-02-20T02:16:34.659217+00:00 app[web.1]: 10.45.77.75:32339 - - [20/Feb/2018:02:16:34] "WSCONNECT /chat/stream/" - - 2018-02-20T02:16:34.659974+00:00 app[web.1]: 2018-02-20 02:16:34,659 DEBUG WebSocket ['10.45.77.75', 32339] accepted by application 2018-02-20T02:16:34.666248+00:00 app[web.1]: 2018-02-20 02:16:34,666 DEBUG Closed 0 connection(s) 2018-02-20T02:16:35.085802+00:00 app[web.1]: 2018-02-20 02:16:35,085 ERROR Exception inside application: NOAUTH Authentication required. 2018-02-20T02:16:35.085814+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels/consumer.py", line 54, in __call__ 2018-02-20T02:16:35.085816+00:00 app[web.1]: await await_many_dispatch([receive, self.channel_receive], self.dispatch) 2018-02-20T02:16:35.085818+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels/utils.py", line 47, in await_many_dispatch 2018-02-20T02:16:35.085820+00:00 app[web.1]: result = task.result() 2018-02-20T02:16:35.085822+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 160, in receive 2018-02-20T02:16:35.085824+00:00 app[web.1]: return await self.receive_buffer_lpop(channel) 2018-02-20T02:16:35.085826+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 222, in receive_buffer_lpop 2018-02-20T02:16:35.085828+00:00 app[web.1]: task.result() 2018-02-20T02:16:35.085829+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 173, in receive_loop 2018-02-20T02:16:35.085831+00:00 app[web.1]: real_channel, message = await self.receive_single(channel) 2018-02-20T02:16:35.085833+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 189, in receive_single 2018-02-20T02:16:35.085835+00:00 app[web.1]: pool = await self.connection(index) 2018-02-20T02:16:35.085836+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/channels_redis/core.py", line 386, in … -
Angular 2 frontend django 2 REST framework backend user auth
I'm new to Django and JavaScript, so please forgive me if this is an obvious question. What is the best way to authenticate users? I can only find posts about using this which doesn't support django 2. Thanks for your help. -
Getting a 403 error involving CSRF when trying to connect to localhost (python requests)
I'm trying to test a connection to one of my Django views using Python's requests library. When I try to make a POST request on it I receive info when viewing request.text telling me the CSRF verification failed, and that I need a CSRF token when submitting forms. I've done some more research here and tried my best with this This is my code right now: post_request = requests.session() post_request.get('http://127.0.0.1:8000/message/') csrftoken = post_request.cookies['csrftoken'] headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'} final_request = post_request.post('http://127.0.0.1:8000/message/', headers=dict(Referer=post_request)) This is my view: def add_message(request): form = InputInfoForm(request.POST) if request.method == 'POST': return HttpResponse('hey') return HttpResponse('test') So how do I verify the CSRF token in the view using requests? -
AJAX call taking super long (2-4 secs)
I'm really stumped on an issue that I need to fix ASAP. On my website, whenever you pan the map, an ajax call is fired, doing a query in the database. The problem is, the ajax call takes somewhere between 2-10 seconds, which is unacceptable. Link to website There are about 500k records in my database. I notice that the more records I add, the slower it gets. That makes sense right, but why is it exceptionally slow and so inconsistent? I am using Digitalocean. When I check my control panel, the CPU/RAM/disk are all operating at very low levels. The AJAX call code: def filter_closed_listings(request): zoom = int(request.GET.get('zoomLevel')) minLat = request.GET.get('minLat') maxLat = request.GET.get('maxLat') minLng = request.GET.get('minLng') maxLng = request.GET.get('maxLng') sold = request.GET.get('sold') property_type = request.GET.get('pType') building_style = request.GET.get('bType') showActiveListings = request.GET.get('showActiveListings') showSoldListings = request.GET.get('showSoldListings') showEndedListings = request.GET.get('showEndedListings') bed = request.GET.get('bed') bath = request.GET.get('bath') low_price = request.GET.get('low') high_price = request.GET.get('high') includePandL = request.GET.get('includePandL') transaction_type = request.GET.get('transactionType') ended_time_difference = datetime.date.today() + datetime.timedelta(-int(sold)) # Date check print(ended_time_difference) # Initial filter with map bounds and date check data = Listing.objects.filter(la__gt=minLat).filter(la__lt=maxLat).filter(lo__gt=minLng).filter(lo__lt=maxLng) data = data.filter(transaction_type=transaction_type) # 0 is 'Any'. Therefore a filter is done if selection is not 'Any'. if not property_type == '0': … -
Django REST Framework setting to change the auto added 'Id' to 'djangoID'
I'm happy to let DRF add an 'ID' column to my model if no primary key is defined. Is there a way in settings to make this name more appropriate? eg 'ID' would actually be 'djangoID' -
Django queryset with prefetch or not?
I have such models class Category(models.Model): name = models.CharField() … class Product(models.Model): category = models.ForeignKey(Category, verbose_name=‘cat’) name = models.CharField() price = models.IntegerField() I need to create queryset which will select all products with price >= 100 grouped by categories. Afterwards I need to get count of products in each category. I did categories = Category.objects.filter(product__price__gte = 100) This queryset gave me all categories which contain product with price >= 100. But how can I get count of products in it and products themseves? Maybe I need to use a prefetch_related, but I don't know how. -
Django foreign keys are not saving properly
I have multiple foreign keys in the same model and for some reason, whenever I hit submit on the form, the last foreign key is overriding the previously entered ones. Can anyone see whats going on? models.py class Meal(models.Model): """ Three of these will be given to a study """ date = models.DateField(null=True, blank=True) start_time = models.TimeField(null=True, blank=True) stop_time = models.TimeField(null=True, blank=True) description = models.CharField(max_length=256, null=True, blank=True) class Meta: verbose_name_plural = 'Meals For Studies' def __str__(self): return "Meal Information for CRF # " + str(self.general_info.case_report_form_number) class MotionStudyInstance(models.Model): # ###############ADD MEAL INFORMATION####################### meal_one = models.ForeignKey(Meal, related_name='first_meal', on_delete=models.CASCADE, null=True, blank=True) meal_two = models.ForeignKey(Meal, related_name='second_meal', on_delete=models.CASCADE, null=True, blank=True) meal_three = models.ForeignKey(Meal, related_name='third_meal', on_delete=models.CASCADE, null=True, blank=True) class Meta: verbose_name_plural = 'Motion Studies Awaiting Validation' def __str__(self): return "CRF: #" + str(self.general_info.case_report_form_number) forms.py class MealForm(forms.ModelForm): class Meta: model = Meal views.py class MotionStudyInstanceFormView(LoginRequiredMixin, View): def post(self, request): if request.method == 'POST': form = MotionStudyInstanceForm(request.POST, request.FILES) meal_one_form = MealForm(request.POST) meal_two_form = MealForm(request.POST) meal_three_form = MealForm(request.POST) if meal_one_form.is_valid() and meal_two_form.is_valid() and meal_three_form.is_valid(): meal_one = meal_one_form.save() meal_two = meal_two_form.save() meal_three = meal_three_form.save() motion_study_instance_one = form.save(commit=False) motion_study_instance_one.meal_one = meal_one motion_study_instance_one.meal_two = meal_two motion_study_instance_one.meal_three = meal_three motion_study_instance_one.save() return redirect('data:motion-studies') else: form = MotionStudyInstanceForm() return render(request, self.template_name, {'form': form}) -
Django 1.9 No module named 'django.urls'
Trying to install pcapdb on a fresh debian install (requires django==1.9) installed via 'sudo pip3 install django==1.9' Other parts of django can be imported without issue e.g. django.conf, django.db, django.utils, etc. Output of 'pip3 list | grep -i django' Django (1.9) django-auth-ldap-ng (1.7.6) django-braces (1.12.0) django-celery (3.2.2) django-filebrowser (3.9.1) django-grappelli (2.10.2) django-hosts (3.0) django-url-tools (0.0.8) djangorestframework (3.7.7) djangorestframework-jwt (1.11.0) pip3 --version pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6) django version from interpreter import django print(django.get_version()) # 1.9 Ideas? -
Highlighting individual bootstrap column
I'm making a django website, where I have to change the color of text and make a box appear when hovering over their bootstrap column. The problem I'm having is trying to individually refer to the column to only highlight that column and not another. The code: $(document).ready(function(){ $('.col-sm-2').hover(function(){ if($(this).attr('id')==$('.col-sm-2').children('.box').children('img').attr('alt')) { $(this).children('.box').css('border', '1px solid #aeaeae'); $(this).children('.box').css('padding', '0px'); $(this).children('.carinf').children('a').css('color', '#012190'); } }, function(){ $('.box').css('border', '0px'); $('.box').css('padding', '1px'); $('.shoeinf').children('a').css('color', 'black'); }); }); .box { border-radius: 18px; font-size: 150%; padding: 1px; display: inline-block; box-sizing: border-box; height: auto; max-width: 100%; float: center; } .carinf { white-space: nowrap; text-align: center; text-overflow: string; max-width: 100%; position: relative; } .box:hover { padding: 0px; border: 1px solid #aeaeae; } img { position: relative; display: block; margin-left: auto; margin-right: auto; padding: 2%; } a { color: black; text-decoration: none; } a:hover { text-decoration: none; color: #012190; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div class="container"> {% for k in latest_kickz %} {% if forloop.first %}<div class="row">{% endif %} {% sub 'market/images/{0}/{1}/{2}.png' k.manufacturer|slugify k.model|slugify k.colour|slugify as sub1 %} <div class="col-sm-2" id="{{ k.colour }} , {{ k.model }} , {{ k.manufacturer }}"> <a href="{% url 'market:detail' k.id %}"> <div class="box" > <img src="{% static sub1 %}" alt="{{ … -
Bootstrap, nav-stacked not actually stacking list entries
it seems i'm missing something obvious here i expected the HOME BLOG CONTACT entries to be stacked on top of one another at all times. what am i missing? <body class="body" style="background-color:#f6f6f6"> <div class="container-fluid" style="min-height:95%; "> <hr> <div class="row"> <div class="col-sm-2"> <br> <br> <!-- Great, til you resize. --> <!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#fff">--> <div class="well bs-sidebar" id="sidebar" style="background-color:#fff"> <ul class="nav nav-pills nav-stacked"> <li role="presentation" class="active"><a href='/'>Home</a></li> <li role="presentation"><a href='/blog/'>Blog</a></li> <li role="presentation"><a href='/contact/'>Contact</a></li> </ul> </div> <!--well bs-sidebar affix--> </div> <!--col-sm-2--> <div class="col-sm-10"> <div class='container-fluid'> <br><br> {% block content %} {% endblock %} </div> </div> </div> </div> <footer> <div class="container-fluid" style='margin-left:15px'> <p><a href="#" target="blank">Contact</a> | <a href="#" target="blank">LinkedIn</a> | <a href="#" target="blank">Twitter</a> | <a href="#" target="blank">Google+</a></p> </div> </footer> </body> -
nodejs high modular project with django architecture
I want to start a big web application. this application need to respect this constraint: use NoSQL database Hight modularity easy to use i can't use django because is not officialy support NoSQL backend. But django offert a big modularity approach. Now i decided to use NodeJS for two reason: support NoSQL backend easy to use but i don't wont to start from scratch and i want to save django modularity advantages. I see express is most used but express is too simple. someone can recommend me how to build a hight modular project with express or a nodejs web framework that can use modular django architecture ? -
docker-compose cannot start service: "exec: \"python3\": executable file not found
(I'm not deeply experienced with docker, fwiw) I have a django appication I'm containerizing. Currently when I run docker-compose up the redis service starts up, but apiexits with error: ERROR: for api Cannot start service api: OCI runtime create failed: container_linux.go:296: starting container process caused "exec: \"python3\": executable file not found in $PATH": unknown #docker-compose.yaml version: '3' services: redis: image: redis ports: - 6379 api: build: context: ../backend/ dockerfile: ../backend/Dockerfile env_file: .env volumes: - ../backend:/code/ ports: - "8001:8001" depends_on: - redis with #../backend/Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code ADD . /code/ WORKDIR /code/ RUN pip install -r requirements.txt CMD python manage.py runserver and #./.env DJANGO_SETTINGS_MODULE=backend.settings.dev DJANGO_SECRET_KEY=<redacted> SENTRY_URL=<redacted> I've also, based on other issues, tried using both CMD and RUN with their differing argument types, i.e. in the existing shell and without, but the output hasn't changed. I should also acknowledge that it's possible I'm not restarting actually catching the updates to docker-compose.yaml or Dockerfile. My workflow has been $ docker-compose down followed by $ docker-compose up. -
In Django, how to display a date widget in the HTML form for a model DateField?
I am new to Django and looking to do something simple. I have a date database field and I am trying to get Django to display it as a 'date' widget in the HTML forms. Following is my code: models.py from django.db import models class DateF(models.Model): edate = models.DateField() forms.py from django.forms import ModelForm from django import forms from .models import DateF class DateForm(forms.ModelForm): class Meta: model = DateF fields = ['edate'] views.py from django.shortcuts import render from .forms import DateForm def index(request): if request.method == 'POST': pass else: form = DateForm() return render(request, 'datef/index.html',{'form':form}) Template file <!DOCTYPE html> <html> <head> <title>Date field test</title> </head> <body> <div style="width: 600px;margin: auto;"> <h2>Date field</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} </form> </div> </body> </html> The above displayed a text input field. I tried the following in my forms.py based on the following and still could not get it to work. https://stackoverflow.com/questions/660929/how-do-you-change-the-default-widget-for-all-django-date-fields-in-a-modelform from django.forms import ModelForm from django import forms from .models import DateF from django.forms import fields as formfields from django.contrib.admin import widgets class DateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(DateForm, self).__init__(*args, **kwargs) self.fields['edate'].widget = widgets.AdminDateWidget() class Meta: model = DateF fields = ['edate'] What am I missing? Do I need … -
django-oauth-toolkit 'invalid client' error after deploy on AWS Elasticbeanstalk
I use django-oauth-toolkit with my django/django-rest-framework application. When I request an access token in dev mode on localhost, it works OK: dev@devComp:$ curl -X POST -d "grant_type=password&username= <user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ {"access_token": "fFySxhVjOroIJkD0IuEXr5WIhwdXg6", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups", "refresh_token": "14vhyaCZbdLtu7sq8gTcFpm3ro9YxH"} But if I request an access token from absolutely the same application deployed at AWS Elasticbeanstalk, I get 'invalid client' error: dev@devComp:$ curl -X POST -d "grant_type=password&username= <user_name>&password=<password>" -u"<client_id>:<client_secret>" http://my-eb-prefix.us-west-1.elasticbeanstalk.com/o/token/ {"error": "invalid_client"} Please advise me what to do to get rid of this error and normally request access tokens from django app deployed at AWS. -
Weird behavior with external class in django
I've got a weird problem here. It hurts my brain thinking about it. I've got a Django project with multiple apps. Today I added another app. (views.py) from %app_name%.%class_file% import %class_name% def api(request): t = %class_name%() data = {} data['listOtherDevices'] = t.listOtherDevices logger = logging.getLogger(__name__) logger.error(len(t.listOtherDevices)) return JsonResponse(data) The imported class fills the 'listOtherDevices'-array via __init__ perfectly fine when I run it inside a console. When I do so, there are exactly 3 elements inside this array (as there are 3 devices in my LAN the class could find). So when I visit the url (development server -> manage.py runserver) linked to this method I can see a JSON with exactly 3 entries. So far so good but now comes the weird part. When I refresh the url in my browser or visit it one more time, there are more than 3 entries. The scheme is like this: opened url 1 time: 3 entries opened url 2 times: 9 entries (+ 6) opened url 3 times: 18 entries (+ 9) opened url 4 times: 30 entries (+ 12) opened url 5 times: 45 entries (+ 15) opened url 6 times: 63 entries (+ 18) I can see a pattern there … -
Django template: 2 for loops with same iterable seems to be interfering with each other
So I have 2 for loops in an HTML template, back to back that are both using the same iterable like so: {% for counter in iSM %} #some code here {% empty %} <p>There's a missing tab here.</p> {% endfor %} </div> {% for iteration in iSM %} #some code here {% endif %} {% empty %} <p>There's a missing context here.</p> {% endfor %} The issue I have with this is it seems that the counter doesn't reset. The first for loop will operate as normal, no problem. The second for loop will trigger the empty. Switching the order of these for loops will work for whatever loop is on top. How do I go around having both loops return all elements of the view the same? -
Is there any way to add through to M2M field with keeping the related manager's .add() working?
While Django doesn't completely support adding the through attribute to a M2M field (in order to add some extra fields), it can be migrated. The main issue is, Django will complain when any code tries to .add() models to the related set even if there are no required fields in the through model outside of the FKs of the linked models. So, I want to add a nullable field to the through model and still keep .add() and remove working like it was before (and implicitely using None as the nullable field value). Adding auto_created=True in the meta almost works, but it breaks migrations amongst other things. Is there any way to make it work outside of overriding the many2many descriptor (which isn't exactly included in the public API, though a lot of third-party Django packages use it)? -
Django Widget Tweaks help text as placeholder
Is there any way to render help text as placeholder in Django Widget Tweaks. New to django widget tweaks. -
how to implement django-crispy-forms tags in Jinja2
i recently switched from using django templates to using Jinja2. how can i be able to use the {% crispy %} tags with Jinja2 templates? I am not too proficient with programming in python yet