Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatically refreshing table in Django using Jquery
I am developing a code in Django and trying to refresh the table automatically. I have used jquery but it does not refresh the table. Here is the my view: (views.py) from django.http import HttpResponse from django.template import loader from models import objectDB def index(request): objects= objectDB.objects.all() template = loader.get_template('Myapp/index.html') context= { 'objects': objects} return HttpResponse(template.render(context, request)) def refreshedindex(request): increment = int(request.GET['increment']) increment_to = increment + 10 objects= objectDB.objects.all() template = loader.get_template('Myapp/refreshedindex.html') context= {'objects': objects} return HttpResponse(template.render(context, request)) Here is my table plus java script: (index.html) <style> #customers { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } #customers td, #customers th { border: 1px solid #ddd; padding: 8px; } #customers tr:nth-child(even){background-color: #f2f2f2;} #customers tr:hover {background-color: #ddd;} #customers th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #4CAF50; color: white; } </style> {% if objects %} <table style="width:100%" border="1" id = "customers"> <tr> <th>obj Value</th> <th>item</th> <th>Type</th> <th>Tags</th> <th>Date First</th> <th>Date Last</th> </tr> {% for obj in objects %} <tr> <td>{{ obj.value }}</td> <td>{{ obj.item }}</td> <td>{{ obj.type }}</td> <td>{{ obj.tags }}</td> <td>{{ obj.date_first }}</td> <td>{{ obj.date_last }}</td> </tr> {% endfor%} </table> {% else %} <h3>These is no obj to show</h3> {% endif %} <script type="text/javascript" src="jquery-1.11.3.min.js"></script> <script> … -
page redirect with href don show data
im doing an app that get data from course and show it in a table. The url is: url(r'^(?P<id_course>\d{12}M\d{2})/enroll/$', enroll_course, name='enroll_course'), The issue is when redirect with these: <a href="{% url 'enroll_course' id_course=course.id_course %}" ><span class="new badge red darken-4" data-badge-caption="Enroll"></a> This is the function in views.py def enroll_course(request, id_course): print("desde la pagina") course_bites=get_course_detail(id_course) try: course_str = (course_bites).decode('utf-8') except UnicodeDecodeError: course_str= (course_bites).decode('latin1') course = json.loads(course_str ) print(course) print(type(course)) try: course['professor_name']= get_professor(course['professor_course']) except TypeError: print("Error") registration_form = RegistrationForm() context = { "course": course, "registration_form": registration_form, } return render(request, "public/enroll_course.html", context) It charge de page with no information of course, but when i reload with f5 in the browser, charge de data of the course. Any ideas ? Thank so much. -
How to log Django CronJob function errors to the console?
I jave a CronJob function in Django, parsing and saving data.The huge problem is that if something is wrong, no logs appear in console in terminal, which makes life and debugging very difficult. How to log to console in development mode on localhost? class ParseFromKarabasCron(CronJobBase): RUN_EVERY_MINS = 1 # every 2 hours schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'app.my_cron_job' # a unique code def do(self): pass http://django-cron.readthedocs.io/en/latest/installation.html -
Jenkins GAE Deploy hangs on Getting current resource limits
I am deploying a django project to GAE. When I deploy locally everything runs as smooth as silk, however when I try to deploy from Jenkins it gets hung on the following line: 12:42 PM Getting current resource limits. Full Deploy Log 12:42 PM Application: <gaeproject>; version: dev (was: 1) 12:42 PM Host: appengine.google.com 12:42 PM Starting update of app: <gaeproject>, version: dev 12:42 PM Getting current resource limits. Deploy Command python $GAE_PATH/appcfg.py -A $GAE_INSTANCE -V $GAE_VERSION update . -
How to get the name of a class model in template django
This question is similar to this question (Model name of objects in django templates) but not the same. I want to know how gets the Models class name (in this case 'Apple'), or at the very least return a string that I can pass over. Model.py django.db import models class Apple(models.Model): ..... apple.html <p>Sorry, no {{ ***Model class name**** }}</p> An example in the browser::: " Sorry, no Apple " -
How to modify formset's forms in an iteration
As far as I know if you iterate over a list and update its element, you dont update list itself. list_var = ['a','b','c'] for l in list_var: l = 'x' print list_var it prints out ['a', 'b', 'c'], not X's Below code belongs to one of my project. if hasattr(self.model, 'get_disabled_always_fields'): for field in self.model.get_disabled_always_fields(): for form in self.formset_instance: try: form.fields[field].widget.attrs['readonly'] = True except KeyError as e: pass It updates the list element and it effect the list we were iterating. I didn't bother about it until below code didn't affect formset instances, it's almost the same. for form in self.formset_instance: if hasattr(form.instance, 'get_disabled_fields'): for field in form.instance.get_disabled_fields(): try: form.fields[field].widget.attrs['readonly'] = True except KeyError as e: pass They are almost identical except, First one,checked the attribute and started an outer loop, second one started to iterate over formset instance and, another loop inside that. Question is , why formset forms affected by for loop modifications , and why my second code block didn't affect. -
Vue.js: load component from another component in javascript during initial page load
I'm really new to Vue.js so please be patient. Trying to create a page with a Vue.js component, that will have other child components. Managed to create and load the first outer component, but I'm having trouble to load the child/inner components. The main project is made using python Django and my code is below. Made several attempts with the import instruction, but always endup with an Uncaught SyntaxError: Unexpected token import message in the javascript console. Anyone can help me figure out what am I doing wrong? Django template: teleconsultoria/templates/teleconsultoria/registro_consultoria_0800.html ... <div class="col s12 bibliografia"> <div class="row" id="caixa-de-referencias"> <div class="input-field col s6"> <textarea id="textarea-bibliografia" class="materialize-textarea"></textarea> <label for="textarea-bibliografia">Bibliografia</label> </div> <list items=items></list> </div> </div> ... <script src="https://unpkg.com/vue"></script> <script src="{% static 'core/js/componentes_vue/list.js' %}"></script> <script> var appts2 = new Vue({ el: '#caixa-de-referencias', data: { items: [ 'referenciA 1', 'referenciA 2', ] } }); </script> List of items component: core/static/core/js/componentes_vue/list.js import collection_item from './collection_item.js'; var list = Vue.component('list', { props: ['items'], template: ` <div class="col s6"> <div class="search"> <div class="search-wrapper"> <input id="search-bibliografia" placeholder="Referências (sugestões)"> <i class="material-icons">search</i> </div> <ul class="collection with-header search-results"> <li class="collection-header"><p>Sugestões baseadas na "hipotese"</p></li> <collection-item v-for="item in items"></collection-item> </ul> </div> </div>` }); Item component: core/static/core/js/componentes_vue/collection_item.js var collectionItem = Vue.component('collection-item', { props: ['texto'], … -
ProgrammingError at /api/accounts/ relation does not exist
I have this django app on windows 10 python 3.6.2 django 1.11.5 djangorest 3.6.4 postgreSql 9.6 I'm using a custom User Model(AppUser) in the accounts app and i have AUTH_USER_MODEL = 'accounts.AppUser' in my settings file. I migrate in this order as advised from various sources migrate auth migrate accounts migrate to migrate all other apps And migrations succeeds as expected. The problem begins when i try to access the api through the browsable api ProgrammingError at /api/accounts/ relation "accounts_appuser" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_appuser" WHERE " I've delete all .pyc files created migrations again and got the same error. Through the process of trying over and over sometimes migration reports No migrations to apply Im starting to think the problem is from postgre -
login() and logout() of django.contrib.auth.views
//models.py from django.contrib.auth.models import AbstractUser from django.contrib.sessions.models import Session class CustomUser(AbstractUser): addr1= models.CharField(max_length=20) addr2= models.CharField(max_length=20) city= models.CharField(max_length=20) state= models.CharField(max_length=20) forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'})) //project/urls.py(the outer one) from django.contrib.auth import views from student.forms import LoginForm url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/home'}), //login.html(the login template) <div class="container"> <section id="content"> <form action="{% url 'login' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1>Login Form</h1> <div class="imgcontainer"> <img src="{% static 'student/patient.jpg' %}" alt="Avatar" class="avatar"> </div> <div class="username"> {{ form.username.label_tag }} {{ form.username }} </div> <div class="password"> {{ form.password.label_tag }} {{ form.password }} </div> <div class="submitb"> <input type="submit" value="Log In" name="mybtn"> </div> <div class="resetb"> <input type="submit" value="Reset"> <a href="#forgotpwd">Forgot password?</a> </div> <input type="hidden" name="next" value="{{ next }}" /> </form> </section> </div> this is the settings.py //settings.py LOGIN_REDIRECT_URL = '/login/sample' is the login() and logout() being called here when i login and logout in this manner?...if not then can i extend the login() and logout() of django.contrib.auth??? -
selecting specific object from list in django template
I am working with a formset_facotry and I am having an issue trying to figure something out. I have a list of users returned from a queryset in views.py file. I also have a list of forms that are created based on the number of objects returned from the list query. What I want to happen is that it selects the first object returned and display it before the first form that is to be displayed. Then grab the second object and displayed it right before the second form and so on... General idea behind it is the followoing: I want it to do something like this general template: header = 'Add record' + groupName if message: print(message) count = 0 for f in form: expenses[0] f.as_p count = count + 1 I want to grab a specific item based on the count within the loop: Here is the code that I have in the template: {% extends "base.html" %} {% block content %} <h2>Add expense - {{ currentGroup.name }}</h2> {% if message %} <p>{{message}}</p> {% endif %} <form action="." method="POST"> {% csrf_token %} {{ form.management_form }} {% with count=0 %} {% for f in form %} {% for expense … -
Anchor tag appending field to current url
I have a model with a field website_link class Partner(models.Model): website_link = models.CharField(max_length=120) And I access it in the template like so <div class="col-sm-3 col-sm-offset-1"> {% if instance.logo %}</a> <!-- website link just gets appended to the end of current url for some reason--> <a href="{{ instance.website_link }}"><img src='{{ instance.logo.url }}' class='img-responsive' alt=""></a> {% endif %} </div> When I call this in the template inside of an anchor tag the link navigates to the current url with the website_link appended to the end. So if instance.website_url = www.partnerone.com instead of the linke going to "www.partnerone.com" it goes to "http://127.0.0.1:8000/partners/partner-one/www.partnerone.com" -
Django add foreign field to a query
I have two tables: menu and foodtype class Foodtype(models.Model): foodtype_en = models.TextField() active = models.BooleanField() class Meta: managed = False db_table = 'foodtype' class Menu(models.Model): title_en = models.TextField() description_en = models.TextField() active = models.BooleanField() id_foodtype = models.ForeignKey(Foodtype, models.DO_NOTHING, class Meta: managed = False db_table = 'menu' Also, I generated a combined table: class MenuSerializer(serializers.ModelSerializer): foodtype_en = serializers.CharField() class Meta: model = Menu fields = ('id', 'title_en', 'active') And I'm trying to get all the active menu records. And I have: menu = Menu.objects.filter(id_truck=idtruck).annotate(foodtype=foodtype) What is wrong with my query? -
"Table 'nest.auth_user' doesn't exist"
I am creating a custom user registration form and I keep getting this error. How do I correct this. > ProgrammingError at /Identity/register/ (1146, "Table 'nest.auth_user' > doesn't exist") I adjusted the authentication system to use email instead of username and I switched from SQlite to Mysql. # Create models for Identities app. from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save from django.contrib.auth.models import User # Create your models here. class UserManager(BaseUserManager): # Create a model manager for User model with no user name field use_in_migrations = True def _create_user(self, email, password, **extra_fields): # Create and save a User with the given email and password if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): # Create and save a regular User with the given email and password. extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): # Create and save a SuperUser with the given email and password. extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise … -
Django Sessions table displaying only admin id
sessions Session key session data Expire date z8mmy56dgxtw7kiohhsczvdfugydt958 {} Oct. 12, 2017, 10:50 p.m. bnxre1r8muapvy1znvqu0msectghm2vm {u'_auth_user_hash': u'ca7e738308ed261de83fe3c80c9a4657b37e8c81', u'_auth_user_id': u'2', u'_auth_user_backend': u'django.contrib.auth.backends.ModelBackend'} Oct. 12, 2017, 10:14 p.m. 0erbl0nmfsj4vzczubslpea3eagyzroe {u'_auth_user_hash': u'ca7e738308ed261de83fe3c80c9a4657b37e8c81', u'_auth_user_id': u'2', u'_auth_user_backend': u'django.contrib.auth.backends.ModelBackend'} Oct. 12, 2017, 11:21 p.m. I have three users in my CustomUser(AbstractUser) table but no matter which one is logged in, the auth_user_id shows id=2 that is the id of the superuser admin. The other two ids are not shown. what is wrong here? I have not handled sessions explicitly. i have used django's inbuilt auth system using AbstractUser. -
Django restframework: How serialize two models queryset?
I have the following situation: A user can have more than one profile. Here is my models class. Something like this example: models.py class Profile: name=models.Charfield() class UserProfile: user=models.ForeignKey(User) profile = models.ForeignKey(Profile) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' Here I'm returning all my users by JSON but I would like to add a new field called profiles that returns all ids profiles that the user have. { "id": 1, "name" : "John" .... profiles = [1, 2] } How can I get(query) all profiles that the user have and add them on my final JSON? -
fetchone and fetchall returning null
I have a table userToken with three columns: piEmail , piCode, piToken This is how I created this table: class UserToken(models.Model): piEmail = models.CharField(max_length=128) piCode = models.CharField(max_length=128) piToken = models.CharField(max_length=128, unique=True, default=uuid4) piToken is autoFill, I do not insert this value. Now I am inserting value in this table and in the next line trying to fetch the token value for the random value which I inserted in table: random_number = User.objects.make_random_password(length=10, allowed_chars='123456789abcdefghijklmno') userToken_instance = UserToken.objects.create(piEmail='abc@abc.com', piCode=random_number) userToken_instance.save() cursor = connection.cursor() cursor.execute("SELECT piToken FROM app_usertoken where piCode = %s", (random_number,)) row = cursor.fetchall() But it is returning null. when I check in the table, value is there. I tried many ways but not working. worst thing is the below query is working fine, so I am not able to figure out what is wrong with the Where clause: cursor.execute("SELECT piToken FROM app_usertoken") Below statement returns null: cursor.execute("SELECT piToken FROM app_usertoken WHERE piCode ='h1cj82ongk'") -
filtering objects in descending order in django
I am trying to show a table of schools in a cluster(city or town) in a descending order with respect to school average marks. <table class="table"> <thead> <tr> <th>School</th> <th>Strength</th> <th>Average</th> </tr> </thead> <tbody> {% for school in school_order %} <tr> <td><a href="{% url 'data:school_detail' state.id region.id cluster.id school.id %}">{{ school.school_name }}</a></td> <td>{{ school.strength }}</td> <td>{{ school.get_average }}</td> </tr> {% endfor %} </tbody> </table> This is the table I'm trying to display in my template school_order = cluster.school_set.all().order_by('-get_average') This is how I'm trying to get school_order in view.py get_average is not a field for model school but it is a method I used in the model. class School(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) region = ChainedForeignKey(Region, chained_field="state",chained_model_field="state", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE) cluster = ChainedForeignKey(Cluster, chained_field="region",chained_model_field="region", show_all=False, auto_choose=True, sort=False, on_delete=models.CASCADE) school_name = models.CharField(max_length=250) facilitator = models.CharField(max_length=250) f_number = models.IntegerField() f_email = models.EmailField() school_logo = models.FileField(default='') strength = models.IntegerField() def get_average(self): return self.avergae_set.latest('average_date').average_value This is my model for school. The error I'm getting is cannot resolve keyword 'get_average' into field. Please help! -
TemplateDoesNotExist at /accounts/register/ accounts/register.html
why i still getting this error even though i already create register.html? i already read about this error and i already try to put in settings.py : TEMPLATES_DIRS [ os.path.join(BASE_DIR, '/profiles/accounts/templates')] and still nothing have changed . i try to create my own customize registration form . can anyone help me please ? im new in django and python . i dont know what went wrong because i already create the template by following this tutorial : https://www.youtube.com/watch?v=5x97gGspzjY -
Getting associated values from Python dictionary that is using lists
Ok, so I am working on an application that can go through a number of different database objects, compare the string and return the associated id, first name and last name. I currently have it to where I am building a list of tuples and then populating a dictionary with the key and values(using a list). What I want to do next is find the Max percentage and then return the associated fist and last name from the dictionary. I know the description is a little confusing so please look at the below examples and code: # My Dictionary: {'percent': [51.9, 52.3, 81.8, 21.0], 'first_name': ['Bob', 'Bill', 'Matt', 'John'], 'last_name': ['Smith', 'Allen', 'Naran', 'Jacobs']} # I would want this to be returned: percent = 81.1 (Max percentage match) first_name = 'Matt' (First name associated with the max percentage match) last_name = 'Naran' (Last name associated with the max percentage match) # Code so Far: compare_list = [] compare_dict = {} # Builds my list of Tuples compare_list.append(tuple(("percent", percentage))) compare_list.append(tuple(("first_name", first_name))) compare_list.append(tuple(("last_name", last_name))) # Builds my Dictionary for x, y in compare_list: compare_dict.setdefault(x, []).append(y) Not sure where to go to return the first and last name associated with the Max percentage. … -
What framework or tool has been used to build kegbot-server
What framework or tool has been used to build kegbot server? https://github.com/Kegbot/kegbot-server I can see there it's using Django, but i can't find manage.py and the directories structure does't look like typical django project. Is it some constructor? Or maybe kind of django fork? Or maybe it's just packaged thing that supposed for deployment but not contribution? -
Django not finding templates
I'm trying to set up a Django app for a project, but I'm having trouble with the templates folder being found. Here is my layout... -Alexa -Alexa -__init__.py -settings.py -urls.py -wsgi.py -AlexaApp -migrations -static -css -js -templates -login.html -__init__.py -admin.py -apps.py -models.py -tests.py -views.py -manage.py settings.py INSTALLED_APPS = [ 'Alexa', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Alexa.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] urls.py from django.conf.urls import url from django.contrib import admin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', auth_views.login, {'template_name': 'templates/login.html'}), url(r'^logout/', auth_views.logout), ] I've tried adding os.path.join(BASE_DIR, 'templates') to my TEMPLATES DIRS, but that didn't help. I've also tried adding 'Alexa' and 'AlexaApp' to my INSTALLED_APPS as well. I've also tried changing the 'templates/login.html' to a direct path the template folder with no success. I'm sure it's something simple, but not sure where I'm messing up. I'm using Django 1.11.5. Can anyone help me out? Thanks in advance! Dylan -
SAML SSO Authentication with Django REST Framework
I'm currently working on a AngularJS front-end and Django REST back-end. I've been using django-rest-auth in the past to authenticate my connections between the two, but I now have to integrate a SSO authentication using SAML. I've looked around and decided to use python3-saml, but any of the documentation and use case examples (for this package and any other) are applied for pure Django applications. I've been basing myself on OneLogin's django/flask guide and I tried making a custom Middleware that would catch my requests, but the implementation of the redirects provided by OneLogin does not work with REST call (obviously). I've also seen some people using the AUTHENTICATION_BACKENDS Django setting and I'm wondering if it's maybe more what I'm looking for. Thank you for any help. -
Django Template Form
This is how my form input field looks like! <td>Email:</td> <td>{{ form.email }}</td> It's giving Email: & then input field as usual. In < input /> fields we have placeholder="..." which shows up in the input. But in my case how can I pre-populate email inside input as a placeholders? -
how to make django render the default home page produced by apache
As is known, after issuing a request through web explorer, apache will return its default static home page to the explorer. I'm using django and apache with mod_wsgi to deploy my site(i.e. django app on apache web server). How to route the processing to django mapping rules defined in views.py to dynamically produce a home page(i.e. index page) for that site when I issue a request to that server running apache? Thanks in advance! -
Blue footer in Gentelella Theme
I'm currently working with this fantastic theme. For context I'm using the django flavor django-gentelella. My problem is when I remove some elements from the side bar a blue footer appears, those elements are the following: Removing <div class="sidebar-footer hidden-small"> Blue Footer appears: Not removing the above class but if you remove some menu elements from the side bar when you click the hamburger to minimize the sidebar, blue footer again: I tried to replicate both scenarios on the demo: gentelella demo but only the first scenario can be reproduced, probably because the template is not being rendered. I'm not a CSS expert but if someone can help me I would really appreciate it.