Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.11 One-to-Many relationship no related set
So I have two models: class UserData(models.Model): """ Holds basic user data. """ id = models.IntegerField(primary_key=True, editable=False) # id is taken from data. class ConsumptionTimePoint(models.Model): """ Individual consumption time points with a One-to-Many relationship with UserData """ user_data = models.ForeignKey(UserData, on_delete=models.CASCADE) And when I try and test them by creating them both, and their relationship in a test: def test_basic_model_creation(self): user_data_object = UserData.objects.create(id=1) user_data_object.save() consumption_time_point_object = ConsumptionTimePoint.objects.create(user_data=user_data_object) consumption_time_point_object.save() self.assertIsNotNone(consumption_time_point_object.user_data) self.assertEquals(1, len(user_data_object.consumption_time_point_set.all())) I get the following error: AttributeError: 'UserData' object has no attribute 'consumption_time_point_set' But from my understanding that's the correct way to get the set. Have I misnamed something? Or is this a testing issue? -
sort by a value in Pandas column
I groupby my data as follows in Pandas: df.groupby(by=['industry', 'country', 'category'])['category'].count() The DataFrame looks something like this after the groupby: --------------------------------------- Industry | Country | category | --------------------------------------- Oil | Portugal | 0 | 14 1 | 4 None | 7 Germany | 1 | 27 0 | 22 None | 7 Spain | 1 | 12 0 | 1 --------------------------------------- Gas | Ireland | 1 | 2 0 | 11 None | 1 Italy | 0 | 120 1 | 33 Malta | 1 | 3 0 | 4 None | 7 Turkey | 0 | 355 1 | 44 --------------------------------------- However, I would like to sort my data based on the count of a particular Category value. For example, sort it by the count of category value '0' so that the frame looks like below. Please note the sorting based on the count of category '0' (22,14,1) and (355,120,11,4). --------------------------------------- Industry | Country | category | --------------------------------------- Oil | Germany | 1 | 27 0 | 22 None | 7 Portugal | 0 | 14 1 | 4 None | 7 Spain | 1 | 12 0 | 1 --------------------------------------- Gas | Turkey | 0 | 355 1 … -
How to ensure no repeating datas when use django?
background I aim at overing a project which is made up of django and celery. And I code two tasks which would sipder from two differnt web and save some data to database —— mysql. As before, I do just one task, and I use update_or_create shows enough. But when I want to do more task in different workers ,and all of them may save data to database, and what's more, they may save the same data at the same time. question How can I ensure different tasks running in different worker makeing no repeating data when all of them try to save the same data? I know a django API is select_for_update which would set a lock in database. But when I reading the documentions, it similar means, would select,if exist,update. But I want to select,if exist,update,else create. It would more be like update_or_create,but this API may not use a lock? -
Django ManagementForm data is missing or has been tampered error on request.POST
When i pass request.POST parameter to my CargoUnitFormSet. It get this error in command line. File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\forms\formsets.py", line 98, in management_form code='missing_management_form', ValidationError: [u'ManagementForm data is missing or has been tampered with'] In myform i create a formset. And my formset is displayed on my web page. Whenever i pass request.POST as a parameter to save my formset it gives this validation error. Here is my view function: def create_entity(request): from django.forms import BaseFormSet from django.forms import formset_factory from django.forms.models import modelformset_factory, BaseModelFormSet CargoUnitFormSet = formset_factory(CargoUnitForm,max_num=3) data = dict() if request.method == 'POST': cargo_form = CargoForm() cargo_form = CargoForm(request.POST, request.FILES or None) cargo_unit_formset = CargoUnitFormSet(request.POST,prefix="foo") if not cargo_form.is_valid(): form = CargoForm() data['form_is_valid'] = False if cargo_form.is_valid() and cargo_unit_formset.is_valid(): cargo = cargo_form.save() for form in cargo_unit_formset.forms: cargo_unit = form.save(commit=False) cargo_unit.list = cargo cargo_unit.save() data['form_is_valid'] = True context = { 'form': cargo_form, 'formset':cargo_unit_formset } data['html_form'] = render_to_string("cargos/form-create.html", context, request=request) return JsonResponse(data) Here is my related html template for formset <div class="row"> {{formset.management_formset}} {% for form in formset.forms %} <div class="item well"> {{ form.as_p }} <p><a class="delete btn btn-danger" href="#"><i class="icon-trash icon-white"></i> Delete</a></p> </div> {% endfor %} </div> Thanks in advance. -
Celery in Django Matching Query Does Not Exist even though Model is present
I'm currently moving from my dev environment to my AWS server and I've hit a snag regarding Celery. These issues where not present when running in the dev environment but have now popped up in the server. Its claims that my AutomationSettings model doesn't exist but its present and the import instructions are present. I've checked out here, here, here and here. How do I fix? Trace (.venv) ubuntu@ip-172-31-43-50:~$ celery -A milingual worker -l info Traceback (most recent call last): File "/home/ubuntu/.venv/bin/celery", line 11, in <module> sys.exit(main()) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/__main__.py", line 14, in main _main() File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/base.py", line 281, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 480, in handle_argv return self.execute(command, argv) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/celery.py", line 412, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/worker.py", line 221, in run_from_argv return self(*args, **options) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/base.py", line 244, in __call__ ret = self.run(*args, **kwargs) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/bin/worker.py", line 255, in run **kwargs) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/worker/worker.py", line 94, in __init__ self.app.loader.init_worker() File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/loaders/base.py", line 116, in init_worker self.import_default_modules() File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/loaders/base.py", line 111, in import_default_modules return [self.import_task_module(m) for m in self.default_modules] File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/loaders/base.py", line 97, in import_task_module return self.import_from_cwd(module) File "/home/ubuntu/.venv/local/lib/python2.7/site-packages/celery/loaders/base.py", line 106, … -
Make google recaptcha not to ask more than once
views.py def the_same_page(request): #This POST request is from '/the_same_page/' if request.method == 'POST': if some_check(): return render(request, 'the_same_page.html') #something goes wrong so I will make render the same page, the same url. the_same_page.html <div class="form-group"> <label class="control-label" for="">text</label> {{ form.text }} </div> <div class="g-recaptcha" data-sitekey="121~~~~1212"></div> <button class="btn btn-default" type="submit">Submit</button> The user want to submit any text, the user have to do recaptcha again and again. I want to remove this recaptcha re-check. How can I set recaptcha to state of human_verified? So don't ask again if the user have checked this recaptcha before? -
Convert a one-to-many hierarchy of Models to a plain json in Django
I have a chain of Django Models with one-to-many relation between one and another. For example class Country(models.Model): name = models.CharField(max_length=128) code = models.IntegerField(unique=True) class Manufacturer(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) address = models.CharField(max_length=128) class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) color = models.CharField(max_length=32) I want to make a dump of the database as a plain json, i.e. an array of objects with no sub-objects. For example { "cars": [ { "color": "white", "manufacturer_address": "ave 1", "manufacturer_country_name": "the uk", "manufacturer_country_code": "56" }, { "color": "red", "manufacturer_address": "ave 2", "manufacturer_country_name": "the usa", "manufacturer_country_code": "57" } ] } Without a doubt, I can hard code all the foreign keys used. It's what I've come up with so far, a sequence of calls to django.forms.models.model_to_dict and models.XXX.objects.filter(id=XXX). But is there a more idiomatic (shipped with Python or Django) way to achieve that? To introspect a Car class and add all its ordinary (non-FK) fields to a json detect all its FKs, "inflate" them recursively as it is stated in item 1 -
Django Saving new record, int() argument must be a string or a number, not 'QueryDict'
I'm using Django 1.11 and Python 2.7.13. I'm deploying on Google App Engine using Cloud SQL (MySQL 5.7) but the error happens in my local development environment. I have a very simple app with 1 form that collects some data and tries to save it as a new record in the database. It works fine if I use the default form and CreateView like this: # views.py class SubjectCreate(CreateView): model = Subject fields = '__all__' success_url = reverse_lazy('subapp:index') However, I want to customize the form (move fields around, use check boxes, etc.) To do this from what I can tell I can't use the default CreateView, etc. but have to write my own. So here's what I've done: # models.py class Subject(models.Model): subject_date = models.DateTimeField(default=timezone.now) subject_field2 = models.CharField(max_length=20) ... whole bunch of other fields ... def __str__(self): return self.subject_date.strftime('%Y-%m-%d %H:%M') + self.subject_field2[:35] + "..." #views.py def createnewsubject(request): if request.method == 'POST': subject_form = NewSubjectForm(request.POST) if subject_form.is_valid(): subject_data = Subject(request.POST) subject_data.save() return HttpResponseRedirect('/') else: subject_form = NewSubjectForm() return render(request, 'subapp/subject_form.html', {'form': consultation_form}) # forms.py class NewSubjectForm(forms.ModelForm): class Meta: model = Consultation fields = "__all__" When the code hits subject_data.save() I get TypeError at /new/ int() argument must be a string or … -
KeyError: 'region' query set
I'm using this code to get a query set with 3 values (game id, platform and release date). It works for the first few json objects until it reaches a certaine one it returns this error: KeyError: 'region' and the cause is region=release_date_object['region'] # Get from 'release_date_object' (JSON object) release_date = ReleaseDate.objects.filter(game=game.id, platform=release_date_object['platform'], region=release_date_object['region']) -
API Integration in Django
I am trying to use the OpenDOTA API in my pet project. At the moment, I am having problem displaying the content of the API into my CBV. My views.py: from django.views.generic import TemplateView import requests import json # Create your views here. class HeroList(TemplateView): template_name = 'dota/heroes.html' url = 'https://api.opendota.com/api/heroes' r = requests.get(url) r.text result = r.json() I am lost on how to call the json in my HTML. I've tried running the same code in python IDLE, and when I type the "result" and hit enter, it gives my the dict. Any idea on how should I display the dict into my template? -
How to create two records in database at once with one form in Django 1.11
Here are my two models: class User_Phrase(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) start_date = models.DateTimeField(default=datetime.now, editable=True) interval_in_sec = models.IntegerField() class Phrase(models.Model): phrase = models.CharField(max_length=250, primary_key=True) user_phrase_id = models.ForeignKey(User_Phrase, on_delete=models.CASCADE) I want to create two records in the database with one form. Scenario: User wants to fill the fields start_date, name, phrase, interval_in_sec. When user submits the form firstly it takes the value from phrase field checks if the current phrase is already stored in the Phrase if yes it binds the user_phrase record to that phrase else it creates phrase record and then associates it with the user_phrase Also, I am using this a string for the phrase primary key, I am not sure if that is correct design but I want unique phrases to be stored in that table. The purpose of that table is basically when a user looks for a phrase, I want to store it and to store some other values connected to that phrase. How do I achieve that? -
Interpreting Django style vs SQLAlchemy style
In SQLAlchemy ORM you do session.add(person); session.commit(). In Django you do person.save(). Is there an important difference between these? It seems like the Django style requires attaching the model object closely to the database, whereas the SQLAORM style does not. When working outside of SQLAlchemy or Django, what makes one of these styles a more appropriate choice? Specifically, when should I design a system to use session.add(person); session.commit() vs person.save()? -
How to save binary data into .wav audio file by using wave module in Python
First of all I am using Python2.7 So right now I have some binary data audio which is taken from web, and now I need to convert this binary data and save it into local storage. Simple solution can be: with open('audio2.wav', 'w') as f: f.write(data) # Where data is binary data But if we will notice mediainfo for this particular audio file then it will be: General Complete name : audio2.wav Format : OGG File size : 49.0 KiB Duration : 3s 966ms Overall bit rate : 101 Kbps Writing application : Mozilla58.0 Audio ID : 1838225608 (0x6D9118C8) Format : Opus Duration : 3s 966ms Channel(s) : 2 channels Channel positions : Front: L R Sampling rate : 44.1 KHz Compression mode : Lossy Writing library : libopus unknown And if we do mediainfo of some original .wav audio file then it will look something like this: General Complete name : woman1_wb.wav Format : Wave File size : 220 KiB Duration : 7s 40ms Overall bit rate mode : Constant Overall bit rate : 256 Kbps Audio Format : PCM Format settings, Endianness : Little Format settings, Sign : Signed Codec ID : 1 Duration : 7s 40ms Bit … -
Django 2.0 'name' is not a registered namespace
I've seen this error posted several times, but I can't find anyone using Django 2.0 and having the problem. The problem cropped up when I tried to nest one app inside another. The nested app (called "users") is meant to allow users to login and out. After putting that segment in, I'm getting the following error: Template error: In template C:\Users\arbit\Documents\python\learning_log\learning_logs\templates\learning_logs\base.html, error at line 6 'users' is not a registered namespace 1 : <p> 2 : <a href="{% url 'learning_logs:index' %}">Learning Log</a> 3 : <a href="{% url 'learning_logs:topics' %}">Topics</a> 4 : {% if user.is_authenticated %} 5 : Hello, {{ user.username }}. 6 : <a href=" {% url 'users:logout' %} ">log out</a> 7 : {% else %} 8 : <a href="{% url 'users:login' %}">log in</a> 9 : {% endif %} 10 : </p> 11 : 12 : {% block content %}{% endblock content %} 13 : Here's my root urls.py from django.urls import path, include from django.contrib import admin from . import views app_name = "learning_log" urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('learning_logs.urls')), ] urlpatterns = [ # Home page path('', views.index, name='index'), # Show all topics path('topics/', views.topics, name='topics'), # Detail page for a single topic path('topics/<int:topic_id>/', views.topic, … -
clear transaction log in sqlite3 database
I am using Sqlite3 in my Django Project. Initially my database size was less than 1 MB. It's been more than a year since I put it on my production server. The size has now become 121 MB. using dump command I copied its content to a .sql file here are first few lines PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE "django_migrations" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app" varchar(255) NOT NULL, "name" varchar(255) NOT NULL, "applied" datetime NOT NULL); INSERT INTO "django_migrations" VALUES(1,'contenttypes','0001_initial','2016-06-11 18:12:58.547832'); INSERT INTO "django_migrations" VALUES(2,'auth','0001_initial','2016-06-11 18:12:58.792963'); INSERT INTO "django_migrations" VALUES(3,'admin','0001_initial','2016-06-11 18:12:59.049214'); INSERT INTO "django_migrations" VALUES(4,'contenttypes','0002_remove_content_type_name','2016-06-11 18:12:59.361764'); INSERT INTO "django_migrations" VALUES(5,'auth','0002_alter_permission_name_max_length','2016-06-11 18:12:59.613627'); INSERT INTO "django_migrations" VALUES(6,'auth','0003_alter_user_email_max_length','2016-06-11 18:12:59.802244'); INSERT INTO "django_migrations" VALUES(7,'auth','0004_alter_user_username_opts','2016-06-11 18:13:00.001846'); INSERT INTO "django_migrations" VALUES(8,'auth','0005_alter_user_last_login_null','2016-06-11 18:13:00.190468'); INSERT INTO "django_migrations" VALUES(9,'auth','0006_require_contenttypes_0002','2016-06-11 18:13:00.257173'); INSERT INTO "django_migrations" VALUES(10,'default','0001_initial','2016-06-11 18:13:00.554142'); INSERT INTO "django_migrations" VALUES(11,'default','0002_add_related_name','2016-06-11 18:13:00.834812'); INSERT INTO "django_migrations" VALUES(12,'default','0003_alter_email_max_length','2016-06-11 18:13:01.067028'); INSERT INTO "django_migrations" VALUES(13,'default','0004_auto_20160423_0400','2016-06-11 18:13:01.234154'); there are too many transaction statements here. I guess this is why the file size has increased. Also, I found out that most of the size is taken by django_session table which is around 70 MB. tried python manage.py clearsessions but the file size didn't reduce I know there is shrink command in sql server … -
Django 2.0 dynamically generate urlpatterns
I wrote this code which is dynamically generate urlpatterns from db. These urls has only one level path ( domain.com/something ) someapp/models.py class SomeModel(models.Model): pattern = models.CharField(max_length=50) name = models.CharField(max_length=50) text = models.CharField(max_length=50) someapp/apps.py class SomeAppConfig(AppConfig): name = 'someapp' def ready(self): from .models import SomeModel from .urls import urlpatterns from . import views urls_in_db = SomeModel.objects.all() for url_in_db in urls_in_db: urlpatterns.append(path(url_in_db.pattern, views.SpecialView.as_view(), name=url_in_db.name) someapp/views.py class SpecialView(generic.TemplateView): template_name = 'template/view_template.html' model = SomeModel def get_context_data(self, **kwargs): context = super(SpecialView, self).get_context_data(**kwargs) context['content'] = SomeModel.objects.get(pattern=self.request.path) return context So the question is: Is this solution antipattern ? And if yes, why ? Thanks -
Django: how to mock a user with FB privilegies
I need to check that the content of a template is loaded properly. However, I need a user that has Facebook integration. This is my view: def profile(request, user_id): """A user's public pledge settings.""" user = get_object_or_404(SocialUser, pk=user_id) # We only want to show profile pages for users with Facebook integration try: user.social_auth.get(provider='facebook') except (UserSocialAuth.DoesNotExist, UserSocialAuth.MultipleObjectsReturned): raise Http404(_('User does not exist')) events = ['A', 'B', 'C'] context = { 'APP_ID': settings.SOCIAL_AUTH_FACEBOOK_KEY, 'user': user, 'last_event': events[-1], } return render(request, 'pledges/profile/profile.html', context) I think that I should create a mock object associated with a UserSocialAuth object, so I can skip that exception. However, I am not sure how to make the database to return this mock object. I am also using pytest for testing, so this is what I have so far: import pytest from unittest import mock from django.test import Client from django.urls import reverse from social_django.models import UserSocialAuth from pledges.models import SocialUser TEST_USERNAME = 'testuser' TEST_PASSWORD = 'password123' TEST_EMAIL = 'testuser@example.com' @pytest.fixture() def create_social_user(): """Creates a social user""" user = mock.Mock(spec=SocialUser) return user @pytest.mark.django_db def test_everytime_bar_is_displayed_on_profile_page_when_non_logged_in( create_social_user): user = create_social_user # I am not sure how to make this user to be the user gotten from the database UserSocialAuth.objects.create(user=user, provider='facebook', … -
Django reverse foreign key in
Model: class Book: title = CharField() author = ForeignKey(Person, related_name='books') class Person: name = CharField() How do I select persons that has books from a certain set? For example, select all persons, that have ('A', 'B', 'C') as books (and possibly more), i.e. subset. -
Django views.py code fails to find media files
I am developing an application in django where my views.py file needs to find a get a file located in the media folder. The structure of my directory is as follows: app/app/views.py app/media/streams/input/audio.mp3 In my views.py I have the following code: filename = "../media/streams/input/audio.mp3" file = open(filename, "r") But when I run the function, I get the following error: [Errno 2] No such file or directory: ../media/streams/input/audio.mp3 I am not sure how to put the right path in it or is it something else that I need to do? -
Returning an image from a Django view using django-sslserver
I'm trying to return an image from a Django 1.11 view while using django-sslserver and Pillow. Here's a minimal view I made for testing. def get_image(request): img = Image.open('oh_noes_cat.png', mode='r') response = HttpResponse(content_type='image/png') img.save(response, 'png') return response In my template I use: <img src={% url "get_image" %} /> In urls.py, I use: url(r'^get_image.png', get_image, name='get_image') The image response works fine with Django runserver but fails under both django-sslserver and runserver_plus from django-extensions. What I see in Chrome is a broken image icon and the error "ERR_CONTENT_LENGTH_MISMATCH". When using django-sslserver I get the error: [26/Dec/2017 18:55:39] "GET /get_image.png HTTP/1.1" 200 0 Traceback (most recent call last): File "/usr/lib/python3.5/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.5/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib/python3.5/wsgiref/handlers.py", line 279, in write self._write(data) File "/usr/lib/python3.5/wsgiref/handlers.py", line 453, in _write result = self.stdout.write(data) File "/usr/lib/python3.5/socket.py", line 593, in write return self._sock.send(b) File "/usr/lib/python3.5/ssl.py", line 861, in send return self._sslobj.write(data) File "/usr/lib/python3.5/ssl.py", line 586, in write return self._sslobj.write(data) ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:1844) [26/Dec/2017 18:55:39] "GET /get_image.png HTTP/1.1" 500 59 Does anyone know how I can make an image response work with django-sslserver or a similar solution for supporting SSL in a Django development environment? I've … -
how to obtain lock on django model for concurrent Operation
i am trying to obtain locking in django model such as if user 1 is editing admin action will be disabled for user 2 once user 1 leaves the form user 2 will have access. but still not able to find solution -
Best way to make "viewed" attribute for messages inside user group?
I am deciding on how to track if a user has seen a post in the timeline or not. There is Post and Comment model like this. class Comment(models.Model): author = models.ForeignKey('UserProfile') title = models.CharField(max_length=255) text = models.TextField(null=True, blank=True) date_created = models.DateTimeField() post = models.ForeignKey('Post', related_name='comments') class Post(ContentTypeModel): title = models.CharField(max_length=255) group = models.ForeignKey('UserGroup', null=True) date_updated = models.DateTimeField() Suggestions about best practices on how to track if post has been seen by particular member of a user group will be nice. -
Built a bootstrap form and trying to use it in Django - Invalid data
My form was working fine when I used {{ form.as_p }} but when I decided to design my form using the twitter bootstrap and added widgets to my fields to be able to use the new form, I no longer receive the form submissions in a folder (because I'm using the send_mail function). It seems that the request is not entering the is_valid block and I can't really figure out why. Note: I'm trying to debug and I'm getting that the email field is required despite filling it with a genuine email. My form: from django import forms class ContactForm(forms.Form): first_name = forms.CharField(widget=forms.TextInput(attrs={'id': 'first_name'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'id': 'last_name'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'id': 'email-address'})) message = forms.CharField(widget=forms.Textarea(attrs={'id': 'message'})) My view: from django.shortcuts import render from myblog import forms # To be able to send mail from django.contrib import messages from django.core.mail import send_mail from django.urls import reverse from django.http import HttpResponseRedirect def contact_form(request): form = forms.ContactForm() # If POST request is coming if request.method == 'POST': # Fills the form with the data form = forms.ContactForm(request.POST) # Check if the data is good if form.is_valid(): send_mail( 'Message from {} {}'.format(form.cleaned_data['first_name'], form.cleaned_data['last_name']), form.cleaned_data['message'], '{first_name} {last_name} <email>'.format(**form.cleaned_data), ['test@gmail.com'] ) # Send message messages.add_message(request, messages.SUCCESS, … -
How to change order field based on language selection?
I create a custom MultilingualCharField and I want order the instances by it, in the right language. I prefer to do so in the model, is it possible? class Myclass(models.Model): name = MultilingualCharField(max_length=32, unique=True) ... def __str__(self): name_traslated={'name_it': self.name_it, 'name_en': self.name_en} name_verbose=_('name_it') return name_traslated[name_verbose] class Meta: #name_traslated={'name_it': self.name_it, 'name_en': self.name_en} name_verbose=_('name_it') ordering = [name_verbose] #ordering = [name_traslated[name_verbose]] __str__ is working but ordering is not: it gives TypeError: 'class Meta' got invalid attribute(s): name_verbose My MultilingualCharField create two columns: name_it and name_en, here the code (from Web Development with Django Cookbook): class MultilingualCharField(models.CharField): def __init__(self, verbose_name=None, **kwargs): self._blank = kwargs.get("blank", False) self._editable = kwargs.get("editable", True) #super(MultilingualCharField, self).__init__(verbose_name, **kwargs) super().__init__(verbose_name, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): # generate language specific fields dynamically if not cls._meta.abstract: for lang_code, lang_name in settings.LANGUAGES: if lang_code == settings.LANGUAGE_CODE: _blank = self._blank else: _blank = True localized_field = models.CharField(string_concat( self.verbose_name, " (%s)" % lang_code), name=self.name, primary_key=self.primary_key, max_length=self.max_length, unique=self.unique, blank=_blank, null=False, # we ignore the null argument! db_index=self.db_index, rel=self.rel, default=self.default or "", editable=self._editable, serialize=self.serialize, choices=self.choices, help_text=self.help_text, db_column=None, db_tablespace=self.db_tablespace ) localized_field.contribute_to_class(cls, "%s_%s" % (name, lang_code),) def translated_value(self): language = get_language() val = self.__dict__["%s_%s" % (name, language)] if not val: val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)] return val setattr(cls, name, … -
Django: smart-select how to use it in forms.py
I am using smart_selects in Django to filter drop down views. In my admin page, I was successful in doing this using 'ChainedForeignKey' I am now trying to create a user form and implement the same thing. my approach is models.py class LegalDocumentField(models.Model): name = models.CharField(max_length=255, default="default", verbose_name="Tên") desc = models.CharField(max_length=255, default="default", verbose_name="Chi tiết") def __unicode__(self): return self.name class Meta: verbose_name = 'Lĩnh vực văn bản pháp luật' verbose_name_plural = 'Lĩnh vực văn bản pháp luật' class LegalDocumentType(models.Model): linhvuc = models.ForeignKey(LegalDocumentField, on_delete=models.CASCADE, verbose_name="Lĩnh vực") name = models.CharField(max_length=255, default="default", verbose_name="Tên") desc = models.CharField(max_length=255, default="default", verbose_name="Chi tiết") def __unicode__(self): return self.name class Meta: verbose_name = 'Loại văn bản pháp luật' verbose_name_plural = 'Loại văn bản pháp luật' forms.py class LegalDocumentForm(forms.Form): document_field = ModelChoiceField(label=_("Lĩnh vực văn bản"), queryset=LegalDocumentField.objects.all(), empty_label="--Lĩnh vực văn bản--", required=False) #ag document_type = ChainedModelChoiceField( to_app_name="myapp", to_model_name="LegalDocumentType", chained_field="linhvuc", chained_model_field="linhvuc", foreign_key_app_name="myapp", foreign_key_model_name="LegalDocumentType", foreign_key_field_name="linhvuc", show_all=False,auto_choose=True) template.html ... <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script type="text/javascript" src="{% static '/smart-selects/admin/js/chainedfk.js' %}"></script> <script type="text/javascript" src="{% static '/smart-selects/admin/js/bindfields.js' %}"></script> ... <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> i want when someone selects document_field the document_type selections are filtered accordingly.But the document_type selections was empty when i changed document_field value.