Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view to display objects by user to visitor
I created an app that allows registered users to create products using a form. Each registered user has a profile page displaying their products, that only they can see when logged in. I want to create a view that will allow an unregistered user to view products by any user by click on a username. How do I do that? -
django-cors-headers Error occurred while trying to proxy request ...?
i'm using python3.6 and django-cors-headers proxy test page,but get the error, about app/home/productDetail/2(single goods detail) proxy error: [HPM] Error occurred while trying to proxy request /media/goods/images/2_20170719161435_381.jpg from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/ap i/errors.html#errors_common_system_errors) [HPM] Error occurred while trying to proxy request /media/goods/images/2_20170719161414_628.jpg from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/ap i/errors.html#errors_common_system_errors) [HPM] Error occurred while trying to proxy request /media/goods/images/2_20170719161405_249.jpg from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/ap i/errors.html#errors_common_system_errors) [HPM] Error occurred while trying to proxy request /media/goods/images/2_20170719161405_249.jpg from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/ap i/errors.html#errors_common_system_errors) [HPM] Error occurred while trying to proxy request /favicon.ico from localhost:8080 to http://shop.xxxx.com:1234 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_syst em_errors) in the error, three image is saved at my project images/2_20170719161405_249.jpg images/2_20170719161414_628.jpg images/2_20170719161435_381.jpg why proxy return Error occurred while trying to proxy request ...? app/home/productDetail/2 and django-cors-headers settings is correct. -
jsonschema library -- schema is not valid?
I am using the jsonschema library (http://python-jsonschema.readthedocs.io/en/latest/validate/) in my Django application for server-side validation and am trying to do server-side validation of JSON with a provided schema. However, I get the error that the schema "is not valid under any of the given schemas." Here is my schema (it is the "scores_ap" property of the "schema" property of the class): class JSONListFieldSchemas: """ Schemas for all the JSON List Fields. Each key represents the field name. """ schema = { "scores_ap": { "$schema": "http://json-schema.org/draft-06/schema#", "title": "AP Scores", "type": "array", "items": { "type": "object", "properties": { "exam": { "type": "string" }, "score": { "type": "integer", "minimum": "1", "maximum": "5", "required": False } } } } } I am getting this error: {'type': 'object', 'properties': {'score': {'minimum': '1', 'type': 'integer', 'ma ximum': '5', 'required': False}, 'exam': {'type': 'string'}}} is not valid under a ny of the given schemas Failed validating u'anyOf' in schema[u'properties'][u'items']: {u'anyOf': [{u'$ref': u'#'}, {u'$ref': u'#/definitions/schemaArray'}], u'default': {}} On instance[u'items']: {'properties': {'exam': {'type': 'string'}, 'score': {'maximum': '5', 'minimum': '1', 'required': False, 'type': 'integer'}}, 'type': 'object'} I am using the schema as follows: from jsonschema import validate from .schemas import JSONListFieldSchemas raw_value = [{"score": 1, "exam": "a"}] validate(raw_value, JSONListFieldSchemas.schema['scores_ap']) -
django serializer split string and save to model
I have model structured like this - class BadKeywords(models.Model): bad_keyword = models.CharField(max_length=200) class Meta: db_table = "bad_keywords" if the method is post I get the string containing commas for eg.- hello, hi, hey. Now I want to split that string with the comma and save an individual item to model using serializer. -
Django Rest Framework foreign key nesting
I am trying to nest my Users table inside my Relationships table. So instead of this: [ { "user": 1, "related_user": 2, "relationship": "followed_by" } ] I am trying to get this: [ { "user": { "username": "user1", "name": "User 1", "email": "bla", "phone": "bla", "date_joined": "2017-11-01T21:34:13.101256Z" }, "related_user": { "username": "user2", "name": "User 2", "email": "bla", "phone": "bla", "date_joined": "2017-11-01T21:34:13.101256Z" }, "relationship": "followed_by" } ] I looked up tutorials and I tried adding serializers.RelatedField , UserSerializer(many=true, read-only=true) etc. but nothing worked Models.py class User(models.Model): username = models.CharField(max_length=255) name = models.CharField(max_length=255) email = models.CharField(max_length=255) phone = models.CharField(max_length=255) date_joined = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return str(self.pk) + ", " + self.username RELATIONSHIP_CHOICE = [ ("follows", "follows"), ("followed_by", "followed_by"), ("none", "none"), ] class Relationship(models.Model): user = models.ForeignKey(User, related_name="primary_user", null=True) related_user = models.ForeignKey(User, related_name="related_user", null=True) relationship = models.CharField(max_length=40, choices=RELATIONSHIP_CHOICE, default=RELATIONSHIP_CHOICE[0]) Serializers.py from rest_framework import serializers from . import models class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ( 'username', 'name', 'email', 'phone', 'date_joined', ) class RelationshipSerializer(serializers.ModelSerializer): related_user = UserSerializer(many=True) class Meta: model = models.Relationship fields = ( 'user', 'related_user', 'relationship', 'related_user' ) I tried to add related user to my serializer but it didnt work. I am getting an error: 'User' object … -
Is it accurate to say that Python/Django is more explicit than Ruby/Rails in how the components are constructed and connected together?
I've learned quite a bit with Ruby/Rails and am now venturing into learning Python/Django. What I've noticed so far is that I see the connections more clearly with Django than I did with Rails. In Rails, that magic that it has under the hood seems awesome, stuff just works....but I don't know exactly how. With Django, I have to be much more verbose but in having to write things out, I feel I understand the structure and concepts better. I haven't gone deep into Django just yet, so maybe I will hit the same roadblocks with it in the future. -
javascript loop over .onclick and query
So this results in the last element having the onclick function. Nothing else works. I tried to follow previous answers by wrapping i in () but that didn't seem to do anything... function waitForLoad(id, callback){ var timer = setInterval(function(){ if(document.getElementById(id)){ clearInterval(timer); callback(); } }, 100); } // to skip the LocationSet and LocationName, because we want to reuse our old Location ref = new Firebase("https://iplus1app.firebaseio.com/"); userLocs = ref.child("users/{{ user.username }}/locations"); // create the button function to redirect for each Location that exists userLocs.once("value", function(snapshot) { var keys = Object.keys(snapshot.val()) for (i = 0; i < snapshot.numChildren(); i++) { var locationKey = keys[i] //var locationKey = Object.keys(snapshot.val()[keys[i]]) var nickName = snapshot.val()[locationKey]['name'] locLat = snapshot.val()[locationKey]['position']['lat'] locLng = snapshot.val()[locationKey]['position']['lng'] locNick = snapshot.val()[locationKey]['name'] waitForLoad(nickName, function(){ document.getElementById(nickName).onclick = (function(i) { return function (i) { tempRef = ref.child("users/{{ user.username }}/temp_location"); tempRef.set( { position: { lat: locLat, lng: locLng }, name: locNick }) location.href = "{% url 'tutorLocationActivities' %}"; } })(i); }); } }) -
AttributeError: module Django.contrib.auth.views has no attribute
In my Django app useraccounts, I created a Sign-Up form and a model for my Sign-up. However, when I went to run python manage.py makemigrations, I encounter the error: AttributeError: module Django.contrib.auth.views has no attribute 'registration'. Secondly, am I coding the SignUpForm in forms.py correctly? I did not want to use the User model in models because it would request username and I didn't want my website to ask for a username. Here is my code: models.py from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User class UserProfile(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.EmailField(max_length=150) birth_date = models.DateField() password = models.CharField(max_length=150) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) instance.profile.save() forms.py from django.forms import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from useraccounts.models import UserProfile class SignUpForm(UserCreationForm): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password1', 'password2', ) views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from useraccounts.forms import SignUpForm # Create your views here. def home(request): return render(request, 'useraccounts/home.html') def login(request): return render(request, 'useraccounts/login.html') def registration(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.birth_date = … -
Django. Access primary key/id value during creation of a record
For my model I use default auto-incremented PrimaryKey/id field. I also have a field called serialNumber which according to design should reference id and generate it's own value based on id value. For example if id is 1234 then serialNumber field should be a string '00001234'. class MyModel(models.Model): ... serialNumber = models.TextField(max_length=8) ... I have no trouble updating serialNumber after the creation of record in DB, but my specific case requires serialNumber to be set together with object initial creation because right after it I return the record via REST API. I tried using signals, but pre_save returns None @receiver(pre_save, sender=MyModel) def my_pre_save(sender, instance, **kwargs): print(instance.id) On the other hand if I do: @receiver(post_save, sender=MyModel) def my_post_save(sender, instance, **kwargs): print(instance.id) I receive the value for id but it's too late because right after .save() my REST API returns response with created object and I don't want to add code that manages serialNumber to serializer. Overriding .save() method for MyModel didn't work either: def save(self, *args, **kwargs): print(self.id) super(MyModel, self).save(*args, **kwargs) Id field still returns None. Anyone has an idea how to access id value during initial creation of a record? -
Using a django model as a field for another model?
I have been tasked with creating Django Models for a hypothetical apartment booking application. My question is: can I use a model that I've defined, as a field in another model? For example, I will have one model called "Listing" that represents an apartment being listed. class Listing(models.Model): address = models.IntegerField() owner = models.CharField(max_length=256) duration = models.DurationField() price= models.IntegerField() I also want to have a "Booking" model that represents an apartment once someone has booked it. It will have the exact same info as a Listing, with the addition of the username of the person who booked it. So can I have my Booking model use Listing as a field? And then just have one extra field for the booker's username. Any other tips/critiques are highly appreciated as I am a complete beginner at Django. -
Django migrations without db table rewrites
I have a huge table and I don't want to cause a table rewrite or so. so in my model I first created a field like this: field = models.IntegerField(null=True) then executed makemigrations, then changed my field to field = models.IntegerField(null=False, default=0) executed makemigrations again and second migration looks like this: migrations.AlterField( model_name='game', name='field', field=models.IntegerField(default=0), ), Would this cause a table rewrite? I know I will still have Null values in the previous rows but I want to make this work for the next rows without causing DB downtime. My db is PostgreSQL. and first migration looks like this, if helpful: migrations.AddField( model_name='game', name='field', field=models.IntegerField(null=True), ), -
django OnetoOneField in database
how one-to-one field in django reflected in database? I have two model: Neighbor and Neighbor_Info which has one-to-one field connection to Neighbor. But In the database I don't see any reference field relation between this two table So I wonder how the one-to-one relation reflected on database? (I use postgresql) -
django registration redux error
I'm using django registration redux in my django project, the problem happened in mapping urls, when you visit: http://127.0.0.1:8000/accounts/register/ it redirect me into : http://127.0.0.1:8000/accounts/profile/ with error message : Using the URLconf defined in trydjango18.urls, Django tried these URL patterns, in this order: ^$ [name='home'] ^contact$ [name='contact'] ^about$ [name='about'] ^admin/ ^accounts/ ^activate/complete/$[name='registration_activation_complete'] ^accounts/ ^activate/resend/$[name='registration_resend_activation'] ^accounts/ ^activate/(P<activation_key>\w+)/$[name='registration_activate'] ^accounts/ ^register/complete/$ [name='registration_complete'] ^accounts/ ^register/closed/$ [name='registration_disallowed'] ^accounts/ ^register/$ [name='registration_register'] ^accounts/ ^login/$ [name='auth_login'] ^accounts/ ^logout/$ [name='auth_logout'] ^accounts/ ^password/change/$ [name='auth_password_change'] ^accounts/ ^password/change/done/$[name='auth_password_change_done'] ^accounts/ ^password/reset/$ [name='auth_password_reset'] ^accounts/ ^password/reset/complete/$[name='auth_password_reset_complete'] ^accounts/ ^password/reset/done/$ [name='auth_password_reset_done'] ^accounts/ ^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(? P<token>.+)/$ [name='auth_password_reset_confirm'] ^static\/(?P<path>.*)$ ^media\/(?P<path>.*)$ The current URL, accounts/profile/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. here is my code for settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'registration', #should be immediately above 'django.contrib.auth' 'django.contrib.auth', 'crispy_forms', 'newsletter',) and ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True here is my code for urls.py: urlpatterns = [ url(r'^$', 'newsletter.views.home', name='home'), url(r'^contact$', 'newsletter.views.contact', name='contact'), url(r'^about$','trydjango18.views.about',name='about'), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('registration.backends.default.urls')),] -
django async task using django q task and redis server
i try to follow this tutorial for django q async tasks and i have install redis from this video on windows 10 (i have also rabbitqm server) I don't get some error but my function don't execute i don't get anything from my function i think the problem is on redis server config. any idea ? here the code : settings.py INSTALLED_APPS = [..]+'django_q', # redis defaults Q_CLUSTER = { 'redis': { 'host': '127.0.0.1', 'port': 6379, 'db': 0, 'password': None, 'socket_timeout': None, 'charset': 'utf-8', 'errors': 'strict', 'unix_socket_path': None } } tasks.py import math import sys def add(n1,n2): test=n1/n2 return test views.py def app_details(request,slug): if request.method == "POST": test = request.POST.get('iy') t1=test t2=test*1542 async('tasks.saga',t1,t2) return render(request, 'page.html',.... that message I get without error in pycharm : 23:54:27 [Q] INFO Enqueued 3 redis cmd : redis command server : -
Overwrite django view with custom context (Django 1.11, Viewflow)
I have a Django 1.11 project using Viewflow - https://github.com/viewflow/viewflow - that I've incorporated. It's been very helpful, but a lot of stuff is kind of "magic", and being my first serious Django project, I'm running into an issue I'm not sure of how to solve, or the best way. I have a generic template that expects a lot of context. I have a function that adds this context to all of my views: def add_general_context(context, MOC, MOC_enabled_fields = (), MOC_status = None): context['MOC'] = MOC context['current_date'] = timezone.now().strftime("%D") context['MOC_form'] = forms.MOCForm(prefix="MOC_form", MOC_enabled_fields=MOC_enabled_fields, instance=MOC) context['MOCAttachments'] = models.MOCAttachment.objects.filter(MOC=MOC) context['MOCAttachment_form'] = forms.MOCAttachmentForm(prefix="MOCAttachment_form") context['MOCApprovals'] = models.MOCApproval.objects.filter(MOC=MOC) context['MOCTasks'] = models.MOCTask.objects.filter(MOC=MOC) context['MOC_status'] = MOC_status context['MOCConversation'] = models.MOCConversation.objects.filter(MOC=MOC) # Add comments to the conversation for conversation in context['MOCConversation']: conversation.comments = models.MOCComment.objects.filter(conversation=conversation) context['MOCComment_form'] = forms.MOCCommentForm(MOC=MOC) context['MOCCommentReply_form'] = forms.MOCCommentReplyForm() I basically need to add this context to a view that is inside viewflow - namely, AssignTaskView - https://github.com/viewflow/viewflow/blob/f50accb3cde5d53f1d4db0debf5936867712c3bd/viewflow/flow/views/task.py#L109 I've tried a few things to overwrite/add to the context, but none seem to work. Attempt 1: Overwrite the URL and use extra_context (SO suggested this) - The issue is that the urls are "magic", my urlpatterns is very simply: from material.frontend import urls as frontend_urls urlpatterns = [ url(r'^MOC/', … -
Render Url dynamically in ReactJS depending on the environment
I am using ReactJS in the front end wherein upon clicking a submit button, it calls 4 apis in dev-environment: ReactDOM.render( <ParameterForm url_schema="http://192.168.99.100/api/v1/var" url_uischema="http://192.168.99.100/api/v1/ui" url_data="http://192.168.99.100/api/v1/data" url_submit="http://192.168.99.100/api/v1/calculated" />, document.getElementById('form') ); I am using docker to run the application locally which has a settings folder with base.py, local.py and production.py. For Production-env, I want the apis to be called something like these: ReactDOM.render( <ParameterForm url_schema="http://xyz:8000/api/v1/var" url_uischema="http://xyz:8000/api/v1/ui" url_data="http://xyz:8000/api/v1/data" url_submit="http://xyz:8000/api/v1/calculated" />, document.getElementById('form') ); I need to know whether is there a way in which these apis can be declared either in local.py or production.py and can be called dynamically in my DOM based on the environment in which I run my app. -
ImageField image_width and image_height auto fill for existing database?
I have an existing database table with an ImageField that already has a bunch of existing registries. I want to add the image_width and image_height on my model but I need something to auto-fill the existing tables with. class ItemImage(models.Model): file = models.ImageField(upload_to=image_directory_path, width_field='image_width', height_field='image_height') image_width = models.IntegerField() image_height = models.IntegerField() I read on the docs that both image_width and image_height get saved automatically when on save(), but the existing images have already been saved. -
Issue deploying django to AWS
I'm trying to deploy my personal website to aws using elastic beanstalk. My website is in django/python. I keep encountering the same issue. Each time I upload the files I get the following error in AWS console: Your requirements.txt is invalid. Snapshot your logs for details. Ok, so I check the logs and from the bits I notice the following: Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 2Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() pip version 7.1.2, however version 9.0.1 is available.You should consider upgrading via the 'pip install --upgrade pip' command. I googled and found many having this issue. They suggested updating pip and installing dependencies manually. So I logged into the server and started by updating pip. Boom, another issue. After updating to pip 9.0.1 when I type pip --version I get the following: -bash: /usr/bin/pip: no such file or directory I can't seem to move on with this. I thought elastic beanstalk is supposed to be easy but I keep getting more and more stuff to do. I'm at my wits end after all the testing today. Could I ask for any help with this? What should … -
syntax for django queryset exists
Suppose I have Django models like this: class Foo(Model): bar = ForeignKey(Bar, related_name="foos") class Bar(Model): dummy = models.CharField(max_length=128, null=False) I know that I can get all Foo object for a bar using bar.foos.all(). Suppose I just want to see if a bar has any Foos. What is the syntax for this: Option 1: bar.foos.exist() Option 2: bar.foos.all().exists() Which of the above is correct? Every example I have seen of exists() uses filter() so I'm not sure what to do if I don't need to filter. -
Set up Django DiscoverRunner to always recreate database on testing with radish
I am using radish bdd with selenium to test my django app, however sometimes django ask to delete database because it's already exists in database. here's my terrain.py: import os import django from django.test.runner import DiscoverRunner from django.test import LiveServerTestCase from radish import before, after from selenium import webdriver os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tangorblog.settings.features') BASE_URL = os.environ.get('BASE_URL', 'http://localhost:8000') @before.each_scenario def setup_django_test(scenario): django.setup() scenario.context.test_runner = DiscoverRunner() scenario.context.test_runner.setup_test_environment() scenario.context.old_db_config =\ scenario.context.test_runner.setup_databases() scenario.context.base_url = BASE_URL scenario.context.test_case = LiveServerTestCase() scenario.context.test_case.setUpClass() scenario.context.browser = webdriver.Chrome() @after.each_scenario def teardown_django(scenario): scenario.context.browser.quit() scenario.context.test_case.tearDownClass() del scenario.context.test_case scenario.context.test_runner.teardown_databases( scenario.context.old_db_config) scenario.context.test_runner.teardown_test_environment() I think that, I can somehow could alter this on scenario.context.old_db_config =\ scenario.context.test_runner.setup_databases() But I don't know how. Any help? -
ModuleNotFoundError: No module named 'my_app'
I am trying to make a custom manager that will run a function from another file in a sibling directory, but this error keeps popping up. I have tried: 1) Adding the module to my PYTHONPATH. 2) Adding init.py files. 3) Appending the module to sys.path. I am using Python3 and Django. /app --- /managers -------/manager.py <--- /*importing code here*/ --- /my_app -------/request.py <--- /*code to be imported*/ None of these have worked. -
Adding Domain\ to username
I'd like for my login page to have the user name function as it is, but for the record that is written to the database when a user authenticates with LDAP i'd like to have Domain\username, the domain will never change so I could force it without looking it up. How would I go about doing this? Below is my from __future__ import unicode_literals from django.utils import timezone from django.contrib.auth.models import (AbstractBaseUser,PermissionsMixin) from django.db import models from django.conf import settings from django.forms import ModelForm class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=7, unique=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) facility = models.CharField(max_length=140) jobdescription = models.CharField(max_length=140) positiondescription = models.CharField(max_length=140) coid = models.CharField(max_length=5) streetaddress = models.CharField(max_length=140) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" -
Django model.objects.all() gives list index out of range upon calling it normally
So im currently working on a private project using Django and when I try loading the page for the teams it just says "list index out of range" and im using object.all() to fetch every team from the model Team, Inside the template im using a for loop to post each team on the page I've been trying using order_by() and first() but they didn't either seem to help. My traceback is here http://dpaste.com/2S4Q7FY What am I doing wrong here what should I change The view def teams(request): teams = Team.objects.all() context = { 'teams': teams, } if request.user.is_authenticated(): logged_in_user = get_object_or_404(User, pk=request.user.pk) context['logged_in_user'] = logged_in_user return render(request, 'teams.html', context) Model Team class Team(models.Model): name = models.CharField(max_length=16) logo = models.ImageField(upload_to='teams/avatars', default='static/img/userpreload.png') background = models.ImageField(upload_to='teams/backgrounds', default='static/img/userpreload.png') description = models.TextField(blank=True) people_needed = models.PositiveSmallIntegerField() members = models.ManyToManyField(User, through='TeamMembership') accepts_applications = models.BooleanField() @property def teamleaders_listable(self): leaders = self.members.filter(teammembership__leader=True) string = leaders[0].extendeduser.nickname for leader in leaders[1:]: string += ", " + leader.extendeduser.nickname return string @property def multiple_teamleaders(self): if len(self.members.filter(teammembership__leader=True)) > 1: return True else: return False def __str__(self): return self.name -
python code optimization: creating dynamic variables in a loop inside a class for django / wagtail
I am trying to optimize internationalization for my django (wagtail) site. I have a model which creates fields for the CMS that allow translation to different language: from internationalization.translatedfield import TranslatedField class BlogPage(Page): body_en = RichTextField(blank=True) body_fr = RichTextField(blank=True) body = TranslatedField( 'body_en', 'body_fr' ) content_panels = Page.content_panels + [ FieldPanel('body_en', classname="full"), FieldPanel('body_fr', classname="full"), ] The translatedfield import just allows us to use a single variable name in our django template ('body'): from django.utils import translation class TranslatedField(object): def __init__(self, en_field, fr_field): self.en_field = en_field self.fr_field = fr_field def __get__(self, instance, owner): if translation.get_language() == 'fr': return getattr(instance, self.fr_field) else: return getattr(instance, self.en_field) And in the template: {{ page.body|richtext }} All this allows the CMS user to input text for 'body_fr' and 'body_en' fields, and, based on the URL the visitor was at, output either the french or english translations (e.g. site.com/en/blog or site.com/fr/blog). The problem is there could be potentially dozens of languages and dozens of fields, so you can see how this model could get very large. So what I'd like to do is dynamically create those self.en_fields and .fr fields in a loop. So the TranslatedField import might look something like: class TranslatedField(object): def __init__(self, field, languages): … -
How to modify the author choices field in my generic CreateView with authors(fk) only from the current user?
This is my code, i have read the documentations and it seems this method is the right way, i get no errors but i see no results. Can somebody help me in what i am doing wrong? class BookCreate(LoginRequiredMixin, CreateView): model = Book fields = ['title', 'isbn', 'year', 'author', 'publisher'] def form_valid(self, form): form.instance.owner = self.request.user return super(BookCreate, self).form_valid(form) def form_valid(self, form): b = Book.objects.all form.instance.author = ModelChoiceField(queryset=b.author_set.filter(owner=self.request.user)) return super(BookCreate, self).form_valid(form)