Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python syntax error without traceback?
I'm using django mongodb for a gym application website that I'm building for fun as my first web development project. I've just installed PyMongo, Django MongoDB, and I've created some models: from django.db import models from djangotoolbox.fields import ListField, EmbeddedModelField class Person(models.Model): name = models.CharField(max_length=200) class Workout(models.Model): date = models.DateTimeField('workout date') person = models.ForeignKey(Person, on_delete=models.CASCADE) lifts = ListField(EmbeddedModelField('Lift')) cardio = ListField(EmbeddedModelField('Cardio')) def __str__(self): return str(self.date) class Lift(models.Model): name = models.CharField(max_length = 200) #e.g. bench press, squat, deadlift, ... sets = models.ListField() # Stores a list of reps, each element corresponding to a set def __str__(self): return str(self.name) class Cardio(models.Model): name = models.CharField(max_length = 200) #e.g. running, cycling, etc. distance = models.IntegerField() #In metres. duration = models.IntegerField() #In minutes def __str__(self): return str(self.name) Now, I would like to start the shell to try to save some data. I get this strange error: (workout) Sahands-MacBook-Pro:workout sahandzarrinkoub$ python manage.py shell SyntaxError: invalid syntax (base.py, line 272) Since it doesn't even point me to an error location, I don't know what to do. There are many base.py-files on my computer. What is this error and how do I solve it? Some (possibly) useful additional info: (workout) Sahands-MacBook-Pro:workout sahandzarrinkoub$ python Python 3.6.2 (default, Jul 17 … -
"ValueError: attributes needs to be a callable, a list or a dict" on mezzanine admin
im using Django + Mezzanine and getting and unknow problem. When i try to create a new page, blogpost or anything in the mezzanine admin interface i receive the folowing message: "ValueError: attributes needs to be a callable, a list or a dict". This error ocures only on production on my server, at the local testing runs ok. Im using Mezzanine 4.1.0 and Django 1.9 on both servers Print of the error page -
Django template include overwrite <h1> tag
I have the following html files. banner.html <header class="intro2"> <div class="intro-body"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>{% block banner %}Bannertest{% endblock banner %}</h1> </div> </div> </div> </div> </header> test.html {% include 'banner.html' %} {% block banner %}Test{% endblock banner %} I'm new to Django but I would expect the H1 title to be updated to say Test instead of Bannertest? What am I doing wrong? -
Django Heroku and postgresql
I am new to publishing django apps on heroku. I have read their tutorials and figured I would start simple by modifying their template django project. So far everything was good. Then I made an app as one does, made a model and ran python3 manage.py makemigrations my_app python3 manage.py migrate and things seemed ok. I then pushed to heroku and there were no immediate complaints. However, now when I try to make save a new model I get the error: ProgrammingError at /my_app/ relation "my_app_myappmodel" does not exist LINE 1: INSERT INTO "my_app_myappmodel" ("field1", "field2", "field3") VALUES... odd... So I run this locally and everything works fine. I have tried cleaning my migrations, faking my migrations, squashing my migrations, etc (as other S.O. posts suggest) Nothing works. What is up and how do I fix it? -
Django model filter and do distinct by name
I have two models category class Category(models.Model): parent = models.ForeignKey() name = models.CharField(max_length=250) name parent ------- ------- vehicle 0 car 1 motorcycle 1 truck 1 bicycle 1 fff 0 .... Brand name category ---- --------- BMW car BMW truck BMW bicycle toyota car mercedes car mercedes truck someThing fff .... I want to create a queryset of Brand that is filtered by vehicle and to be distinct by name. so I can create a form in my template that will have a drop down filter with all the brands related to vehicle categories with no duplicate of names name category ---- --------- BMW car toyota car mercedes truck Is there any option to do it in a simple way,or do I need to write a function for that? I saw an example Select DISTINCT individual columns in django? but it returns a ValuesQuerySet and I need a QuerySet, and I prefer not to use ().distinct('someItem') that is supported only on PostgreSQL. -
Replacing django-admin default logo
I have generated a django-admin for my app and I can access the dashboard. But it contains a logo that says "django admin". I want to change it to my own custom logo. How can I do that? I have tried adding a base.html file to admin directory and tried to override but for some reason it's not working. It's code is as follows: {% extends "admin/base.html" %} {% load theming_tags %} {% load staticfiles %} {% block blockbots %} {{ block.super }} {# Using blockbots ensures theming css comes after any form media and other css #} {% render_theming_css %} <style type="text/css"> #header #branding h1 { background-image: url("bootstrap_admin/img/logo-140x60.png"); } </style> {% endblock %} {% block branding %} <a href="{% url 'admin:index' %}" class="django-admin-logo"> <!-- Django Administration --> <img src="{% static "bootstrap_admin/img/logo-140x60.png" %}" alt="{{ site_header|default:_('Django Admin') }}"> </a> {% endblock branding %} How can I achieve what I'm trying to? -
Social - Auth: google OAuth2 with Django project failing
I am trying to add googleOauth2 to my django project but keep getting a 404 as below stating "Backend not found" Page not found (404) Request URL: http://127.0.0.1:8000/social-auth/login/google/ Raised by: social.apps.django_app.views.auth Backend not found settings.py extract below: AUTHENTICATION_BACKENDS = ( 'social.backends.facebook.Facebook2OAuth2', 'social.backends.google.GoogleOAuth2', 'social.backends.twitter.TwitterOAuth', 'django.contrib.auth.backends.ModelBackend', 'account.authentication.EmailAuthBackend', ) SOCIAL_AUTH_FACEBOOK_KEY = 'xzy' SOCIAL_AUTH_FACEBOOK_SECRET = 'xzy' SOCIAL_AUTH_TWITTER_KEY = 'xzy' SOCIAL_AUTH_TWITTER_SECRET = 'xzy' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xzy' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xzy' I don't think I am getting as far as the google servers but I have rechecked and copied and pasted key and secret to ensure that was right. FB is working fine. -
attempt to create queryset with filters at runtime does not return rows but SQL looks fine
Django 1.11.5 I am trying to build a query set with a chain of filters at runtime def query_cache(self, object: ObjectType, filters: List[MutableMapping] = None) -> QuerySet: filters = filters or [] object_name = object.value q = Cin7Cache.objects.filter(object_type=f"'{object_name}'") for f in filters: q = q.filter(**f) return q I get a queryset that always evaluates to no rows. The sql generated is fine. If I run it on postgresql, I get the rows I want SELECT "voga_cin7cache"."object_uniqueID", "voga_cin7cache"."object_type", "voga_cin7cache"."last_modified", "voga_cin7cache"."jdata" FROM "voga_cin7cache" WHERE ("voga_cin7cache"."object_type" = 'orders' AND ("voga_cin7cache"."jdata" -> 'createdDate') > '"2017-09-09"'); I can produce the same SQL with this: result_query = Cin7Cache.objects.filter(object_type='orders').filter(jdata__createdDate__gt='2017-09-09') and in this case, the result_query is not empty. The query in this case is: SELECT "voga_cin7cache"."object_uniqueID", "voga_cin7cache"."object_type", "voga_cin7cache"."last_modified", "voga_cin7cache"."jdata" FROM "voga_cin7cache" WHERE ("voga_cin7cache"."object_type" = orders AND ("voga_cin7cache"."jdata" -> 'createdDate') > '"2017-09-09"') it's not exactly the same: in the where clause, string constant 'orders' is not quoted the second time, but both give the same result set when evaluated in the postgresql console. WHen I inspect the queryset object, in the non-working case I have _result_cache = [] and in the second example, the working one, the query set has _result_cache=None Why is my first query set empty? -
Django - IndentationError at /
So I'm building my 1st website and I'm having an issue. I don't really understand how views, modules and my website connects.. And maybe thats the reason I got this error... My folder of the html files is map/templates/serverlist.html My error - IndentationError at / unexpected indent (forms.py, line 6) Request Method: GET Request URL: http://172.16.10.60:8000/ Django Version: 1.3.1 Exception Type: IndentationError Exception Value: unexpected indent (forms.py, line 6) Exception Location: /media/sf_C_DRIVE/Users/eilon.ashkenazi/Desktop/EilonA/DevOpsMap/WebFiles/../WebFiles/map/views.py in <module>, line 4 Python Executable: /usr/bin/python Python Version: 2.7.5 Python Path: ['/media/sf_C_DRIVE/Users/eilon.ashkenazi/Desktop/EilonA/DevOpsMap/WebFiles', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages'] Server time: Wed, 13 Sep 2017 07:39:50 -0500 view.py - # Create your views here. from django.shortcuts import render_to_response from django.template import RequestContext from map.forms import PostForm from map.models import serverlist def home(request): entries = serverlist.objects.all() return render_to_response('serverlist.html', {'serverlist' : entries }) def postView(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): # Checks if validation passed servername = request.POST.get('ServerName','') owner = request.POST.get('Owner','') item = serverlist(servername=ServerName,owner=Owner) form.save() # Save the data into the DB return HttpRespondRedirect(reverse('map:serverlist')) # Resdirect after POST else: form = PostForm() return render(request, 'templates/serverlist.html', { 'form' : form, }) forms.py - from django import forms from map.models import serverlist class PostForm(forms.Form): ServerName … -
Django celery and rabbitmq doesn't work until restart
I have problem with django, celery and rabbitmq. I use celery to send messages to FCM devices, but problem is that celery doesn't run that FCM command for sending messages, until I restart celery server. And when I restart celery, and try again, still same, I need to restart it again after every action. Example code: from __future__ import absolute_import, unicode_literals from celery import shared_task # firebase cloud messaging from fcm.utils import get_device_model Device = get_device_model() @shared_task def send_firebase_message(json, **kwargs): response = Device.send_msg(json, **kwargs) return response This is simple code, so this Device.send_msg doesn't fire until I restart celery server. Anyone got any solution for this? What can be the problem? -
NoReverseMatch at /<urls>
I am using django 1.10. I want to know how the reverse function works. This is a basic chat application using django. I am stuck at line no:7 in index.html Below ones are the files: viwes.py from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import get_object_or_404 from chat.models import ChatRoom def index(request): chat_rooms= ChatRoom.objects.order_by('name')[:5] context = { 'chat_list' : chat_rooms } return render(request,'chats/index.html', context) def chat_room(request,chat_room_id): chat = get_object_or_404(ChatRoom, pk =chat_room_id) return render(request,'chats/chat_room.html', {'chat':chat}) chat/urls.py from django.conf.urls import url from django.urls import reverse from chat import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<chat_id>[0-9]+)/$', views.chat_room, name='chat_room'), ] index.html {% if chat_list %}</pre> <ul> <ul>{% for chat in chat_list %}</ul> </ul> <ul> <ul> <li><a id=""href="{% url 'chat_room' chat.id %}"> {{ chat.name }}</a></li> </ul> </ul> <ul>{% endfor %}</ul> <pre> {% else %} No chats are available. {% endif %} Any suggestions are welcome! -
Unit test in Django dont see correct redirect url for successfull login?
In my Django project I create custom admin page (NOT admin from Django). I have 2 login pages. One for admin, second for other users. Here below you can see urls.py file for admin. I test it and it works fine. After successful login Django redirect user to url which was next parameter (/administration/dashboard/). I wrote unit test and it raise error. From error I understand that Django redirect to default url (/accounts/profile/). Why unit test dont use settings which I did in urls.py file (next parameter)? How to fix this problem? Right now I notice that problem disappear only if I use this code LOGIN_REDIRECT_URL = '/administration/dashboard/' in settings.py. I cant use it cause in the future I will use LOGIN_REDIRECT_URL to my other login page. I would be grateful for any help! urls.py: from django.contrib.auth import views as authentication_views urlpatterns = [ # Administration Login url(r'^login/$', authentication_views.login, { 'template_name': 'administration/login.html', 'authentication_form': AdministrationAuthenticationForm, 'extra_context': { 'next': reverse_lazy('administration:dashboard'), }, 'redirect_authenticated_user': True }, name='administration_login'), ] tests.py: class AdministrationViewTestCase(TestCase): def setUp(self): self.client = Client() self.credentials = {'username': 'user', 'password': 'password'} self.user = User.objects.create_user(**self.credentials) def test_administration_authorization(self): self.assertTrue(self.user) logged_in = self.client.login(**self.credentials) self.assertTrue(logged_in) response = self.client.post( reverse("administration:administration_login"), follow_redirects=True ) self.assertEqual(response.status_code, 302) self.assertRedirects( response, reverse("administration:dashboard"), status_code=302, … -
Check if User is in Many2Many field
I have the following model with a m2m field where logged in Users can show interest in a publication: models.py from django.db import models class Publication: title = models.CharField(max_lenth=512) users_interested = models.ManyToManyField(User) views.py from django.shortcuts import render from django.views import View from .models import Publication class listPublicationView(View): def get(self, request, *args, **kwargs): publications = Publication.objects.all() return render(request, "base.html", {'publications': publications}) Now i try to produce a "i am already interested" in the template when a logged in user is already interested in the publication: base.html {% for publication in publications %} {{publication.title}} {% if currently logged in User is interested in publication (check users_interested) %} i am already interested {% endif %} {% endfor %} I've been stuck on this problem for days. Any help is appreciated. -
Django view not receiving variables from post form
I am sending variables from one template to a view through a post form and then using them in the next template. But the variables are not present when it reaches the template. Here is the JavaScript used in the first template. game2.html: function clickFntn(clicked_id) { {% autoescape off %} var clicked = document.getElementById(clicked_id).src; var clicked1 = clicked.replace(/^.*[\\\/]/, ''); var clicked2 = clicked1.slice(0,-4); if (clicked2 == gv_common) { gv_set1_counter = gv_set1_counter + 1; var set1 = {{ set1 }}; if (gv_set1_counter == 2) { var_user = "{{user}}"; game_id = {{game.id}}; var player_end_time = new Date(); var play_time = parseInt((player_end_time-player_start_time)/1000); post("{% url 'game2_end' %}", {type:"first", user:var_user, time: play_time, id: game_id}); } {% endautoescape %} }; function post(path, params, method) { method = method || "post"; // Set method to post by default if not specified. // The rest of this code assumes you are not using a library. // It can be made less wordy if you use one. var form = document.getElementById("form1"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit(); } view.py: def game2_end(request): if request.method == "POST": if request.POST.get("type") == "first": … -
finish setting up django channel & celery to have background process async to site
I have this javascript that fires when a button is clicked $('.test-parse').unbind().click(function() { parent = $(this).parent().parent(); var x = parent.find('.x').text(); var y = parent.find('.y').text(); var area_id = parent.find('.area').text(); if (area_id != '') { var area = areas[area_id]; } else { var area = null; } var cropped = $('.zoom-in').hasClass('btn-success'); if (cropped) { var img_url = $('#main-img-src').text(); } else { var img_url = $('.img-class').attr('src'); } var data = { 'x': x, 'y': y, 'image': img_url, 'width': $('.img-class').width(), 'height': $('.img-class').height(), 'color': parent.find('#color').css('background-color'), 'variance': parent.find('.color').val(), 'switch-color': parent.find('.switch-color').prop('checked'), 'new-color': parent.find('.color-code').val(), 'keep-perspective': parent.find('.perspective').prop('checked'), 'cls-id': parent.find('.cls-id').text(), 'area-id': area, 'grayscale': $('.gl-scale input').prop('checked'), } var unique_processing_id = ''; var task_id = ''; var csrftoken = $.cookie('csrftoken'); $.ajax({ url: "/start-render-part", type: "POST", dataType: 'json', beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, data: JSON.stringify(data), success: function(response){ if (response['status'] == 'ok') { if (response['unique-id']) { unique_processing_id = response['unique-id']; } if (response['task_id']) { task_id = response['task_id']; } var add_to_group_msg = JSON.stringify({ 'unique_processing_id': unique_processing_id, 'task_id': task_id, 'command': 'add_to_group', }); var socket = new WebSocket("ws://{HOST}/render-part/".replace('{HOST}', window.location.host)); socket.onopen = function() { var … -
How to differentiate cloned elements in jQuery and add events to cloned elements
I am trying to make deck builder. I want have this functionality, if I click on a card it shows in deck section, counter goes up. When I click on a card in deck section counter goes down and when it zero card disappears from deck section. My problem is how to differentiate cloned elements from original and how to add event to elements I am cloning. This is my JS script: $(".bronze").mouseup(function(e){ if (e.which === 1) { var counter = parseInt($(this).find(".bronze_counter").text(), 10) var card_name = $(this).attr("class").replace("bronze ", "") if (counter < 3) { counter += 1 $(this).find(".bronze_counter").text(counter); if (counter == 1){ $(this).clone().appendTo(".deck"); } else { $(".deck ." + card_name).find(".bronze_counter").text(counter); } } } }); And my template: <h3>Current Deck</h3> <div class="container deck"> </div> <div class="container"> {% for card in cards %} <span class="bronze {{ card.name | cut:'\'' | cut:' '}}"> <span><img src="{{ card.thumbnail_link }}" style="width:5%"> [</span> <span class="bronze_counter">0</span> <span>/3] </span> </span> {% endfor %} </div> Further I need to somehow save this deck in database. I was thinking about getting card names plus counter of each card and saving them in database. Am I digging a hole under myself? Thanks in advantage! Tomek Argasiński -
Attribute error '/posts/' 'Comment' object has no attribute '_mptt_meta'
I am following this example on how to set threaded comments with django_comments and django-mptt. I have followed most of it and the posted comments are working in admin but I am getting this error 'Comment' object has no attribute '_mptt_meta'. I have tried using a different instances to reference with and tried different objects but I am not sure what the problem might be? I have a comments app where I am running most of the code from in this example: comments/models.py: from django_comments.models import Comment from mptt.models import MPTTModel, TreeForeignKey class MPTTComment(MPTTModel, Comment): """ Threaded comments - Add support for the parent comment store and MPTT traversal""" # a link to comment that is being replied, if one exists parent = TreeForeignKey('self', null=True, blank=True, related_name='children') class MPTTMeta: # comments on one level will be ordered by date of creation order_insertion_by=['submit_date'] class Meta: ordering=['tree_id', 'lft'] comments/forms.py: from django import forms from django.contrib.admin import widgets from django_comments.forms import CommentForm from .models import MPTTComment class MPTTCommentForm(CommentForm): parent = forms.ModelChoiceField(queryset=MPTTComment.objects.all(), required=False, widget=forms.HiddenInput) def get_comment_model(self): # Use our custom comment model instead of the built-in one. return MPTTComment def get_comment_create_data(self): # Use the data of the superclass, and add in the parent field … -
Wrong hyperlinks of Django Rest Framework with complex stack using SSL, AWS Load Balancer, Nginx and Gunicorn
I can't find out how to correctly set up nginx so my hyperlinks in API build by DRF are correct. My current configuration for nginx is: upstream web { ip_hash; server web:8000; } # portal server { listen 8000; server_name localhost; location / { proxy_set_header Host $host:$server_port; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://web/; } } nginx is running inside a container exposing port 8000 and maps it into internally running gunicorn (also in a container) also on 8000. So when I spin up the whole docker machinery, I can nicely access localhost:8000/api and links are rendered OK. Even when I access it using different domain (e.g. if I set in /etc/hosts: 127.0.0.1 mytest.com), the URL and port get passed correctly to the DRF and links are rendered as expect. But this service must sit behind AWS Load Balancer with certificate using SSL. Hostname on this LB is set otherdomain.com and it redirects traffic to the machine where the above nginx is run using HTTP on port 8000. Then, when try to access it using https://otherdomain.com/api, links are rendered as http://otherdomain.com:8000/api/ <- hence wrong scheme (http instead https) and wrong port (8000 instead of 80/443). It … -
is it possible to create a rest web api with pure django?
I can't figure out if it's possible to create a django api without the django rest framework because I'm having troubles with csrf token while receiving my POST datas. Is it possible to disable this because I can't use django csrf token management in my javascript electron app ? -
How to Handle in Django - Exception Type: MultipleObjectsReturned
Here I am struggling with the handling the exception, here is the details of my data models. Routes Model- class Routes(models.Model): serial_no = models.IntegerField(primary_key=True) toll = models.CharField(max_length=1000, blank=True, null=True) cost = models.CharField(max_length=300, blank=True, null=True) t = models.ForeignKey('Tollmaster', models.DO_NOTHING, blank=True, null=True) r = models.ForeignKey(Routeinfo, models.DO_NOTHING) class Meta: managed = True db_table = 'routes' unique_together = (('serial_no', 'r'),) But in admin panel I am getting error MultipleObjectsReturned at /admin/tollm/routes/27/change/ get() returned more than one Routes -- it returned 2! Request Method: GET Request URL: http://127.0.0.1:8000/admin/tollm/routes/27/change/ Django Version: 1.11.5 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Routes -- it returned 2! Exception Location: C:\Users\prash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py in get, line 384 Python Executable: C:\Users\prash\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.2 I am using Postgresql database, here is the schema for this table, Table "public.routes" Column | Type | Modifiers -----------+-------------------------+----------- serial_no | integer | not null toll | character varying(1000) | cost | character varying(300) | t_id | integer | r_id | character varying(300) | not null Indexes: "sno_rid_pkey" PRIMARY KEY, btree (serial_no, r_id) Foreign-key constraints: "r_rinfo_fk" FOREIGN KEY (r_id) REFERENCES routeinfo(r_id) "t_id_fk" FOREIGN KEY (t_id) REFERENCES tollmaster1(tid) any help would be appreciated. -
Basic logics with Django views and foreignkey
I am new to Django and struggling with a basic problem, yet cannot find a solution online. I have these models: class Suggestion(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) description = models.TextField() created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class Vote(models.Model): suggestion = models.ForeignKey(Suggestion) voter = models.ForeignKey('auth.User') vote_count = models.IntegerField(default=1) and I'm trying create a view that would add a Vote to a given Suggestion, capturing the User who voted. I've seen some seem to do this with a form or with a regular function, so not sure what's the best practice here? -
Case WHEN to fetch data from different model when data is not zero
I have a simple model like this: class Payments(models.Model): dt=models.DateField() payer=models.IntegerField(default=0) If a member pays for himself, payer=0. But sometimes his support group (there are many groups) can pay for him/her and when that happens, the payer holds the ID of the support group. I didn't want to implement a relationship here. Now I want to list payments made but when payer>0, to get name of the subgroup that actually paid for the member. data=Payments.objects.filter(**build_filters['filters']).annotate(support_group_name=Case(When(payer__gt=0, then=Value('support group name goes here'), default=Value(''), output_field=CharField())).values('support_group_name','id','dt') I already have a function that use from various locations which returns name of a support group provided with id. I tried: data=Payments.objects.filter(**build_filters['filters']).annotate(support_group_name=Case(When(payer__gt=0, then=Value(support_name(payer)), default=Value(''), output_field=CharField())).values('support_group_name','id','dt') But I get payer is undefined. Any idea what I can do about this? -
template.render() python subfunction in Django 1.11 not available
So, I have PyCharm 2017.2.3, and Python 3.6, and Django 1.11. while practising on the test project, I tried to render to my index.html in view.py under my app. Below is the piece of code that I am talking about: def index(request): db_Conn = Album.objects.all() template = loader.get_template('/music/index.html') context = { 'db_Conn': db_Conn, } return HttpResponse(template.re) inside "return HttpResponse", I can get until template, but when I use a period after template to use the render() subfunction, I do not get any suggestion from PyCharm for "render(), instead, I could see two other functions which not relevant to my post. Can sombody help me on this. My learning is halted due to this. -
django admin 1.11 add an attribute to the options of a select
In django 1.11 admin, I have a list field and I would add an attribute in each <option> of my <select> Currently I have <select name = "example" id = "id_example"> <option value = "" selected> --------- </ option> <option value = "480"> data1 </ option> <option value = "481"> data2 </ option> <option value = "482"> data3 </ option> </select> I would like to add a link attribute to : <select name = "example" id = "id_example"> <option value = "" selected> --------- </ option> <option value = "480" link = "1"> data1 </ option> <option value = "481" link = "1"> data2 </ option> <option value = "482" link = "2"> data3 </ option> </select> I tested the following stack Django form field choices, adding an attribute but the function render_option (self, selected_choices, option_value, option_label) is not in django 1.11 https://code.djangoproject.com/ticket/28308 Do you have any idea how to add an attribute properly? -
Import Django models from outside the project
i m working at an app which use two tables from different databases.I manage to make the connection and make the tables strutures in models.py, but now one i change the models.py file, i copy one of the table in another python script, and i put the file elsewhere for other people to use it.My question it is possible in Django to import a model from outside the project? or the package?