0

I'm studying Django from the book Django 2 by Examples. I'm trying to improve a project which starts in chapter 10. Now, I'm trying to add multilingualism with the help of "django-parler". In general I did it, but it seems to me that there are better ways. Views are implemented as classes that are inherited from mixins. If a language other than the default language is selected on the page, the form still comes with the value of laguage_code field equal to default. I tried unsuccessfully to change this field in the form_valid method. The form was still saved with the default language. The only option that works for me is this, by it looks like kludge:

def form_valid(self, form):
    language = translation.get_language()
    _course = form.save(commit=False)

    try:
        course = Course.objects.get(pk=_course.id)
    except Course.DoesNotExist:
        course = Course()
        course.owner = self.request.user
    course.set_current_language(language)

    cd = form.cleaned_data
    course.subject = cd['subject']
    course.title = cd['title']
    course.slug = cd['slug']
    course.overview = cd['overview']
    course.save()
    return redirect(reverse('courses:manage_list'))

Maybe someone knows a more elegant way to implement this?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40

1 Answers1

0

I hope, you have a class based Django FormView with ModelFormMixin:

def form_valid(self, form):
    self.obj = form.save()  # you dont need it in UpdateView
    return super().form_valid(form)

By the way.

Django-Parler or Django-HVAD are already died projects. You can use django-modelTranslation. Or my project Django-TOF v.2.

Of course django 2 is already very old project. Django 4.1 is much much better.

In my opinion the best book about Django - Django Design Patterns and Best Practices. Last version. it is more Django-ish than "2 scope" or "Django 2 by Example"

Maxim Danilov
  • 2,472
  • 1
  • 3
  • 8
  • Thank you for your answer, it's works, but it didn't solve the problem. The form is still saved in the default language. I was forced to add to the method two lines: `self.object.owner = self.request.user` and `self.object.save()`, replacing at the same time `self.object = form.save()` to `self.object = form.save(commit=False)`. – Matthew Shtyasek Aug 21 '22 at 03:56