Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
passing parameters through url to view django
I'm having some difficulty passing values to my view through url. So far, I've managed to run my view without any issues. view.py (draws a graph): def draw(request) .... .... return HttpResponse (buffer.getvalue(), content_type="Image/png") but I need my view to take input from users, so I edited it and added an extra parameter: def draw(request, loan_amount) loanAmount = loan_amount ..... The user input is passed from a form, to another view: def search_member(request): loanAmount = request.GET.get('desired_loan') return render(request, 'blog/search_member.html', {'loanAmount':loanAmount) In my template, I insert the user input in the draw's parameter: <img src="http://test.com/graph/{{loanAmount}}"> This is suppose to draw an image base on the user input, instead I get no image at all. If I remove the parameter, the image works fine. I'm assuming I'm doing something wrong with the setup of the parameter, most likely in the template, or url: url(r'^graph/(?P<desired_loan>\d+)/$', views.draw, name='draw'), I have tested the view, form and everything else, they all work. How can I narrow down this problem to find the solution? Any direction/help would be appreciated, thanks, -
How to access parent abstract class of model in Django
(using dajngo 1.9 and python 2.7) So I have an abstract class with a few child classes. It looks like this : class Node(models.Model): [...] class Meta: abstract = True class Individual(Node): [...] class Company(Node): [...] class Media(Node): [...] class Share(models.Model): share = models.FloatField(null=True) child_content_type = models.ForeignKey(ContentType, related_name='child') child_object_id = models.PositiveIntegerField() child = GenericForeignKey('child_content_type', 'child_object_id') parent_content_type = models.ForeignKey(ContentType, related_name='parent') parent_object_id = models.PositiveIntegerField() parent = GenericForeignKey('parent_content_type', 'parent_object_id') The thing is that, virtually, the Share's child and parent can take any model in. So I want to implement an extended save() method (for Share) that will check that both the child and the parent inherit from Node. I'm looking for something that could look like this : assert child.inherited_class.name == 'node' assert parent.inherited_class.name == 'node' (or with child_content_type of ocurse) -
AWS Django TemplateDoesNotExist S3
I'm trying to get my templates to work out of my static files directory which is stored in a S3 bucket. The templates work when its within the app but when I take it out I get this error Request Method: GET Request URL: http://django-env2.55jfup33kw.us-west-2.elasticbeanstalk.com/ Django Version: 1.9.2 Exception Type: TemplateDoesNotExist Exception Value: home.html Exception Location: /opt/python/run/venv/lib/python2.7/site-packages/django/template/loader.py in get_template, line 43 Python Executable: /opt/python/run/venv/bin/python Python Version: 2.7.10 Python Path: ['/opt/python/run/venv/lib64/python2.7/site-packages', '/opt/python/run/venv/lib/python2.7/site-packages', '/opt/python/current/app', '', '/opt/python/run/baselinenv/local/lib64/python2.7/site-packages', '/opt/python/run/baselinenv/local/lib/python2.7/site-packages', '/opt/python/run/baselinenv/lib64/python2.7', '/opt/python/run/baselinenv/lib/python2.7', '/opt/python/run/baselinenv/lib64/python2.7/site-packages', '/opt/python/run/baselinenv/lib/python2.7/site-packages', '/opt/python/run/baselinenv/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7', '/usr/lib/python2.7'] Server time: Mon, 22 Aug 2016 04:31:48 -0700 settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['<bucket name>.s3-website-us-west-2.amazonaws.com/static/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', ], }, }, ] AWS_STORAGE_BUCKET_NAME = <bucket Name> AWS_ACCESS_KEY_ID = <AWS_ACCESS_KEY_ID > AWS_SECRET_ACCESS_KEY = <AWS_SECRET_ACCESS_KEY > DEFAULT_FILE_STORAGE = 'ebdjango.s3utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'ebdjango.s3utils.StaticRootS3BotoStorage' MEDIA_URL = '<bucket Name>.s3-website-us-west-2.amazonaws.com/media/' STATIC_URL = '<bucket Name>.s3-website-us-west-2.amazonaws.com/static/' s3utils.py from storages.backends.s3boto import S3BotoStorage StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static') MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media') views.py from django.shortcuts import render from homepage.models import * from ebdjango.settings import * # Create your views here. def home(request): query = Musician.objects.raw('SELECT F.*, T.* FROM homepage_musician F LEFT JOIN homepage_album T ON F.id = T.artist_id') return render(request, "home.html", {'query':query}) s3 bucket Static Website Hosting You can … -
Import pubsub directley from GoogleAppEngine
I'm using Djangae and need to integrate it with Gcloud PubSub. The only problem is -- when I install python-gcloud and try to run it along with appengine I got following extension: root@ubuntu-1gb:~/tiger/tiger_server# python manage.py shell INFO 2016-08-21 09:26:33,864 blobstore_service.py:73] Starting blobstore service on localhost:8080 Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) import gcloud.pubsub Traceback (most recent call last): File "<console>", line 1, in <module> File "/root/tiger/tiger_server/sitepackages/gcloud/pubsub/__init__.py", line 26, in <module> from gcloud.pubsub.client import Client File "/root/tiger/tiger_server/sitepackages/gcloud/pubsub/client.py", line 19, in <module> from gcloud.client import JSONClient File "/root/tiger/tiger_server/sitepackages/gcloud/client.py", line 20, in <module> from gcloud._helpers import _determine_default_project File "/root/tiger/tiger_server/sitepackages/gcloud/_helpers.py", line 27, in <module> from google.protobuf import timestamp_pb2 ImportError: No module named protobuf When running in the clean virtual environment (without appengine) everything is fine. Is there are build in Gcloud PubSub service library in Google App Enhine? -
KeyError 'CONTENT_TYPE' only in dev server
I have the following code that works perfectly fine in my local development , but when I use the same in project dev server, I get a KeyError: 'CONTENT_TYPE' views.py if request.META['CONTENT_TYPE'] == 'text/plain': context = {} context['All'] = {'total': Theme.objects.all().count(), 'id': 0} for t in ThemeCategory.objects.all(): context[t.categoryName] = {'total': t.theme_set.count(), 'id': t.id} context = collections.OrderedDict(sorted(context.items())) if request.user.is_anonymous(): token = "false" else: token = get_json_web_token(request.user) This is deployed in EC2 server with help of gunicorn and only getting error by running through gunicorn but by running in local host its works...What could be the issue Any help is appreciated -
Using scikit learn with django and spark
I am building a web service which can run machine learning algorithms using Django, scikit and spark. I have imported the spark library by setting the PYTHONPATH = %SPARK_HOME%\python;%SPARK_HOME%\python\lib\py4j-0.8.2.1-src.zip;" I am fetching the data using the sc.textFile("path to data"), where sc is the SparkContext and then converting the data into the pandas data frame. After that I am applying the RandomForestClassifer on the data which is imported from sklearn. My question when I am applying this classifier, the execution will occur on top of the spark or not? I am new to spark actually. from django.shortcuts import render from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.conf import settings from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import KFold from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from pyspark.context import SparkContext from pyspark.mllib.tree import RandomForest from pyspark.mllib.util import MLUtils from pyspark.sql import SQLContext sc = SparkContext(appName="Python") def localdata(): data = sc.textFile('/root/Data/sample1.csv').map(lambda line : line.split("~")) header = data.first() data = data.filter(lambda line: line != header) df = data.toDF(header) #datadf gives the schema dfpandas = df.toPandas() model = RandomForestClassifier(n_estimators=25, min_samples_split=25, max_depth=7, max_features=1) model.fit(dfpandas[predictors], dfpandas[outcome]) #predictors are independent column names and outcome … -
Django Ajax - $.get method success function executed without actual Django view execution
Deleted the previous question to clarify it a bit. I have A Django powered website and a template with dynamically populated table. Template: <table id = 'my_table'> <thead> ...... </thead> <tbody> </tbody> </table> Javascript $(function () { refresh_vendors_list_table(); }); function refresh_vednors_list_table() { $.get("/ajax_refresh_vendors_list_table/", data, function(response) { $('#my_table').find('tbody').html(response); }); } View: def ajax_refresh_vendors_list_table(request): template = 'vendors/vendors_list_paginator.html' vendors_qs = vendors_qs.filter(...) context = {'vendors_qs':vendors_qs} return render_to_response(template, context, context_instance=RequestContext(request)) Template for the table (vendors_list_paginator.html) {% load el_pagination_tags %} {% paginate vendors_qs %} {% for vendor in vendors_qs %} <tr> ...... </tr> {% endfor %} {% show_more_table %} When pressing each row in the table, I am redirected to the corresponding vendor's profile. After editing the profile, I press the back button and coming back again to the table page. At this stage, I start to debug the $.get("/ajax_refresh_vendors_list_table/", data, function(response) I also put a breakpoint at template = 'vendors/vendors_list_paginator.html' (let's call it breakpoint A) A very strange behaviour is observed in $.get function: the corresponding Django view is not called (I don't see my app stop at breakpoing A) and yet $('#my_table').find('tbody').html(response); is executed directly as if the $.get function should execute successfully !!!! In other words, $.get function is executed without any participation … -
"Cannot find installed version of python-django or python3-django" when running celery worker
When I run the command via ubuntu 15.04 terminal celery worker -A celery_blog -l inf -c 5 I always get Cannot find installed version of python-django or python3-django. Though I have installed django for python 2.x as well as 3.x, you may refer the attached screenshot also. -
Django m2m through model with classic admin widget
I need to customise a through model of a many-to-many relationship, the customisation is subtle, because the user won't need do act manually, I try to explain myself better by explaining my use case with the following pseudo code: RouterConfiguration - vpn (many-to-many through VpnClient) # other fields VpnClient - router: ForeignKey to RouterConfiguration - vpn: ForeignKey to Vpn - cert: ForeignKey to Cert Vpn # other fields Cert # (stores x509 certificates) # other fields The through model VpnClient has only one additional field, a ForeignKey to Cert, but I want VpnClient to automatically create a Cert instance without user interaction and until here there is no problem. The problem comes in the Django Admin, because as far as I understood, it is not possible to use the classic many2many widget when using a through model: When you specify an intermediary model using the through argument to a ManyToManyField, the admin will not display a widget by default. This is because each instance of that intermediary model requires more information than could be displayed in a single widget, and the layout required for multiple widgets will vary depending on the intermediate model. Reference: https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#working-with-many-to-many-intermediary-models But I don't want the … -
returning multiple values in view django
I'm having some difficulty returning multiple values in my view. I can create a model, store the values in the model, and then return it, but I don't want to do this. Is it possible to return multiple values? For example, view.py: loanAmount = request.GET.get('desired_loan') repaymentTime = request.GET.get('repayment_time') return render(request, 'blog/draw.html', "I want to return loanAmount and repaymentTime") and then in Template, simply: {{ loanAmount }} How do go about this? Any direction or help will be appreciated. Thanks, -
Asynchronious email sending using celery doesn't work
I'm trying to make Django not to wait until an email is sent. I've decided to use Celery to do that. Unfortunately I can't figure out how to make it work asynchronously. I've created a file tasks.py: # -*- coding: utf-8 -*- from __future__ import absolute_import from .notifications import CustomerNotifications from celery import shared_task @shared_task def prereservation_has_been_confirmed(reservation): CustomerNotifications.prereservation_has_been_confirmed(reservation) The CustomerNotifications.prereservation_has_been_confirmed(reservation) method sends an email to customer. Email sending works but it still waits until the email is sent. (the view is called by AJAX). Do you know what to do? -
Django/Ajax - table is not updated when returning to the page by browser back button
I have A Django powered website and a template with dynamically populated table. Template: <table id = 'my_table'> <thead> ...... </thead> <tbody> </tbody> </table> Javascript $(function () { refresh_vendors_list_table(); }); function refresh_vednors_list_table() { $.get("/ajax_refresh_vendors_list_table/", data, function(response) { $('#my_table').find('tbody').html(response); }); } Now imagine that I have students data in my table. When pressing each row in the table, I am redirected to the corresponding student's profile. After editing student profile I press the back button and going to the table page. I would expect the data to be updated since table content is rendered by Ajax (dynamically). However, this is not what I see in reality. I still have to press the refresh button to see my updates. Previously, when I rendered the table using Django for-loops inside the template, I reloaded the paged automatically, but this proved a poor user-experience. Now I am very frustrated to see that Ajax doesn't work as well. Any ideas how to make the table re-render ? -
Query field for foreign key
So i am writing a form class where you choose Country and then based on which country you choosed it puts Regions into region field. My model looks like: class Country(models.Model): name = models.CharField(max_length=30) short_name = models.CharField(max_length=2) flag = models.ImageField(upload_to='flags') hidden = models.BooleanField(default=False) def __str__(self): return self.name class Meta: verbose_name_plural = "Countries" class Region(models.Model): name = models.CharField(max_length=40) country = models.ForeignKey(Country, on_delete=models.CASCADE, blank=False, null=False) is_capital = models.BooleanField(default=False) def __str__(self): return self.name And now in forms.py i have following class SignupForm(forms.Form): country = forms.ModelChoiceField(queryset=Country.objects.all(), required=True, empty_label='Choose your country...') region = forms.ModelChoiceField(queryset=Region.objects.filter(??), required=True, empty_label='Choose your region...') def signup(self, request, user): user.country = self.cleaned_data['country.id'] user.save() I was experimenting with conditions like id = country.id but no sucess, any suggestions? -
django - CreateView object already exists
When using CreateView, currently nothing is happening if the object to be created (as filled in the form by the user) already exists. How do I redirect to the last page? -
AngularJS, Django Cors Django Rest Framework Intergration
I have developed a site with django backend and also incorporated a django rest framework API and django-cors . The next challenge is to consume the API using angularJS.But the browser keeps returning that my request is Forbidden Error 403. Here's My settings.py INSTALLED_APPS = [ 'bootstrap3', 'Users.apps.UsersConfig', 'projects.apps.ProjectsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders',] MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = ( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'x-csrftoken', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials', 'Access-Control-Allow-Headers', 'Access-Control-Allow-Methods') Heres the html code. <!DOCTYPE html> <html lang="en-US"> <script type="text/javascript" src='angular.js'></script> <head> <title>Test 1</title> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> {{results}} </div> <script type="text/javascript"> var app = angular.module('myApp',[]); app.controller('myCtrl',function($scope,$http){ $http.get("http://127.0.0.1:8000/api/projects/") .then(function(response){ $scope.results=response.data; }); }); app.config(['$httpProvider',function($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common["X-Requested-With"]; $httpProvider.defaults.headers.common["Accept"] = "application/json"; $httpProvider.defaults.headers.common["Content-Type"] ="application/json"; $httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] ='*'; $httpProvider.defaults.headers.common['Access-Control-Allow- Headers']='Origin, X-Requested-With, Content-Type, Accept'; $httpProvider.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET, OPTIONS'; $httpProvider.defaults.headers.common['Access-Control-Allow-Credentials']= true;}]) </script> </body> </html> -
Django rq scheduler can not enqueue same task twice
I am using rq scheduler. I want to remind users to verify their email after 2 mins and 10 mins. So I use post_save signal to schedule these tasks. I have set up task like this: from datetime import timedelta import django_rq @receiver(post_save) def remind_to_verify_email(sender, created, instance, **kwargs): """Send verify email for the new user.""" list_of_models = ('Person', 'Company') scheduler = django_rq.get_scheduler("default") if sender.__name__ in list_of_models: if created: scheduler.enqueue_in(timedelta(minutes=2), send_verification_email, instance) scheduler.enqueue_in(timedelta(minutes=10), send_verification_email, instance) Problem is: I am getting one mail after 2 mins but not second mail after 10 mins. Any help appreciated. -
Can't have many to one relationship for list intention
I would like to add many Agent to PricingOption in a list fashion. class PricingOption(models.Model): creation_date = models.DateTimeField(default=timezone.now) agents = models.ForeignKey("Agent", related_name='%(class)s_agent') Is the model that contains the list. The list objects themselves are class Agent(models.Model): agent_id = models.CharField(max_length=10) ... Now when I try to do things like pricing_option = PricingOption() pricing_option.agents_set.add(some_agent) I get *** AttributeError: 'PricingOption' object has no attribute 'agents_set' -
{Javascript} How to return Json when calling POST xmlHttpRequest
I tried to use xmlHttpRequest POST to upload file in Meteor project. With Django REST framework 2.3.14. I used: var file = $('#control_import_file')[0].files[0]; var xmlHttpRequest = new XMLHttpRequest(); xmlHttpRequest.onreadystatechange = function (e) { if (e.target.status == 200) { var resp = JSON.parse(e.target.response); if (resp.status == 'success') { alert("success"); } else { alert("fail"); } } }; xmlHttpRequest.onload = function () {}; xmlHttpRequest.open("POST", "http://mydemosite.net/orders/import-coupon/25/", true); if (window.FormData) { var formData = new FormData(); formData.append("datafile", file); xmlHttpRequest.send(formData); } In Chrome, it returns: Event {isTrusted: true, type: "readystatechange", target: XMLHttpRequest, currentTarget: XMLHttpRequest, eventPhase: 2…} So I can easyly get Json string: target.response object: ""{"status": "error", "data": {"error_data": ["test123"], "error_code": 0, "error_msg": "Check failed"}, "error_data": ["test123"], "error_code": 0, "error_msg": "Check failed"}" JSON.parse(e.target.response); --> get sth I want. However in Firefox: it returns all that json string above in HTML format: <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><meta name="robots" content="NONE,NOARCHIVE"...</html> Anyone can help me how to handle error response in Firefox? Or Is there any way to get response in all browsers? Thanks a lot! -
Django 1.10 Translation
I was trying internationalization/localization in django. I am getting an error while i am trying to make the '.po' files using the command ./manage.py makemessages relevant parts from settings.py import os from django.utils.translation import ugettext_lazy as _ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '-6n@y00j+-a*8%2lmxrghi&4ld8shgrtuj)cuwdzq94acmx22_' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'sampleproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'django.template.context_processors.i18n' ], }, }, ] WSGI_APPLICATION = 'sampleproject.wsgi.application' LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('fi-FI', _('Finnish')), ('en', _('English')), ] LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] relevant parts from urls.py urlpatterns += i18n_patterns( url(r'^$', home, name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^polls/', include('polls.urls')), ) here is the traceback. Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/project/Myapps/for_sample/lib/python3.4/site-packages/django/core/management/commands/makemessages.py", line 361, in handle potfiles … -
Django pass data to related manager
Is there a possibility to pass parameters to related manager? I need to annotate results of related manager according to some parameters passed to main model manager (which method is called with parameters). class Product(models.Model): title = models.CharField(max_length=100, blank=False) class Recipe(models.Model): ingredients = models.ManyToManyField(Product, through='Ingredient') objects = MyRecipeManager() class Ingredient(models.Model): product = models.ForeignKey(Product) recipe = models.ForeignKey(Recipe) objects = MyIngredientManager() class MyRecipeManager(models.Manager): def do_some_magic(self, payload) # How to pass payload to MyIngredientManager from there? return self.get_queryset() class MyIngredientManager(models.Manager): def get_queryset(self) # How to get payload here? return self.get_queryset() -
How can I set success_mesasge with format() in django generic view?
What I want to implement is like this : from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.views.generic import CreateView from posts.models import Post class PostNewView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'content', 'image'] success_message = "{} has been created successfully".format(self.post.title) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) But it occurs error. Any ideas? -
Template displays foreign key instead of CharField for disabled field
I am using Django 1.97 and have the following models: class Symbol(models.Model): symbol = models.CharField(max_length=15) # more fields class Position(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) symbol = models.ForeignKey(Symbol) # more fields def get_user_positions_qs(self, user): positions = Position.objects.all().select_related('symbol').filter(user=user).order_by('symbol') return positions I need to display a modelform in a template for the logged in user's positions, but the symbol field needs to be disabled. So far I have the following in my view: position = Position() form_class = PortfolioForm PositionModelFormSet = modelformset_factory(Position, fields=('symbol', 'various_other_fields'), form=form_class) def get(self, request): positions = self.position.get_user_positions_qs(user=request.user) position_formset = self.PositionModelFormSet(queryset=positions) return render(request, 'template.html', {'position_formset': position_formset}) And the form: class PortfolioForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PortfolioForm, self).__init__(*args, **kwargs) self.fields['symbol'].widget = forms.TextInput(attrs={'disabled': True}) class Meta: model = Position fields = ['symbol', 'various other fields'] The problem is that when displaying the form, the symbol field only contains the foreign key id instead of the actual symbol CharField from the symbol model. If I change the form so that the symbol field is not disabled, then the symbol field in the template displays the correct value (however it then has a dropdown allowing the user to change the symbol which is not allowed). So my question is, how do I disable the symbol … -
Disable Django Oscar stock management
We doesn't needs stock management and wants to disable thic component at all. I have found answer here but checkbox deactivating does not helps. I think i have to patch sources but can't understand how for now. -
Django/Python: UnboundLocalError. where is my mistake?
models.py class Revistapresei(models.Model): titlulArticol = models.CharField(max_length=300) textArticol = models.TextField() dataArticol = models.DateField(blank=True, null=True) linkArticol = models.CharField(blank=True, max_length=200) STIRIINTERNE = 'Interne' STIRIEXTERNE = 'Externe' TIP_ARTICOL_CHOICES = ( (STIRIINTERNE, 'Interne'), (STIRIEXTERNE, 'Externe'), ) tipArticol = models.CharField(max_length=7, choices=TIP_ARTICOL_CHOICES, default=STIRIINTERNE) def __str__(self): return self.titlulArticol url.py from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^revistaPresei/$', views.revistaPresei_list, name='revistaPresei_list'), url(r'^revistaPresei/(?P<pk>[0-9]+)/$', views.revistaPresei_detail, name='revistaPresei_detail'), ] views.py from django.shortcuts import render, get_object_or_404 from .models import Revistapresei def index(request): return render(request, 'blog/index.html', {}) def revistaPresei_list(request): revistaPreseis = Revistapresei.objects.order_by('-dataArticol') return render(request, 'blog/revistaPresei_list.html', {'revistaPreseis':revistaPreseis}) def revistaPresei_detail(request, pk): revistaPresei = get_object_or_404(revistaPresei, pk=pk) return render(request, 'blog/revistaPresei_detail.html', {'revistaPresei': revistaPresei}) revistaPresei_list.html <html> <head> <title>Revista Presei List</title> </head> <body> {% for revistaPresei in revistaPreseis %} <div> <p>{{ revistaPresei.dataArticol }} / {{ revistaPresei.tipArticol }}</p> <h1><a href="{% url 'revistaPresei_detail' pk=revistaPresei.pk %}">{{ revistaPresei.titlulArticol }}</a></h1> <p>{{ revistaPresei.textArticol }}</p> </div> {% endfor %} </body> revistaPresei_detail.html <html> <head> <title>Revista Presei Detail</title> </head> <body> <div> {% if revistaPresei.titlulArticol %} <div> {{ revistaPresei.dataArticol }} / {{ revistaPresei.tipArticol }} </div> {% endif %} <h1>{{ revistaPresei.titlulArticol }}</h1> <p>{{ revistaPresei.textArticol }}</p> </div> </body> </html> In case when I try to select an item in the file - revistaPresei_list.html - I recieve the error : UnboundLocalError at /revistaPresei/1/ local variable 'revistaPresei' referenced before … -
Database schema for advance blog with django
i'm still new on programming but i have some knowladge about html php mysql python and django, i need some refrence on design a database schema for Blog, im using python and django as my main framework. here my database schame for creating a blog, i need help to work and completing my frist serius blog programming langgue what i want i want to create a blog looklike wordpress. table catagory : categoryID,createdate,modifieddate,createby,modifiedby,category,description,slug,image table tag : tagID, createdate, modifieddate, createby, modifiedby, tag, description, slug table post : postID, createdate, modifieddate, createby, modifiedby, title, content, description, slug, image, commentstatusONof, table postcategorytag : postcategorytagID, posID, categoryID, TagID table comment : commentID, createdate, name, comment, email table postComment ; postcommentID, postID,CommentID Is any thing shuld i add , or please share your database schema for blog .