Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Django LANGUAGE_CODE = 'en' but displays 'fr'?
I wrote my templates in ENGLISH by using {% trans %} inside. I decided to translate that into French, so I put that in the settings : MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', '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', ] LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ) LANGUAGE_CODE = 'fr' LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True Then I used makemessages and compilemessages to generated translated strings. And this worked fine ! My website is in French. But now I would like to get back my site to be in English, So I just change LANGUAGE_CODE to : LANGUAGE_CODE = 'en' But my website is still in French ! Even the django-debug-bar is still in French. The only workaround I found is to comment out the french in LANGUAGES : LANGUAGES = ( ('en', _('English')), # ('fr', _('French')), ) I tried to move the localMiddleware in the list : no success, I tried to clear cookies : no success. I generated english .mo and .po files : no success I tried LANGUAGE_CODE = 'en-us' : no success Why LANGUAGE_CODE = 'en' does not work ? -
password_reset_confirm '{'uidb64': b'MQ', 'token': '4qs-5a42c81174a10304f79c'}' not found. 0 pattern(s) tried: []
I am attempting create the password_reset_confirm view for my application. However I keep getting this error : Here is my code : app urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout, password_reset, password_reset_done, password_reset_confirm, password_reset_confirm urlpatterns = [ url(r'^$', views.vedic_view, name = 'vedic_home_view'), url(r'^login/$', login, {'template_name' : 'exist/login.html'}, name = 'login'), url(r'^logout/$', logout, {'template_name' : 'exist/logout.html'}, name = 'logout'), url(r'^register/$', views.register_view, name = 'register'), url(r'^profile/$', views.view_profile, name = 'view_profile'), url(r'^profile/edit/$', views.edit_profile, name = 'edit_profile'), url(r'^change-password/$', views.change_password, name = 'change_password'), url(r'^reset-password/$', password_reset, { 'template_name' : 'exist/reset_password.html', 'post_reset_redirect': 'exist:password_reset_done' }, name = 'reset_password'), url(r'^reset-password/done/$', password_reset_done, name = 'password_reset_done'), url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', password_reset_confirm, {'post_reset_redirect': 'exist:password_reset_complete'}, name = 'password_reset_confirm') ] It seems the namespace variable in the main urls.py is affecting the url mapping for the password_reset_confirm project urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) from django.conf.urls import include from django.views.generic import RedirectView urlpatterns += [ url(r'^exist/', include('exist.urls', namespace = 'exist' )), url(r'^$', RedirectView.as_view(url='/exist/', permanent=True)), ] -
Creating a OneToOne Relationship between 2 models(forms) in the same view
I am building a signup page. I am using the default User model and a new model called UserInfo for additional user details. I need to establish a OneToOne relationship between the 2 models. To build the signup page, I made a form for each model and put them into the same signup view. My question is, how to I set user(the OneToOneField) in UserInfo to the User that is being created in the same view UserInfo is created? If you look in my views.py below, immediately after I saved User's form(signup_form), I tried a few things like.. user2.user = User.objects.get(pk=pk) - doesn't seem to work user2.user = request.user - doesn't work because request.user is an anonymous user in this case user2.user = user - didn't work models.py: class UserInfo(models.Model): TITLE = ( ('Salesperson', 'Salesperson'), ('Sales Representative', 'Sales Representative'), ('Broker', 'Broker'), ('Broker of Record', 'Broker of Record'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) preferred_email = models.EmailField() office_phone_number = models.CharField(max_length=10) brokerage_of_agent = models.CharField(max_length=50) agent_title = models.CharField(max_length=20, choices=TITLE) def __str__(self): return self.preferred_email forms.py: class SignupForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = User fields = ('username', 'email', 'password1', 'password2') class UserInfoForm(forms.ModelForm): class Meta: model = UserInfo fields = ['preferred_email', 'office_phone_number', 'brokerage_of_agent', 'agent_title'] … -
Django Translation appears to not be using translations
I am trying to set-up template translation inside of Django templates and I am bit puzzled by why it's not working. I've followed the docs but I imagine I am missing one small thing that is tripping this up. I've done the following: USE_I18N = True LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale/'),) LANGUAGE_CODE = 'en-us' LANGUAGES = [('en-us', _('English - US')), ('es', _('Spanish'))] Added {% load i18n %} to the top of the templates Added {% trans %} tags into the templates. Ran ./manage.py makemessages -l es and got the .po file in the locale path so I know it's finding all the template tags. Ran ./manage.py compilemessages and got the .mo file in the locale path I added these two lines to a template to make sure the language code was being set. {% get_current_language as LANGUAGE_CODE %} <h2>Current Language Code: {{ LANGUAGE_CODE }}</h2> I am then able to see that the correct language code is being set. I am also using this tutorial's template to set the language: http://joaoventura.net/blog/2016/django-translation-4/ With that I know a translation is being applied because the selection menu in the form updates the language (in the code side). I assume this is using locale files inside … -
Writing a Django unit test for a function with a HttpResponse
I'm writing a unit test to check to see if the telecasts key is in the JSON data returned in this function (in my views.py): def my_function(request, date1='', date2='', date3='', date4=''): ::some other functions...:: return HttpResponse(data, content_type='application/json') As you see, the JSON I want to check is sent via a HttpResponse as the variable data This JSON data, when received on the front-end, is structured like: {"records": [ {"program": "WWE ENTERTAINMENT", "telecasts": 201,...}, {..} ] So this is how I'm trying to write the unit test, but I'm getting an error when I run it: def my_test(self): """Data returned has telecasts key""" request = self.client.get( '/apps/myapp/2014-08-01/2015-06-10/2016-01-13/2016-03-23/', {dictionary of optional parameters} ) force_authenticate(request, user=self.user) response = my_function( request, '2014-08-01', '2015-06-10', '2016-01-13', '2016-03-23' ) telecasts_check = response['records'][0]['telecasts'] self.assertRaises(KeyError, lambda: telecasts_check) -
How to check if that which is iterated upon is the last key/value in a dict? (probably needs to be done in django template)
The desired outcome is a navigation that look like so: A | B | C | D | E | ... | X | Y | Z Note that both A and Z do not have the pipe on the outsides. This is the template I have currently. <section id="partners_nav"> <div class="row"> <table align="center" cellpadding="4px"> <tr> {% for key, value in index.items %} {% if key in index|last %} {% if value == None %} <td>{{ key }}</td> <td id="partners_nav_bracket">|</td> {% else %} <td><a href="{{ value }}">{{ key }}</a></td> <td id="partners_nav_bracket">|</td> {% endif %} {% else %} {% if value == None %} <td>{{ key }}</td> <td id="partners_nav_bracket">|</td> {% else %} <td><a href="{{ value }}">{{ key }}</a></td> <td id="partners_nav_bracket">|</td> {% endif %} {% endif %} {% endfor %} </tr> </table> </div> The line {% if key in index|last %} is where i'm attempting to check if it is the last item in the iteration. This does not produce any errors.Yet does not remove the pipe to the right of the letter Z. Note: Inside of index is an ordered dictionary which has a key for every letter in the alphabet. And some of these keys have values that are also … -
Update User error with django api rest framework
i need your help plase! it`s very hurry!!!!!! I can`t update users because django give me this error in postman: AttributeError at /profesionales/ Got AttributeError when attempting to get a value for field user on serializer ProfesionalesSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'user'. Request Method: PUT Request URL: http://127.0.0.1:8000/profesionales/ Django Version: 1.11.6 Python Executable: C:\Users\Ismael\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.3 Here my code!!!: VIEW.PY #Listar todos los profesionales o crear uno #profesionales/ class ProfesionalesList(APIView): def get_object(self, pk): try: return User.objects.get(username=pk) except User.DoesNotExist: raise Http404 def get(self, request ): usuarios = Profesionales.objects.all() usuarioSerializer = ProfesionalesSerializer(usuarios, many=True) return Response(usuarioSerializer.data) def post(self, request): profesionalSerializer = ProfesionalesSerializer(data=request.data) if profesionalSerializer.is_valid(): profesionalSerializer.save() return Response(profesionalSerializer.data, status=status.HTTP_201_CREATED) else: return Response(profesionalSerializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request, *args, **kwargs): instance = self.get_object(request.data.get('user').get('username')) profesionalSerializer = ProfesionalesSerializer(instance, data=request.data) if profesionalSerializer.is_valid(): profesionalSerializer.save() return Response(profesionalSerializer.data, status=status.HTTP_201_CREATED) else: return Response(profesionalSerializer.errors, status=status.HTTP_400_BAD_REQUEST) SERIALIZERS.PY class UserSerializer(serializers.Serializer): username = serializers.CharField() first_name = serializers.CharField(allow_blank=True) last_name = serializers.CharField(allow_blank=True) email = serializers.CharField(allow_blank=True) class Meta: fields = ('username', 'first_name', 'last_name', 'email') def create(self, validated_data): user = User.objects.create(**validated_data) return user class ProfesionalesSerializer(serializers.Serializer): user = UserSerializer() numColegiado = serializers.CharField(allow_blank=False) class Meta: fields = ('user', 'numColegiado') … -
Django: GenericForeignKey unit test
I am on django 1.11 and I need to unit test something. I got this message : File "C:\Users\jy95\PycharmProjects\oscareducation\student_collaboration\tests.py", line 49, in testSkills object_id=self.newuser.id ValueError: Cannot query "jy95": Must be "User" instance. My set up def setUp(self): self.settings1 = CollaborativeSettings.objects.create() # un settings par défaut self.settings2 = CollaborativeSettings.objects.create(distance=10) # un settings random self.newuser = User.objects.create(username="jy95") self.student = Student.objects.create(user=self.newuser) """ Le StudentCollaborator associé devrait être crée """ self.founduser = StudentCollaborator.objects.get(user=self.newuser) self.skill_1 = Skill.objects.create(code="B0124", name="Maths", description="Les MATHS") self.skill_2 = Skill.objects.create(code="B0125", name="Logique", description="La Logique") The function where the problem occurrs : def testSkills(self): """ L'étudiant est bon en maths """ SkillHistory.objects.create( skill=self.skill_1, student=self.founduser.user.student, value="acquired", by_who=self.founduser.user, reason="ACQUIS", # n'importe quoi ; juste pour faire en sorte que SkillHistory soi content content_type=ContentType.objects.get_for_model(self.founduser.user), object_id=self.newuser.id ) -
Django Rest Framework how to save a manyToMany with Related Field
I have some problem with Django Rest Framework and manyToMany relation with Related Field. Whenn i list I have a error and when I save, it fill data in database but it cant display the result. My model.py class Product(models.Model): name = models.CharField(max_length=100,unique=True) description = models.TextField() price = models.DecimalField(max_digits=9,decimal_places=3) created = models.DateTimeField(auto_now_add=True) edited = models.DateTimeField(auto_now_add=True) state = models.ForeignKey('ProductState', default=1) tax = models.ForeignKey('Tax') categories = models.ManyToManyField('ProductCategory') class OrderProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) qty = models.IntegerField() tax = models.ForeignKey('Tax') class Order(models.Model): ref = models.CharField(max_length=100,blank=True) created = models.DateTimeField(auto_now_add=True) state = models.ForeignKey('OrderState') user = models.ForeignKey(User) orderproducts = models.ManyToManyField(Product, through='OrderProduct') my serializer.py class OrderProductSerializer(serializers.ModelSerializer): product = ProductSerializer(required=True) class Meta: model = OrderProduct exclude = () read_only_fields = ('order','tax',) def create(self, validated_data): product = validated_data.pop('product') return OrderProduct.objects.create(tax=product['product'].tax, **product) class OrderSerializer(serializers.ModelSerializer): orderproducts = OrderProductSerializer(many=True, required=True) def create(self, validated_data): products = validated_data.pop('orderproduct') order = Order.objects.create(**validated_data) for product in products: op = OrderProduct.objects.create(product=product['product'], tax=product['product'].tax, order=order, qty=product['qty'] ) op.save() order.save() return order; class Meta: model = Order exclude = () read_only_fields = () class ProductSerializer(serializers.ModelSerializer): categories = ProductCategorySerializer(many=True, required=True) tax = TaxSerializer(many=False, required=True) state = OrderStateSerializer(many=False, required=False) class Meta: model = Product exclude = () and my view.py class ClientOrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer … -
Django 'geo_db_type' AttributeError with Multiple Databases
Background I'm using Django with multiple databases: I have a Postgres database and a mysql database (filled with legacy data that I'm slowly converting over to Postgres). I recently brought in GeoDjango (in the form of django.contrib.gis), with the postgis extension for storing lat/lng information as a point. The application itself seems to be running fine. I can access information from the mysql database and the postgres database just fine. I can even leverage the new point field, which means (to me) that the 'gis' stuff is working and configured. Problem The problem occurs when I try to run tests. I get the following error: AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' I believe this is occurring on the mysql database because I first get the prompt stating that the test_db postgress database exists and needs to be dropped and recreated. I enter 'yes', and it does it's thing, then gives me the same prompt about the test_mysql database. When I answer 'yes', I get the error. My legacy app's models don't use any of the new fields; the import is django.db. So I can't figure out why the test thinks that I need geospatial operations on the mysql database. … -
how to get the mutual relationship between users in Django ManyToMany field
Sorry I'm writing this question from mobile so couldn't provide the real code but I have a relationship model with following many to many with related name followers I wanna write a model manager function that returns all mutual relationship that is the people I'm following who happens to be my followers -
Link dependent model classes on same page (Django)
I have these two simple models: class ClassTaxonomy(models.Model): name = models.CharField(max_length = 264) class SubClassTaxonomy(models.Model): name = models.CharField(max_length = 264) class_taxonomy = models.ForeignKey(ClassTaxonomy, related_name = 'taxonomies', on_delete = models.CASCADE) I would want to show on a page that Class instances (A, B,C) are above SubClass instances (AA, BB, CC) somehow as follows: except that I want a correspondence of A to AA, B to BB, etc. In the image, A, B, C are generated through a ListView class ClassTaxonomyListView(ListView): context_object_name = 'class_taxonomy_list' model = models.ClassTaxonomy template_name = 'index/class_taxonomy_list.html' What I cannot figure out is how to link the classes (A, B, C) with the subclasses (AA, BB, CC) in a similar, automated and compact manner. Looking especially for class-based view based solutions, but would not mind other types as long as they can underlie the Class-Subclass dependency. -
Django Custom Template Form and {{nex}}
I'm stuck on creating form, looks like {{ forms.as_p }}. Problem is, that after reading lot's of website's and documentation I still can't understand, how to create custom form with my css class and input fields. I tried this one: action="", method ="post" <div class="form-group"> <input type="text" class="form-control" placeholder="Username" required=""> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Password" required=""> </div> But it doesn't work. What fields, I've missed. Also I have another question: Is it possible to custom "next" variable to redirect after login on my custom page? And how I can do it? -
django reset-password views, NoReverseMatch error and also problems with templates
I need to include password reset function to my app, but always I have NoReverseMatch error. In addition, I can't view my own templates for password reset process. I created templates in registration folder in the same directory with other templates for my app: myapp/templates/registration URLS.PY from django.conf.urls import url, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ ..... url(r'^password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0- 9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), ] I have no custom views for password reset. Should I create views for it? Thanks in advance. -
Login user with API Key tastypie to Angular different port
I'm new to angular and currently using tastypie. I am trying to login user using my current front-end (no angular) login process. When the user logs in, I create an api key. views.py api, create_api = ApiKey.objects.get_or_create(user=user) if create_api: api.save() From there, I have an api.py from django.contrib.auth import get_user_model from django.db import models from django.db.models import signals from tastypie.models import create_api_key User = get_user_model() signals.post_save.connect(create_api_key, sender=User) class MyTable(ModelResource): class Meta: queryset = MyTable.objects.all() resource_name = 'myTable' authorization = ApiKeyAuthentication() list_allowed_methods = ['get', 'post'] def authorized_read_list(self, object_list, bundle): return object_list.filter(user=bundle.request.user) I looked at localhost:8000 using ApiKeyAuthentication I see nothing and checked curl to find it's an anonymous usesr. If I remove i changed to DjangoAuthorization, I see my data. When I go to localhost:4200 where angular is, it says it is an anonymous user for all scenarios. How do I pass my keys to angular? I think I am missing a step somewhere and I am not exactly sure if my thought process is correct. Any help is appreciated. -
Django translation strategy for big textual content
I will use Django translation functions/tags to translate words and small block of text. But I am wondering whether it is relevant to do the same thing for big textual content like "term of service" or "Privacy Policy" pages ? I see 2 ways : 1) use {% blocktrans %} on the whole text, but it will make a lot of data into the gettext database, it may slow down the translation process of all other strings 2) use as many templates as languages, that is to have for the "Privacy Policy" page these kind of template files : privacy_en.html, privacy_fr.html, privacy_de.html... What would be the correct way ? -
Using Django handler404 breaks Wagtail redirects
I have a custom 404 handler that I use for my Django app running the CMS Wagtail. Everything works great with replacing the Django handler404 with a view function of my choosing. Except that it seems to break Wagtails 301 redirect feature. All of the redirects I have now just go to a 404 page. Below is how I am using handler404 in the base app, handler404 = siteapp_views.handler404 -
Django REST ListCreateAPIView Foreign Key
I'm trying to create a new object with a foreign key with django's ListCreateAPIView. The reference to the foreign key is in the url. I tried using lookup_url_kwarg but when I send a json, it still requires me to input an institution views.py class MemorandumCreateView(ListCreateAPIView): # permission_classes = (IsAuthenticated,) queryset = Memorandum.objects.all() lookup_fields = 'institution_id' lookup_url_kwarg = 'institution_id' serializer_class = MemorandumSerializer def get_queryset(self): institution = self.lookup_url_kwarg['institution_id'] return Memorandum.objects.filter(institution=institution) serializers.py class MemorandumSerializer(ModelSerializer): # lookup_fields = 'institution_id' class Meta: model = Memorandum fields = "__all__" urls.py url(r'^(?P<institution_id>(\d+))/memorandums', MemorandumCreateView.as_view()), models.py class Memorandum(Model): MEMORANDUM_CATEGORIES = ( ('MOA', 'Memorandum of Agreement'), ('MOU', 'Memorandum of Understanding') ) AGREEMENT_TYPES = ( ('B', 'Bilateral'), ('M', 'Multilateral') ) institution = ForeignKey(Institution) agreement = CharField(max_length=12, choices=AGREEMENT_TYPES) memorandum_category = CharField(max_length=3, choices=MEMORANDUM_CATEGORIES) memorandum_file = CharField(max_length=512) version_date = DateField() date_effective = DateField() date_expiration = DateField(null=True) college_initiator = CharField(max_length=5, choices=COLLEGES, null=True) -
Django : Unit test with GenericForeignKey
When testing several models, I found this inside one : GenericForeignKey('content_type', 'object_id') How can I make a fake for my unit test since it is not bound to a specific model ? Thanks