Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
credentials authorisation in Ldap using Django
I am trying to build an application using Django. For authorisation we have central authorisation server i.e LDAP. I am trying to use JWT for all the api authentication. but my question is, who to encrypt a password for first time authorisation when user name and password is sent to ldap server -
to retrieve the names of players in django
class is player to retrieve the names of all the players in house name models: class player(models.Model): """ Model representing a book genre (e.g. Science Fiction, Non Fiction). """ name = models.CharField(max_length=100, help_text="Enter a players name") Id = models.CharField(primary_key=True,max_length=100, help_text="Enter a players Id") Num_matches = models.IntegerField() Num_baskets = models.IntegerField() house_name = models.ForeignKey('House_name',on_delete=models.SET_NULL, null=True) def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.Id views def shivalik(request): set1 = player.objects.filter(house_name__hou_name='shivalik') return render(request,'shivalik.html', context={'set1':set1 } ) html file {% block content %} <h2>{{set1}}</h2> {% end block %} In shivalik.html it is not printing the names of player it is printing the query. I tried to keep set1.name in views but it showing no attribute name in set Please help me to show the list of all player names in house_name: shivalik -
How to implement stylesheet and images using Django?
I've been trying to make a webpage using Django (python), CSS and HTML. I set up the 'core' of the site and I am now trying to make the site good looking using html and css. The problem is: when I want to use an image or stylesheet stored in my app directory using <... href='.../image.jpeg', it just does not find it. No matter where I place it. Whereas it does load an image webadress. Does it have something to do with the settings of my app? So the way Django looks for this particular file? Maybe someone could explain how and where exactly to store file so Djano can find it. Kind regards, -
The secondary linkgae in my webpage cannot display the options in Django 1.10
I use smart_selects to realize secondary linkage in Django admin page.Succeed!When I choose one university,only the colleges those belong to the university can be chosen. But,when it comes to the form in webpage,the second level form cannot display any option.This is the wrong webpage:enter image description here Here is the codes. models.py class StudentModel(models.Model): GENDER_CHOICES = (('M','男'),('F','女'),) name = models.CharField(verbose_name='姓名',max_length=20) gender = models.CharField(blank = True,max_length=4,choices = GENDER_CHOICES,verbose_name='性别') date_of_birth = models.DateField(verbose_name='出生日期',blank=True,null=True) age = models.IntegerField(verbose_name='年龄',default=0) highschool = models.ForeignKey(SeniorHighSchoolModel,verbose_name='高中名称') university = models.ForeignKey(UniversityModel,verbose_name='大学名称') college = ChainedForeignKey(CollegeModel,chained_field='university',chained_model_field='university',show_all=False,blank=True,null=True,verbose_name='学院名称') def __str__(self): return self.name forms.py from django import forms from .models import StudentModel class LoggingForm(forms.ModelForm): class Meta: model = StudentModel fields=['name','gender','date_of_birth','age','highschool','university','college'] logging.html <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type='submit' /> Thanks for yours answers in advance! -
Django Signals And Delay
I have a model 'Tasker' that has fields including 'start_date', 'end_date', 'time_diff' Class Tasker(models.Model): user=models.ForeignKey(User) start_date=models.DateTimeField() end_date=models.DateTimeField() #for this I added 5hrs to it with timedelta and override the saved function. time_diff= models.TimeField() #the time diff between start_date and end_date field is saved here. I want to do this, For each task created by a user, after 5hrs, check if the user has completed the task. If the task has not been completed, then mark it as incomplete and do other things. I'm confused on the scope on how to go about this. But I believe creating a signal will help. The question now is, since Signals work immediately after an action is triggered, how do I go about making it work by delaying it for 5hrs before checking if the task has been completed by the user. Do I need a worker like celery? -
Django - Loading dynamic Templates
I would like to update information refer to the loading files in Django. First of all, it's pretty clear to load static files. So in my case, we have simple website, where one of the script generate dymamic content. Which might be changed. That dynamic content, it's - List of folders, - With single HTML file - And JPG Images. And main tasks here - it's loading that HTML files, including images. That generated content, i can put in any folder (and can change any content). And in my example, I putted into templates folder, and load like snippet below, but where all images are missing. So I need to put that HTML to TEMPLATES, to load files, and separete images to STATIC, to load them. So I think, something wrong here, and was is the correct way for such issue. <div class="container"> {% include "stories/Princess_Run_Story/Princess_Run_Story.html" %} </div> -
Getting url with # in django
I'm trying to do a redirect for a url /accounts/social/connections/# url(r'^/accounts/social/connections/$', redirect_account_connection), Django patterns fails to catch it, tried also with # and * included both fail and is instead renders from django allauth. -
Where to store model-related non-logical repetitive code in Djangо?
I'm looking for a proper way to manage repetitive model-related code in Django that doesn't refer to the model logic. Example: class Comments(models.model): ### model stuff ### Threaded comments rendering is an expensive operation, so I want to store them into the cache as HTML. Repetitive code that we have to deal with: def get_comments_html(target_object): ## check cache ## is there is no cached copy, then build HTML and store to the cache I think that Comments model caching logic doesn't relate to the Comments itself and should be placed anywhere else. Ways to solve the problem: Here are three approaches I see to solve this problem: Store ALL such functionality into model consumer class: class ModelConsumer(object): # here we can place repetitive code for all models (of just pass) class CommentsConsumer(ModelConsumer): model = Comments def get_comments_html(target_object): pass Store such logic independently as plain functions in comment_app/utils.py Create independent class for each problem (f.e. CommentCacheManager and so on) What is the best solution for this problem that will not result in product limitations in the future? -
Compare datetime field with date in djano orm
Code : start_date = '2017-02-03' OutputData = Entity.objects.filter(created_on__year=start_date.year, created_on__month=start_date.month,created_on__day=start_date.day).count() I have data on that date but still I get 0 count in output and I am not getting why. Please tell me where I am doing wrong. Thank you very much for help!!!!! -
Ordering a queryset by score in a many-to-many relationship of another model
I have models setup as follows, each lesson belongs to a chapter and has a owner. For each chapter, the user has a score which is stored in the UserChapterScore table from django.db import models class User(models.Model): name = models.TextField() class Chapter(models.Model): name = models.TextField() class Lesson(models.Model): chapter = models.ForeignKey(Chapter) owner = models.ForeignKey(User) name = models.TextField() class UserChapterScore(models.Model): chapter = models.ForeignKey(Chapter) user = models.ForeignKey(User) score = models.IntegerField(default=0) How can I retrieve lessons belonging to a chapter, ordered by the owner's chapter score? -
Can we call Ajax in Django Form in onchange function?
Actually there is no html code in case of Django Form. dirrectly html selectbox/textbox happening through Django Model, with help of verbose_name and help_text class Activity(models.Model): act_des_code = models.ForeignKey('Destionation', related_name='act_des_code',db_column='act_des_code') act_cit_keyname = models.CharField(max_length=30) act_discription = models.TextField(max_length=255,verbose_name='Description') class ActivityForm(ModelForm): class Meta: model = Activity fields = ['act_des_code', 'act_cit_keyname','act_discription'] widgets={'act_discription': Textarea(attrs={'cols': 80, 'rows': 5})} act_des_code and act_cit_keyname are two selectbox. Note: No HTML code, All thing happening through Django Form. in front end Onchange of act_des_code(dropDown) i want to display Destionation class column value in act_cit_keyname(dropDown). Ex: Onchange of country all city should come in city dropDown. Your valuable comment will help me alot. -
AssertionError at /accounts/tcresults
I got an error, AssertionError at /accounts/tcresults No exception message supplied . I wrote in tc.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Score</title> </head> <body> <h1>Score</h1> <h2>Your Score is {{ tcresults.tc }} {{ value1 = tcresults.tc if value1 > 5000: <h2>Good</h2> elseif value1 < 900: <h2>Bad</h2> }} </h2> </body> </html> in views.py def tc(request): tcresults = ImageAndUser.objects.filter(user=request.user).order_by('id').last() d = { 'tcresults': tcresults, } return render(request, 'registration/accounts/tc.html', d) I cannot understand why this error happen. What should I do to fix this? -
How to retrieve specific attributes in models in django
We need to retrieve names of all the players of a specific house name in django models.py: class player(models.Model): """ Model representing a book genre (e.g. Science Fiction, Non Fiction). """ name = models.CharField(max_length=100, help_text="Enter a players name") Id = models.CharField(primary_key=True,max_length=100, help_text="Enter a players Id") Num_matches = models.IntegerField() Num_baskets = models.IntegerField() house_name = models.ForeignKey('House_name',on_delete=models.SET_NULL, null=True) views.py: def shivalik(request): queryset = player.objects.all().filter(house_name='shivalik' ) return render(request,'shivalik.html',{'queryset': queryset}) shivalik.html: {% extends "basic.html" %} {% block content %} <h2><li>{{queryset.name}}</li></h2> {% endblock %} error: ValueError at /bb/shivalik/ invalid literal for int() with base 10: 'shivalik' Request Method: GET Request URL: http://127.0.0.1:8000/bb/shivalik/ Django Version: 1.10.5 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'shivalik' -
django - looking for a library to create ajax progress bars etc
In my project, I have some database-heavy operations that users need to be able to do, like duplicating huge chunks of objects etc, so these have to be set up as background tasks. I am planning on using long-polling + Celery for this. And I can set this up from scratch, as I have done before, but it occured to me that there might be some kind of library, or a Django package that has already some typical parts implemented (e.g. a view for responding to long-polling requests, a customizeable JS snippet etc.). So, is there one? This problem looks very typical. -
What's the best way to do an AND and an OR filter simultaneously in Django?
I'm using a friendship system where I'm checking to see if the user was the one requested or if that person requested that person to be friends and vice versa. I'm just trying to filter the exact friend request model between two users. I added a friend in my system but this piece of code is printing out an empty query set. qs = FriendshipRequest.objects.select_related('from_user', 'to_user') .filter(Q(to_user=remote_user) & Q(from_user=user) | Q(from_user=remote_user) & Q(to_user=user)).all() -
My app does not show if statement in browser
My app does not show if statement in browser. I wrote in tc.html, <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Score</title> </head> <body> <h1>Score</h1> <h2>Your Score is {{ tcresults.tc }} {{ value1 = tcresults.tc if value1 > 5000: <h2>Good</h2> elseif value1 < 900: <h2>Bad</h2> }} </h2> </body> </html> I wanna show in my app's browser, if users' score is bigger than 5000,I wanna show "Good" in my browser and users' score is smaller than 900,I wanna show "Bad" in my browser. But now, all my if statement is showed in my app's browser. Data base has users' tcresults datas. How should I fix this? -
Possible me to custom dynamic login_url for Django @login_required?
Basic way to do this decorator @login_required is like this; @login_required(login_url='/path/to/login/') def foobar(request): # do stuff Here I want to make this value of login_url to dynamic path from request.GET.next. it possible for me? -
Secret_Key setting must nor be Empty Error?
While running my project in terminal, after running the command " python manage.py build -ad ", I am getting this following error. Can anyone help me out (project1) srk@srk-Lenovo-G580:~/easygaadi_backend$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in execute_from_command_line(sys.argv) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/core/management/base.py", line 306, in run_from_argv connections.close_all() File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/db/utils.py", line 229, in close_all for alias in self: File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/db/utils.py", line 223, in iter return iter(self.databases) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/db/utils.py", line 156, in databases self._databases = settings.DATABASES File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/conf/init.py", line 53, in getattr self._setup(name) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/conf/init.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/conf/init.py", line 116, in init raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
Django dashboard performance
I've designed a dashboard using Django and it has following elements: 1. User task 2. User email/notifications 3. 5 cards, representing summaries 4. 1 Pie-Chart 5. 1 Progress bar chart It's my local development and I don't have much data in system, so all loads within a second. I use custom SQL queries (RawSQL) to build my dataset; because I want to hide my Models being accessed directly and also there is complex joins involved for fetching results. I doubt this design may not be scalable with Production data. Please advice me to build my dataset as smaller sets and secure. I've already considered the Ajax; however, need experts advice or any reference to design scalable QuerySet/execution of those. -
Django Tutorial Part 1 Error: URL does not match URL patterns
I am going throught the Django tutorial here: https://docs.djangoproject.com/en/1.10/intro/tutorial01/ I follow the instructions exactly. But when I try to go to http://localhost:8000/polls/, I don't see the message “Hello, world. You’re at the polls index.” as expected. Instead, I get the following error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ The current URL, polls/, didn't match any of these. Here is my mysite/urls.py file. I am not sure why the first regex pattern in urlpatterns is not recognized. from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] -
Django module for a tag input field on a user form, with autocomplete & automatic adding new tags?
I want to have a django form that has a field that allows inputting tags, with autocomplete functionality, and the ability to automatically add new tags. I was using django-tagulous for this, until I discovered that pasting a series of 3 or more comma delimited strings, would cause the browser to hang (in jquery). I have looked at the alternatives, but either they are mainly designed to be used by the admin module, or the documentation for implementation is very sparse, without a real hardcoded demo, which is included with the tagulous package. Can anyone help me out? Thanks very much! Mark London -
Accessing django localhost server through lan
I have a django server running on my PC. I want to access the server through my android phone.How can I do that? I tried running python manage.py runserver 0.0.0.0:8000. After this, I can access server from my pc through PC's ip address, but not accessible through other device coonected to same wifi. -
TypeError: keys must be a string for JsonResponse()
I'm new to django and can't find much on the following error, while trying to return a Stripe Customer. None of the keys appear to be string. The code straight from Stripe documentation. @csrf_exempt def my_customer_view(request): try: customer_id = "cus_A4yKZgMIIpMH0C" customer = stripe.Customer.retrieve(customer_id) return JsonResponse(customer) except stripe.error.StripeError as e: return HttpResponse(status=402) returning this error: Internal Server Error: /payment/get_customer/ Traceback (most recent call last): File "/home/ec2-user/.virtualenvs/lotit/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/ec2-user/.virtualenvs/lotit/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ec2-user/.virtualenvs/lotit/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ec2-user/.virtualenvs/lotit/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/ec2-user/lotit/lotitdjango/paymentAPP/views.py", line 40, in my_customer_view return JsonResponse(customer,) File "/home/ec2-user/.virtualenvs/lotit/local/lib/python2.7/site-packages/django/http/response.py", line 520, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "/usr/lib64/python2.7/json/__init__.py", line 251, in dumps sort_keys=sort_keys, **kw).encode(obj) File "/usr/lib64/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib64/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) TypeError: keys must be a string [25/Feb/2017 02:42:50] "GET /payment/get_customer/ HTTP/1.1" 500 124638 This is the customer object: { "account_balance": 0, "created": 1486533146, "currency": null, "default_source": "card_19p6QYAJgAhgcU1VkYDxsaoP", "delinquent": false, "description": null, "discount": null, "email": "justin@gemia.com", "id": "cus_A4yKZgMIIpMH0C", "livemode": false, "metadata": {}, "object": "customer", "shipping": null, "sources": { "data": [ { "address_city": null, … -
no error in command prompt on manage.py runserver 8080 and at same time no respond
I am trying to make my second app in django but i don't see any respond and i am getting no errors but at the same time no respond . C:\Users\User\Desktop\tutorial\first>manage.py runserver 8080 C:\Users\User\Desktop\tutorial\first>python manage.py runserver C:\Users\User\Desktop\tutorial\first> Earlier with manage.py runserver 8080 , i was able to run my app perfectly but now i don't see any change in command prompt .What can be the reason for this and how do i solve this problem ? I am a beginner so please bear with me -
OperationalError at /admin/accounts/imageanduser/
I got an error, OperationalError at /admin/accounts/imageanduser/ no such column: accounts_imageanduser.t_bil . I did not designate /admin/accounts/imageanduser/ in urls.py, so I do not know how to fix this error. What should I do to fix this?