Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to obtain dicts key and values in django template
I have a dictionary: {'m': 'm', 'c': None, 's': None, 'n': None, 'a': 'a', 'x': None, 'b': None, 'l': None, 'u': None, 'o': 'o', 'q': None, 'i': None, 'f': None, 'z': None, 'e': None, 't': 't', 'h': None, 'y': None, 'v': None, 'p': None, 'k': None, 'g': None} I'd like to hand the key value pairs that have the value None differently than the key value pairs that have the letters. I have been struggling to figure this out so any help is greatly appreciated! Heres what I have so far for the template <table align="center" cellpadding="4px"> <tr> {% for key in index_display.key() %} {% if index_display[key] = None %} <td><a href="">{{ key }}</a></td> <td id="partners_nav_bracket">|</td> {% else %} <td><a href="{{ value }}">{{ key }}</a></td> <td id="partners_nav_bracket">|</td> {% endif %} {% endfor %} </tr> </table> This however throw an error: Could not parse the remainder: '()' from 'index_display.key()' -
How to ensure Django model saves before Celery task execution?
I have a Django 1.11 + MySQL + Celery 4.1 project where a view creates a new user record, and then kicks off a Celery task to perform additional long-running actions in relation to it. The typical problem in this case is ensuring that the user creation is committed to the database before the Celery task executes. Otherwise, there's a race condition, and the task may try and access a record that doesn't exit if it executes before the transaction commits. The way I had learned to fix this was to always wrap the record creation in a manual transaction or atomic block, and then trigger the Celery task after that. e.g. def create_user(): with transaction.atomic(): user = User.objects.create(username='blah') mytask.apply_async(args=[user.id]) @task def mytask(user_id): user = User.objects.get(id=user_id) do_stuff(user) However, I still occasionally see the error DoesNotExist: User matching query does not exist in my Celery worker logs, implying my task is sometimes executing before the user record gets committed. Is this not the correct strategy or am I not implementing it correctly? -
validation django model (BaseProduct)
I am trying to validate this model, but I am struct with that so, can someone please pick it up and help me out I need to validate CharFiled, DecimalField and ImageField models.py class BaseProduct(models.Model): PRODUCT_TYPE = ( ('normal', 'Normal'), ('combo', 'Combo'), ) id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) type = models.CharField(max_length=200], choices=PRODUCT_TYPE, blank=True, default='normal', help_text='Product availability') price = models.DecimalField(max_digits=6, decimal_places=2, default="") image = models.ImageField(upload_to='image/product/', blank="True") class Meta: verbose_name = "product" def __str__(self): return '%s, %s, %s' % (self.name, self.type, self.price) -
Change rendering of a particular CharField in Django
I have a model BankAccount. BankAccount model contains CharField IBAN which is a International Bank Account Number. I use {{ bank_account.IBAN }} in multiple templates. It's stored as a string without spaces but I want to change it's template rendering such that every 4 characters are followed by zero. SK121234123412341234 will be rendered as SK12 1234 1234 1234 1234 I could probably create some TemplateTag or TemplateFilter but I'm curious if there is a way to change it in BankAccount model. For example create my own IBANField (overriding CharField) so I don't have to surrounding IBAN variable by tags or filters. class BankAccount(models.Model): IBAN = models.CharField(max_length=40, ... ) ... Didn't find rendering methods here: https://docs.djangoproject.com/en/1.11/howto/custom-model-fields/ -
django channels working in runserver but "Still in CONNECTING " & "ERR_CONNECTION_TIMED_OUT" in production, probably related to SSL
I am following "getting started" in the django channel docs as well as "django channels form the ground up" tutorial in the django, using REDIS, NGINX and GUNICORN on digital ocean. Based on browser console errors, I modified command to wss to test in browser: socket = new WebSocket("wss://" + window.location.host + ":8001/chat"); Then the rest copied: socket.onopen = function() { socket.send("hello world"); } // Call onopen directly if socket is already open if (socket.readyState == WebSocket.OPEN) socket.onopen(); The terminal response to runserver 0.0.0.0:8000 : System check identified no issues (0 silenced). October 30, 2017 - 10:40:10 Django version 1.11, using settings 'dojos.settings' Starting Channels development server at http://0.0.0.0:8000/ Channel layer default (channels_panel.apps.DebugChannelLayer) Quit the server with CONTROL-C. 2017-10-30 10:40:10,203 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-10-30 10:40:10,205 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-10-30 10:40:10,206 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-10-30 10:40:10,208 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2017-10-30 10:40:10,208 - INFO - server - Using busy-loop synchronous mode on channel layer 2017-10-30 10:40:10,209 - INFO - server - Listening … -
lazy reference: doesn't provide model user?
Currently I'm using Django 1.11 and Python 3.6. I'm attempting to create a custom user model with a new application that authenticates with LDAP, but i'm greeted with the following error message. raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'accounts.user', but app 'accounts' doesn't provide model 'user'. Settings.py Installed Apps, Auth Backends, and Auth_User Model: INSTALLED_APPS = [ 'django_python3_ldap', 'django_extensions', 'django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', ] AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) AUTH_USER_MODEL = "accounts.User" Admin.py: from django.contrib import admin from django.conf import settings from .models import User # Register your models here. admin.site.register(User) Below is my models.py: 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.forms import ModelForm class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=25, 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) USERNAME_FIELD = "username" -
Python calendar.month_name How to Skip 0-index
So I am trying to use the Python calendar API to loop through the months of the year. Let's say the current month is January (month "1"). If I do calendar.month_name[1-1] (A month before January), the result I get is an empty string "" - seemingly because month "0" doesn't exist. However, if I do calendar.month_name[1-2], the resulting -1 value leads to December being returned. So my question is how do I get a month_name[] parameter of 0 to return the month before it? -
is there any implementation for a field datetime-range with Django and Mysql?
I need create a new Field in my DB class Driver(models.Model): name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) licence_date = models.DatetimeFieldRange(blank=True , null=True) In this field I going to save two dates( start - end) thanks -
Django: How to scale system with highthrought request?
I'm going to design an analysis system as Google analytic. I want use Django for webserver and front end. But I really need a high throughput system, with thousands of requests per second and respond in 10-15 milisecond. I'm not experience for do that. So please help me to make clear something: 1) Should we use kafka for handle incoming request? I just use for weblog, so I just one topic for pub/sub. So will kafka help scale my system? How about if I just build kafka on standalone server? Please give me idea about kafka. 2) Without kafka, could we have any other solutions? Please help or sharing any idea that you know. Thanks & Best Regards, Phuong Hoang