Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Daphne not listening to websockets
I have a webapp written with django-channels+celery that uses websockets for client-server communication. After testing it running daphne, the celery worker and redis on my host machine I decide to encapsulate everything with docker-compose to have a deployable system. This is where the problems started. I managed to have it working after learning, tweaking and debugging my docler-compose.yaml but still I can't get websockets to work again. If I open a websocket and send a command, wether from inside the javascript part of the app, or from the javascript console in chrome, it never triggers the ws_connect nor the ws_receive consumers. This is my setup: settings.py # channels settings REDIS_HOST = os.environ['REDIS_HOST'] REDIS_URL = "redis://{}:6379".format(REDIS_HOST) CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { # "hosts": [os.environ.get('REDIS_HOST', 'redis://localhost:6379')], "hosts": [REDIS_URL], }, "ROUTING": "TMWA.routing.channel_routing", }, } routing.py channel_routing = { 'websocket.connect': consumers.ws_connect, 'websocket.receive': consumers.ws_receive, 'websocket.disconnect': consumers.ws_disconnect, } consumers.py @channel_session def ws_connect(message): print "in ws_connect" print message['path'] prefix, label, sessionId = message['path'].strip('/').split('/') print prefix, label, sessionId message.channel_session['sessionId'] = sessionId message.reply_channel.send({"accept": True}) connMgr.AddNewConnection(sessionId, message.reply_channel) @channel_session def ws_receive(message): print "in ws_receive" jReq = message['text'] print jReq task = ltmon.getJSON.delay( jReq ) connMgr.UpdateConnection(message.channel_session['sessionId'], task.id) @channel_session def ws_disconnect(message): print "in ws_disconnect" connMgr.CloseConnection(message.channel_session['sessionId']) docker-compose.yaml version: '3' services: … -
Django. Listing files from a static folder
One seemingly basic thing that I'm having trouble with is rendering a simple list of static files (say the contents of a single repository directory on my server) as a list of links. Whether this is secure or not is another question, but suppose I want to do it... That's how my working directory looks like. And i want to list all the files fro analytics folder in my template, as links. I have tried accessing static files in view.py following some tutorial and having it like that: view.py from os import listdir from os.path import isfile, join from django.contrib.staticfiles.templatetags.staticfiles import static def AnalyticsView(request): mypath = static('/analytics') allfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] return render_to_response('Rachel/analytics.html', allfiles) And my template: <p>ALL FILES:</p> {% for file in allfiles %} {{ file }} <br> {% endfor %} And my settings.py PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] And i am getting the error: FileNotFoundError at /analytics/ [WinError 3] The system cannot find the path specified: '/analytics' Error traceback Any help will be very appreciated -
Django template is removing html table, regardless of using safe or autoescape
I am trying to pass a variable which has a html table into it as a HTML table in a Django template. when I pass it though and mark it as | safe or turn auto escape off. all the HTML is inserted but the table is fully removed, does anyone know why and how I can turn it off? import urllib.request from bs4 import BeautifulSoup tt_opener = urllib.request.build_opener() tt_opener.addheaders = [('User-Agent', 'Mozilla/5.0')] tt_service = tt_opener.open('https://managed.mytalktalkbusiness.co.uk/network-status/') tt_soup = BeautifulSoup(tt_service, "html.parser") tt_data = tt_soup.table template <div id="TALK-TALK-Service" style="width:50vw; height:50vw; float:left;"> {{ TalkTalk |kksafe }} </div> the tt_data variable printed via shell <table border="0" cellpadding="0" cellspacing="0" class="opaltable" width="100%"><th nowrap="nowrap"> </th><th nowrap="nowrap">Issue</th><th nowrap="nowrap">Services affected</th><th nowrap="nowrap">Location</th><th nowrap="nowrap">Last update</th><tr><td width="20"><img src="https://managed.mytalktalkbusiness.co.uk/images/redlight.gif"/></td><td width="350"><a href="https://managed.mytalktalkbusiness.co.uk/network-status-report.php?reportid=15462">incident 10574541 - Washington Exchange - no service</a></td><td>Extranet, Ethernet, EoFTTC &amp; EFM via TalkTalk, DSL via TalkTalk</td><td width="100">n/a</td><td nowrap="nowrap" width="150">11th Oct 2017 12:53</td></tr><tr><td width="20"><img src="https://managed.mytalktalkbusiness.co.uk/images/redlight.gif"/></td><td width="350"><a href="https://managed.mytalktalkbusiness.co.uk/network-status-report.php?reportid=15448">Incident 10573277 - Network – P1 – Some TTB customers are experiencing Post Dial Delay SIP/VOE</a></td><td>SIP/VOE</td><td width="100">n/a</td><td nowrap="nowrap" width="150">11th Oct 2017 12:27</td></tr></table> the html displayed on the webpage <div id="TALK-TALK-Service" style="width:50vw; height:50vw; float:left;"> [&nbsp;, Issue, Services affected, Location, Last update, <img src="https://managed.mytalktalkbusiness.co.uk/images/redlight.gif"><a href="https://managed.mytalktalkbusiness.co.uk/network-status-report.php?reportid=15462">incident 10574541 - Washington Exchange - no service</a>Extranet, Ethernet, EoFTTC &amp; EFM via TalkTalk, DSL … -
How to add new form to django formset and not lose user input from previous forms
If user adds another form to formset, but has already typed something in first form, then the input will be lost, as new form was created. User now has 2 empty forms. Is there a way to add new form to formset but not lose user input? forms.py class Form(forms.Form): client = forms.CharField(label='Client', required=False) end_client = forms.CharField(label='End client', required=False) product = AutoCompleteSelectField(lookup_class=ProductLookup, label='Model', required=False) views.py def get(self, request): request.session['form_count'] = 1 FormSet = formset_factory(Form) formset = FormSet() return render(request, self.template_name, {'formset': formset} ) def post(self, request): if "add-form" in request.POST: form_count = request.session['form_count'] print("There are " + str(form_count) + " forms") form_count = form_count + 1 request.session['form_count'] = form_count print("Form count increased by 1, form count is: " + str(form_count)) FormSet = formset_factory(Form, extra=int(form_count)) formset = FormSet() **<-- if I put request.POST in here, new form will not be created** return render(request, self.template_name, {'formset': formset}) html file <div class="content"> <form method="post"> {% csrf_token %} {{ formset.management_form }} <div class="form-group"> {% for form in formset.forms %} <table class='no_error'> {{ form.as_table }} </table> <br> <br> {% endfor %} </div> <input class="btn btn-primary" type="submit" value="Submit order" /> <input name="add-form" class="btn btn-primary" type="submit" value="Add new product" /> </form> </div> -
Django field lookups day not wok
The model: class A(models.Model): ... stop_date = models.DateTimeField() start_date = models.DateTimeField() ... when i use field lookups day , the result is not my expect: a_list = A.objects.filter(stop_date__day=10) the a_list is a empty queryset. But the database has some records which the day of stop_date is 10. In settings.py, USE_TZ = True TIME_ZONE = 'UTC' Is there something wrong with the time zone setting? Expect your help. -
django test: fixtures not loading with selenium
My fixtures are correctly loaded by TestCase test: like in: class Test_test_fixture(TestCase): fixtures = ['lwt/fixtures/myfix.json'] def setUp(self): super(Test_test_fixture, self).setUpClass() print(User.objects.all()) .. But doing the same thing with Selenium is printing an empty query: class Selenium_fixtures(StaticLiveServerTestCase): fixtures = ['lwt/fixtures/myfix.json'] @classmethod def setUpClass(cls): super(Selenium_fixtures, self).setUpClass() print(User.objects.all()) ... What am I missing? -
why template inheritance when include is more intuitive?
I am new to programming, so I'm sorry if this seems trivial and stupid. Why template inheritance when include seems more intuitive? And seem to do the job? -
Django Multiple Generic Foreign Keys - How to Structure DRF Serializer
I have read the documentation about Content Type for Django, but I cannot seem to correctly think of a way to apply it to my situation. The common 'Tag' example is a little too simplistic. My situation: I have a Model called Docket. It has several fields which hold various simplistic values. However, it also needs to have a destination and a source. In my app, destinations and sources can both be either a Facility Object or a TransFrontier Object. So for example, you could have a Docket which has a Facility as it's source and a TransFrontier as its destination. You could also have a Docket with a TransFrontier as its source and a Faclity as its destination. Additionally, users will not be creating new Facility or TransFrontier objects when they create a new docket. These will existing Facility or TF objects we already have in the database. So to do this I initially thought of ContentType and Generic Foreign Key. I came up with this model: class Docket(BaseDocket): # Fields dest_id = models.PositiveIntegerField() destination = GenericForeignKey("dest_c_type", "dest_id") source_id = models.PositiveIntegerField() source = GenericForeignKey("source_c_type", "source_id") # limit dest & source to facility and transfrontier limit = models.Q(app_label='facilities', model='facility') | … -
django form.is_valid() only works in debug
I have a CreateView subclass with the following method: def post(self,request, *args, **kwargs): form = self.get_form(self.get_form_class()) formset = StepFormSet(self.request.POST) if formset.is_valid() and form.is_valid(): return self.form_valid(form.cleaned_data, formset.cleaned_data) else: return self.form_invalid(form, formset) Two of the fields in every form in formset are TimeFields. Now, if I type an obviously wrong time format (e.g. 09, or ddd), formset.is_valid()==True no matter what. It only returns false if I debug it within PyCharm Professional, placing a breakpoint at the first line of the method. I can't really understand what differs in the debug... -
Django Bootstarp/Materialize
{% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> </head> <body> <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel"> <div id="Carousel" class="carousel slide"> <ol class="carousel-indicators"> <li data-target="Carousel" data-slide-to="0" class="active"></li> <li data-target="Carousel" data-slide-to="1"></li> <li data-target="Carousel" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="item active"> <img src="img/Carousel/001.jpg"> </div> <div class="item"> <img src="img/Carousel/002.jpg"> </div> <div class="item"> <img src="img/Carousel/003.jpg"> </div> </div> <a class="left carousel-control" href="#Carousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#Carousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> </body> </html> My bootstrap doesn't work for carousels neither does for Materialize. What could be the problem? Is the Javascript causing problem or what is it? I'm getting broken carousels. Ignore the images in the code. -
how can we can make Array of Array in python
I am getting data in python like this N/A,0E-11,0E-11,0E-11,@,N/A,0.0,0.0,0E-11,@ 1 line contain data for 1 array like N/A,0E-11,0E-11,0E-11, this is array of 4 variables N/A , 0E-11 , 0E-11 , 0E-11 . And I have separated both by @ I get all variables in loop like this results += cursor.fetchone() //getting full line results+='@' // giving @ after 1 array of data for r in results: //iterating all variables results_data.append(r) results_data.append(',') print results Now I want to make a array of array like this array3= [[1 2 3], [4 5 6] [7 8 9], [10 11 12]] like after @ new array and , a new attribute. -
How to make a custom database function in Django
Prologue: This is a question arising often in SO: Equivalent of PostGIS ST_MakeValid in Django GEOS Geodjango: How to Buffer From Point Get random point from django PolygonField Django custom for complex Func (sql function) and can be applied on the above as well as in the following: Django F expression on datetime objects I wanted to compose an example on SO Documentation but since it got shut down on August 8, 2017, I will follow the suggestion of this widely upvoted and discussed meta answer and write my example as a self-answered post. Of course, I would be more than happy to see any different approach as well!! Question: Django/GeoDjango has some database functions like Lower() or MakeValid() which can be used like this: Author.objects.create(name='Margaret Smith') author = Author.objects.annotate(name_lower=Lower('name')).get() print(author.name_lower) Is there any way to use and/or create my own custom database function based on existing database functions like: Position() (MySQL) TRIM() (SQLite) ST_MakePoint() (PostgreSQL with PostGIS) How can I apply/use those functions in Django/GeoDjango ORM? -
Stripe Connect Callback and Python Django
def stripe_callback(request): client_secret = STRIPE_API_KEY # the temporary code returned from stripe code = request.GET.get('code', '') # identify what we are going to ask for from stripe data = { 'grant_type': 'authorization_code', 'client_secret': clientsecret, 'client_id': clientid, 'code': code } print(data) # Get the access_token using the code provided url = 'https://connect.stripe.com/oauth/token' r = requests.post(url, params=data) # process the returned json object from stripe stripe_id = r.json().get('stripe_user_id') print(stripe_id) I'm signing up my users and in their landing page I present a stripe connect but everything is working after following stripe doc and i get the response json with all the required info as follows: { "access_token": "sk_test_dQQmmR8797495973tAuO66iZP5V", "livemode": false, "refresh_token": "rt_BYhJGFxQlhgfiub4fbu4un3mn3FdAKiQ9XFgmkxI2cq", "token_type": "bearer", "stripe_publishable_key": "pk_test_UNvjubd4b4dini4ioTQNo4", "stripe_user_id": "acct_19qf4r7tg974fh8f40Za", "scope": "read_write" } What I've not been able to do is save the stripe_user_id againt my website user. Any input on this from you guys would be great. -
Why does uploading images to S3 with JS+Django always yield a 400-error?
I've tried with code from several tutorials that teach me how to upload images to S3 using XHR's. The Ajax-call to get the signature from my webserver goes fine, but when I try to upload the form + image to AWS I always get that 400-error with no further details. Could anyone please help me diagnose this issue? I'm using a Chrome browser. Let me know if you need further details. Backend code (in views.py): def sign_s3(request): S3_BUCKET = 'my-bucket' folder_name = request.GET.get('folder_name', '') file_name = request.GET.get('file_name', '') file_type = request.GET.get('file_type', '') upload_start_path = "static/img/{}".format(folder_name) filename_final = "{}.{}".format(file_name, file_type) policy_expires = int(time.time()+5000) policy_document_context = { "expire": policy_expires, "bucket_name": S3_BUCKET, "key_name": "", "acl_name": "public-read", "content_name": "", "content_length": 524288000, "upload_start_path": upload_start_path } policy_document = """ {"expiration": "2019-01-01T00:00:00Z", "conditions": [ {"bucket": "%(bucket_name)s"}, ["starts-with", "$key", "%(upload_start_path)s"], {"acl": "%(acl_name)s"}, ["starts-with", "$Content-Type", "%(content_name)s"], ["starts-with", "$filename", ""], ["content-length-range", 0, %(content_length)d] ] } """ % policy_document_context aws_secret = str.encode(os.environ.get('AWS_SECRET_ACCESS_KEY')) policy_document_str_encoded = str.encode(policy_document.replace(" ", "")) url = 'https://{bucket}.s3.{region}.amazonaws.com/'.format( bucket=S3_BUCKET, region='eu-central-1' ) policy = base64.b64encode(policy_document_str_encoded) signature = base64.b64encode(hmac.new(aws_secret, policy, hashlib.sha1).digest()) data = { "policy": bytes.decode(policy), "signature": bytes.decode(signature), "key": os.environ.get('AWS_ACCESS_KEY_ID'), "file_bucket_path": upload_start_path, "file_id": 1, "filename": filename_final, "url": url, } return JsonResponse(data) Frontend code: var fileItemList = []; document.getElementById("button").onclick = function(){ var … -
TLS1.2 not supported with my python/django site
I'm hoping someone might be able to help me. I have a client that has a website running Python 2.7.5+ (according to python -V). It's an ecommerce site that also uses the eWay payment gateway. They recently made some changes to only support TLS1.2 https://www.eway.com.au/tls-updates. However, when a customer goes through the checkout it shows a denied message from the eWay payment gateway. eWay say that this is because the transaction is still not coming through as TLS1.2. I have upgraded the Amazon EC2 instance and modified the apache .conf file so that it only supports TLS1.2 and i have verified this by checking the site through an SSL test with https://www.ssllabs.com/ssltest/. Therefore, I believe the issue may be due to the pyOpenSSL package being on a version that doesn't support TLS1.2. It's apparently on version 0.13: pyOpenSSL==0.13. I was wondering if someone might be able to help confirm or disprove my theory (I know this may be difficult with not having access to the server) and perhaps provide some pointers. I have tried upgrading pyOpenSSL using the command pip install –upgrade pyopenssl==0.15.1 but I got the following error; Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip-1.5.2-py2.7.egg/pip/basecommand.py", line 122, in … -
Django: Custom Profile Picture To New User
In Registration form before saving the User I wants to give the Profile picture of First user to every new user until they change it. This is what I tried, def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): new_form = form.save(commit=False) new_form.user.userprofile.profile = UserProfile.objects.profile(id=1) new_form.save() This code is showing me the error "'Manager' object has no attribute 'profile'". How can I do that ? -
How to use an es6 file with django?
I would like to implement this answer: https://stackoverflow.com/a/31669706 but I dont have an idea how to integrate it with Django. Would appreciate any guidance. Thank you. -
Get the selected radio button in django template
In my template I have for loop. As you can see the id for each radiobutton is reprsented by {{stud.id}} . {{stud.nameAndSurname}} shows the name and the surname of the student(in browser I can see name and surname of the corresponding student). <form method="POST" class="post-form"> {% csrf_token %} {% for stud in students %} <input type="radio" id={{ stud.id }} name="student">{{ stud.nameAndSurname }} {% endfor %} <button type="submit" class="save btn btn-default">GO!</button> </form> In my view.py I have: class MyClass(View): def get(...): ... def post(self,request, pk): myVar = request.POST.get("student") return HttpResponse(myVar) If I click submit button i want to go to another page that shows me name and surname of the selected student. Now the issue is that instead of the student's name and surname it's showing me simply written "on" -
How to insert multiple images into a blog post not File field upload (Django blog)
I am a semi-noob to Django web development. I've managed to add a File field that actually allows me to upload an image into the post (The image is displayed in post-list and post-detail) but what if I wanted to add several images in a post? I am currently writing a tutorial post and would like to insert images under each instruction for the benefit of the user. I don't want the tutorials to be purely text, how do I go about doing this? Below is my models.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from django.utils import timezone #from taggit.managers import TaggableManager class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.FileField(null=True, blank=True) #tags = TaggableManager() def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def approved_comments(self): return self.comments.filter(approved_comment=True) class Meta: ordering = ["-pk"] class Comment(models.Model): post = models.ForeignKey('blog.Post', related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def approved_comments(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.text And here's my forms.py from django import forms from .models import Post, Comment class PostForm(forms.ModelForm): class … -
How do you store general site settings in the database with django?
I am trying to decide whether I should use the settings file or store settings in the database so that other tools that hook into the database can be used. At its most basic the model will be called Setting from django.db import models class Setting(models.Model): name = models.Charfield(max_length=255, blank=False) value = models.Charfield(max_length=255) So no datatype nothing just text, which is pretty much how it is in the config file. Then getting a setting is just a matter of: my_setting = Setting.objects.get(name='my_setting') Would this way be suitable? -
Django, having Q object filter by function in model
Inside my Profile model I have the following function: It serves to return the fullname of the user (or a alternative if some data is missing). def full_name(self): first_name = self.user.first_name.strip() if first_name and self.user.last_name: if not self.middle_name: full_name = u'%s %s' % (first_name, self.user.last_name) else: full_name = u'%s %s %s' % (first_name, self.middle_name, self.user.last_name) return full_name.strip() elif first_name: return first_name return self.user.username Now for my question: I have a view where I filter a queryset based on the variable 'q' (that is returned from a searchbox in the template) Like so: qs = qs.filter(tenant_demo_purchase=True).order_by('-id') #Search users within results q = self.request.GET.get('q', None) if q: qs = qs.filter(Q(user__username__icontains=q) | Q(user__first_name__icontains=q) Q(user__last_name__icontains=q) | Q(arrangement_period__arrangement__title__icontains=q) | ).filter(tenant_demo_purchase=True).order_by('-id') else: pass return qs This filter works fine if I give it a firstname, username, or a last name. But if I give it a firstname + lastname (example: "John Doe") it returns no results. Most of my users tend to submit the fullname, so as a solution I tried to have it acces the Profile.full_name function. By adding the following line Q(user__profile__fullname__icontains=q) However, this crashes with the following error message: raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0])) FieldError: Related Field got invalid lookup: fullname … -
ImportError: No module named allauth. Django
in a project with django, when I do "python manage.py runserver" I get this error traceback : Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python27\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named allauth I installed allauth using pip3 install allauth. And this is my INSTALLED_APPS : INSTALLED_APPS = [ 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] -
Limiting QuerySets in Django is not working
I just get no answer what is not working from Django. Django says everything is okay. I want to limit the results I get from my database. In the documentation is said that the first parameter is the offset and the second how much results I get beginning with the offset + 1. What I am doing wrong here ? When I do not limit the queries everything works fine. So the mistake should be by using the limitation. views.py def ajax_more(request): categoryid = request.GET.get('categoryid', None) query = request.GET.get('query', None) offset = request.GET.get('offset', None) if query: if categoryid == "6": advertisements = Advertisement.objects.filter(title__contains=query)[int(offset): 2] else: advertisements = Advertisement.objects.filter(category__id=categoryid, title__contains=query)[int(offset): 2] else: if categoryid == "6": advertisements = Advertisement.objects.all()[int(offset): 2] else: advertisements = Advertisement.objects.filter(category__id=categoryid)[int(offset): 2] advertisements_list = [] for advertisement in advertisements: advertisements_list.append({ 'id': advertisement.id, 'description': advertisement.description, 'title': advertisement.title, 'picture_url': advertisement.image.url, 'date': advertisement.date }) data = { 'advertisements_list': advertisements_list } return JsonResponse(data) -
Django self.cleaned_data.get("field") is None when field value is 0 : why?
I have a field : models.py class MyClass(models.Model) : myfield = models.FloatField(blank=True, null=True) and a form validation that handles conditionals controls on multiple fields and must raise an error if self.cleaned_data.get("myfield") is None. My problem is : I want to accept the value "0" as correct. but when a user inputs 0 for the field myfield, the self.cleaned_data.get("myfield") is None : Why ? and the form validation raises an error. -
How to iterate for loop with range using django template
I WANT TO USE i inside the loop means {{ posts.0.title|capfirst }} {{ posts.i.title|capfirst }} value of i is 0 to 12 but its not working with {{ posts.i.title|capfirst }} {% for i in TotalCountRange %} <tr class="even pointer"> <td class="a-center "> <input type="checkbox" class="flat" name="table_records"> </td> <td class=" "><a href="{{ post.get_absolute_url }}">{{ posts.0.title|capfirst }}</a></td> <td class=" ">{{ post.pub_date|date:"d M y h:i a" }} </td> <td class=" "><a href="{{ post.category.get_absolute_url }}">{{ post.catname }} <i class="success fa fa-long-arrow-up"></i></a></td> <td class=" ">{{ post.username }}</td> <td class=" "> <!--{% for tag in post.tags.all %}--> <!--{% with b=',' %}--> <!--{% if forloop.counter >= 2 %}--> <!--<a href="{{ tag.get_absolute_url }}">{{b}}{{ tag }}</a>--> <!--{% else %}--> <!--<a href="{{ tag.get_absolute_url }}">{{ tag }}</a>--> <!--{% endif %}--> <!--{%endwith%}--> <!--{% empty %}--> <!--<a href="">None</a>--> <!--{% endfor %}--> </td> <td class=" "><a href="#">Edit</a></td> </tr> {% endfor %}