Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update a field for all instances when a Many-to-many relationship is involved
I have the following: class Customer(model): stores = models.ManyToManyField(Store, related_name = "customers") subscriptions = models.ManyToManyField(Subscription, through = "CustomerSubscription") class CustomerSubscription(model): subscription = models.ForeignKey(Subscription) customer = models.ForeignKey(Customer) class Subscription(model): is_valid = models.BooleanField() For a given store instance: store = Store.objects.get(pk=1) I want to get all the subscriptions for all the customers and set is_valid to False. This is my attempt which appears to work: customers = store.customers.all() for c in customers: c.subscriptions.update(is_valid=False) I then tried using prefect_related: customers = store.customers.prefect_related("subscriptions") for c in customers: c.subscriptions.update(is_valid=False) But I don't believe I am doing this correctly as it resulted in more sql queries than my first attempt. How should I be doing this? -
How can I generate a pdf from django and send it by mail
estoy tratando de generar un pdf a partir de un html que diseñe para luego covertirlo en pdf y enviarlo por correo electronico, pero inteno generarlo y solo se generan desde el lado del cliente y no lo puedo enviar asi por el correoenter image description here I tried with pisa of xml2pdf and it only renders on the client side as far as it seems to me everything else generates blank pdf -
What "Tomcat/bypass/command/base64/.. " mean?
I don't know what is the problem exactly? Hello.. I built an website with Django framework and deploy it to Debian server, i install Apache web server on it then run the website.. So in the project i do some thing like this : Get the ip address from people who are visiting the main page in the website and save them for one day, and in the next day delete the old IPes and save for today and so on.. but the website has no domain name yet.. it still under trail until this moment.. I display the IPes on admin interface... Then wow!! I get this !! enter image description here Where they come from ?? And what doesn't the string i mentioned in orange box ? I searched on google it seem like an attack or something i don't know! So i delete the log file on Apache server after copy it on my device.. And now the time on my server does not work ?? I can't get the time with : datetime.datetime.now() In view.py file -
postgresql - cannot modify default "postgres" user
How to change, alter, postgres default values for my project? I have a django project which I try to deploy to digital ocean on an ubunto instance. In psql I create a new user with new_password and grant it all privileges to the new_db. Yet, these created entries are not connected to my project database. i.e. The values of the databases remain the default ones: Name/User/Password=postgres I note here the commands I run the Docean, ubuntu server: Assunming a new_user created (i.e. none root) and all psql packages are installed. sudo -u postgres psql CREATE DATABASE new_db; #DATABASE created; CREATE USER new_user WITH PASSWORD 'new_psw'; ALTER ROLE new_user SET client_encoding TO 'utf8'; ALTER ROLE new_user SET default_transaction_isolation TO 'read committed'; ALTER ROLE new_user SET timezone TO 'UTC'; GRANT ALL PRIVILEGES ON DATABASE new_db TO new_user; Quitting postgres, I my database value on my shell: The values remain the default ones: DATABASES {‘default’: {‘ENGINE’: ‘django.db.backends.postgresql’, ‘NAME’: ‘postgres’, ‘USER’: ‘postgres’, ‘PASSWORD’: ‘postgres’, ‘HOST’: ‘localhost’, ‘PORT’: 5432, ‘ATOMIC_REQUESTS’: False, ‘AUTOCOMMIT’: True, ‘CONN_MAX_AGE’: 0, ‘CONN_HEALTH_CHECKS’: False, ‘OPTIONS’: {}, ‘TIME_ZONE’: None, ‘TEST’: {‘CHARSET’: None, ‘COLLATION’: None, ‘MIGRATE’: True, ‘MIRROR’: None, ‘NAME’: None}}} I also tried the following: I then declared the new_user as the database … -
Django OneToOne field where one side of the relation is mandatory
Suppose I have these models: class Space(models.Model): item = models.OneToOneField(Item, null=True, on_delete=models.CASCADE) class Item(models.model): ... A Space can contain an Item, but it can be empty too. On the other hand, every Item must have a Space. It cannot exist in a void. I could create a field .space in my Item model (with null=False), but then Space.container can never be empty (raising a RelatedObjectDoesNotExist exception when creating/querying them). Handling these exceptions is cumbersome. I'd rather have Space.container return None (as is the case with my current setup). Is there an easy way to make .space in the Item model mandatory, but not the other way around? -
How to set the redirect URL in Django within the dispatch method with URL parameters
I have a custom Mixin that checks for the total usage of a particular service and based on that allows users to submit the form or redirect to the success_url with an error message of total usage. This works fine for URLs without any dynamic parameters like pk or slug. but with parameters, Django cannot find a URL pattern to redirect to the success_url. urls.py (URL file of Instagram app) # some other urls path('<int:post_id>/image/stock/', InstagramImageStockView.as_view() , name='instagram_image_stock'), path('<int:post_id>/image/stock/generate/', InstagramGenerateStockImageView.as_view(), name='instagram_fetch_stock_image'), # more URLs views.py class InstagramGenerateStockImageView(CustomMixin, FormView): form_class = InstagramStockImageForm success_url = 'instagram:instagram_image_stock' # other code custom mixin class CustomMixin: # other methods def check_generation_status_and_redirect(self, request, *args, **kwargs): if self.able_to_generate: return super().dispatch(request, *args, **kwargs) else: # Set an error message based on conditions. return redirect(self.success_url, kwargs=kwargs) def dispatch(self, request, *args, **kwargs): self.check_daily_count() return self.check_generation_status_and_redirect(request, *args, **kwargs) When a user reaches the limit I am getting NoReverseMatch error while redirecting to the success_url. I also tried by defining the success_url with reverse_lazy but not working. Thanks. -
how can I determine which ORM is the most suitable for my specific Django project requirements?
What are the factors to consider when choosing an ORM for a Django project, and how can I determine which ORM is the most suitable for my specific project requirements? I'm currently working on a new project and I'm looking for advice on the best ORM to use that doesn't require migration. I prefer to work with ORMs that simplify database interactions and reduce the amount of boilerplate code that I have to write. However, I've run into issues with ORMs that require migration for database schema changes. I'm hoping that some of you may have experience with ORMs that don't require migration and can offer recommendations. I'm particularly interested in ORMs that have a robust set of features, good documentation and are easy to use. Any suggestions would be greatly appreciated. Thank you in advance! -
Django ModelForm has no model class specified error
*** forms.py file *** I've checked most sites and videos and the issue is not solving. from django import forms from django.forms import ModelForm from .models import * class TaskForm(forms.ModelForm): class Mete: model = Task fields = '__all__' here is the views.py file * from django.shortcuts import render, redirect from .models import * from .forms import * # Create your views here. def home(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks':tasks, 'form':form} return render(request, 'home.html', context) here is the html file * <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home page</title> </head> <body> <h1>Todo project by Rohit.</h1> <form method="POST" action="/"> {% csrf_token %} {{ form.title }} <input type="submit" name="Create Task"> </form> {% for task in tasks %} <div> <a href="{% url 'deletepage' %}">Delete task</a> <a href="{% url 'updatepage' %}">Update task</a> {{task.title}} </div> {% endfor %} </body> </html> -
Uploading to MEDIA_URL instead of referencing static image
I have some default images stored in my static folder that we use for migrations. I reference these when deploying new features in order to batch create a large number of icons: # Set Icon icon_path = finders.find(my_path) if icon_path: icon_file = open(icon_path, "rb") icon = File(icon_file) else: raise Exception("Icon file not found.") obj.icon = icon One thing I've noticed with this method is that the saved icon references the static folder URL instead of referencing my S3 MEDIA_URL (configured with django-storages). I'm wondering if there's something I'm missing that could be causing this to happen, because when I upload an image and set it the same way from a DRF serializer it goes to S3 instead. -
Using TailwindCSS in a Django project hosted on Github
I want to use Django together with TailwindCSS in a personal web project and followed two instructions for setting it all up: on the one hand the installation instructions on https://tailwindcss.com/docs/installation on the other hand this Youtube tutorial (because the installation guide was too short for my limited understanding of the topic). https://www.youtube.com/watch?v=lsQVukhwpqQ Since I am not familiar with node.js and npm, i am unsure how to store the resulting project in Github and reproduce it on other computers. The structure of the Django project is no problem, I am familiar with it. I am unsure about the files and folders related to Tailwind and Node. After the tutorial I had a "node_modules" and a "local-cdn" folder as well as "package.json" and "package-lock.json" and a "tailwind.config.js". My question would be: which files present at the end of the two tutorials above should be synced with Github, which should not be synced and what to set up on a second machine (beyond installing node and django obvsly) to continue working on this already existing project there (in contrast to the tutorials above describing how to start a new project)? -
Django 404 I cannot get Django to redirect 404s to my homepage
I'm having a problem getting handler 404 to redirect to my homepage. Here's what I have and tried... In settings.py DEBUG=False In views.py class view_404(request, exception=None): return render(request, "mysite/index.html") In urls.py From django.conf.urls import handler404 urlpatterns = [ path('', views.index, name='index') ] handler404 = "mysite.views.index" I've tried putting the view_404 function directly in the urls.py file, I've tried handler404 = views.index. I've tried handling 404s in my nginx.conf file error_page 404 =200 /index.html; and error_page 404 /index.html; location /index.html { root path/to/template; internal; } I have not been able to get any of these to work... -
Django : best place to store constants used in view and Celery tasks
I'm looking for advice regarding project structure in my Django app. I want to define a constant that is used both in a view and in a background task (Celery to be specific), but I am not sure where this should be placed. The constant defines the number of records to be shown to the user. My model represents an image, and only the recent 100 records need to be displayed on the page. Older records can be deleted, and there is a separate Celery task that cleans up such records on a weekly basis. I have defined this 100 as NUM_RECORDS_TO_SHOW in my model class, but I am not sure if this is the best place, since I am exposing my model to the business logic. Defining this constant in my view seems also a bad idea, as this could lead to circular imports. -
Why my views.py doesn't save submitted csv file in data folder in my app directory in Django project?
Hello I am working on a project Django. I am trying to save a file after users submits it from webpage. I created views and HTML.. part of the views.py, html and urls.py are provided below. Can i get some help why my code is not saving file in data folder in my app directory? views.py class CsvPlot(View): def save_uploaded_file(self, request, file): if request.method == 'POST' and request.FILES[file]: uploaded_file = request.FILES['document'] # attribute = request.Post.get("attribute") # print(attribute) # check if the file ends with csv if uploaded_file.name.endswith('.csv'): save_file = FileSystemStorage() name = save_file.save(uploaded_file.name, uploaded_file) print(name) # Let's save the file in the data folder current_dir = settings.BASE_DIR / 'ml_in_geotech' file_directory = os.path.join(current_dir, 'data') if not os.path.exists(file_directory): os.makedirs(file_directory) self.file_path = os.path.join(file_directory, name) self.readfile(request, self.file_path) request.session['file_path'] = self.file_path else: return HttpResponse('Invalid file type. Only CSV files are allowed.') My HTML <div class="upload_file"> <h2>Train Your Data</h2> <form method="POST" enctype="multipart/form-data" action="/"> {% csrf_token %} <input type="file" name="document" id="document" required="required"> <button type="submit">Submit</button> </form> {% block messages %} {% if messages %} <div class="container" style="color: firebrick; margin-top: 20px" > {% for message in messages %} {{ message }} {% endfor %} </div> {% endif %} {% endblock %} </div> My urls.py path('csv-plot/', views.CsvPlot.as_view(), name='csv_plot'), ] -
Overriding the default validation for a Django admin Foreign Key field
I have Django models that inherit from an Archive class in which the default manager (objects) is replaced with a query that does not return archived records. This works well throughout the system. However, in admin, when a record with a foreign key attempts to validate and that foreign key instance is an archived record, the validation attempts to use the new default manager, objects which filters out archived records as opposed to the objects_all manager which returns all records - and since an archived record is not returned using objects, the save fails with "instance does not exist". Here is a simplified example: class Inv(AbstractArchive): item_code = models.CharField(max_length=20, primary_key=True) qty = models.IntegerField() def __str__(self): return f"{self.item_code}" class Txn(AbstractArchive): inv = models.ForeignKey(Inv) date = models.DateField() added = models.IntegerField My admin for Txn looks like this (I defined a form in admin with a queryset that gets all the records, even those marked as archived - I also included a clean method hoping this would override the form's default validation that uses the objects manager) class TxnForm(forms.ModelForm): class Meta: model=Txn def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['inv'].queryset = Inv.objects_all.all() def clean_inv(self): inv= self.cleaned_data['inv'] if not Inv.objects_all.filter(inv=inv).exists(): raise forms.ValidationError("Invalid inventory record selected.") … -
How to update m2m objects with django formsets?
I'm starting this project in which I have an Order class with an m2m relationship with an Item class using the throug argument with an ItemTimes class. The idea is to add several items to an order registering also it times. For that I use a model formset. The creation of the order goes well but to update items I can't even get to the point in which the formset is valid. Printing the formset errors throws this: [{'id': ['This field is required.']}, {'id': ['This field is required.']}, {'id': ['This field is required.']}, {'id': ['This field is required.']}, {}, {}, {}, {}, {}] but in the indexes where says "This Field is required" is where ItemTimes objects are selected. Help please. Here models.py """orders models""" # django from django.db import models # local from ..customers.models import Customer from ..kits.models import Kit from ..items.models import Item from ..executors.models import Executor class Order(models.Model): """Pre Bill document to register job details performed""" customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, verbose_name="Cliente") symptom = models.CharField('Síntoma', max_length=100) flaw = models.CharField('Defecto', max_length=100) repair_description = models.CharField('Reparación', max_length=100) folio = models.CharField('No. folio', max_length=10) # next four attributes are related to the modality of the order check_diagnosis = models.BooleanField('Revisión/Diagnóstico') repair = models.BooleanField('Reparacón') … -
Django: Update all records in a table when I insert a new record
hello friends i need help! It turns out that I have a model which has several properties, I use it to obtain the consumption of the readings of a meter. The consumption is obtained through some property and then I obtain the total consumption in another property. class ConsumoElect(models.Model): pgd = models.ForeignKey(TipoPGD, on_delete=models.CASCADE, related_name='consumoelect') fecha = models.DateField(default=datetime.now) fecha_AM = models.CharField(max_length=20) lec_madrugada = models.IntegerField(default=0) lec_dia = models.IntegerField(default=0) lec_pico = models.IntegerField(default=0) reactivo = models.IntegerField(default=0) dato = models.IntegerField(default=0) total = models.IntegerField(default=0) def __str__(self): return '%s' % (self.pgd) def get_cm(self): c_m = list(ConsumoElect.objects.filter(pgd=self.pgd).filter(fecha__gt=self.fecha).order_by('fecha').values('lec_madrugada', 'fecha')) if not c_m: return 0 else: if not c_m[0]['lec_madrugada']: return 0 else: return ((c_m[0]['lec_madrugada'] - self.lec_madrugada)) consumo_m= property(get_cm) def get_cd(self): c_d = list(ConsumoElect.objects.filter(pgd=self.pgd).filter(fecha__gt=self.fecha).order_by('fecha').values('lec_dia')[0:1]) if not c_d: return 0 else: if not c_d[0]['lec_dia']: return 0 else: return ((c_d[0]['lec_dia'] - self.lec_dia)) consumo_d= property(get_cd) def get_cp(self): c_p = list(ConsumoElect.objects.filter(pgd=self.pgd).filter(fecha__gt=self.fecha).order_by('fecha').values('lec_pico')[0:1]) if not c_p: return 0 else: if not c_p[0]['lec_pico']: return 0 else: return ((c_p[0]['lec_pico'] - self.lec_pico)) consumo_p= property(get_cp) def get_total(self): return (self.consumo_d + self.consumo_m + self.consumo_p) consumo_total= property(get_total) def save(self, *args, **kwargs): fe=date.strftime(self.fecha, "%Y-%m") self.fecha_AM = fe self.total = self.consumo_d + self.consumo_m + self.consumo_p return super().save(*args, **kwargs) class Meta: unique_together=['pgd', 'fecha'] verbose_name = 'Consumo Electrico' verbose_name_plural = 'Consumo Electrico' ordering = ['pgd', 'fecha'] db_table … -
Django unable to submit form, getting error 'Select a valid choice. That choice is not one of the available choices'
I have a django form in which, 'Select_Category' will be filtered based on the value selected in 'Select_Type'. I am using an Ajax query to achieve this. When executing, I can see the filter is working properly as expected. But when I click submit, I get error on page 'Select a valid choice. That choice is not one of the available choices' and the 'Select_Category' filed is getting emptied. forms.py class Test_Form(forms.Form): Select_Type = forms.ChoiceField(choices=[('Incoming', 'IN'), ('Outgoing', 'OUT')], initial='Outgoing') Select_Category = forms.ModelChoiceField(queryset=Categories.objects.all()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['Select_Category'].queryset=Categories.objects.none() Since the form is not being submitted, I suspect some issue with my forms.py. Can someone help? -
Django Serializer to group fields
I want to build a simple endpoint /users/ that returns output like the following: { ids: [ "e3fa5cbe-e89e-4017-bbd3-546019247932", "94c1f979-f122-471b-a694-e748f5d95c25", "30f20792-18d9-4db0-8dde-9ad62d239928", "2ee0399d-881a-43b5-ad53-a741507e12c1", "359b6550-bcfd-4c41-99be-3422cbba3da5" ] } The id's belong to the user objects themselves. I have a model viewset defined as such: class UserIdViewSet( viewsets.ModelViewSet, mixins.ListModelMixin, ): queryset = User.objects.all() permission_classes = [IsAdmin] serializer_class = IdListSerializer filterset_class = UserFilter def get_queryset(self): return User.objects.filter( company=self.request.user.get_company() ) But I am having difficulty writing IdListSerializer. ChatGPT and Copilot suggest variations of the following: class IdListSerializer(serializers.Serializer): ids = serializers.ListField(child=serializers.UUIDField()) def to_representation(self, instance): return {"ids": [str(user.id) for user in self.objects.all()]} But instance is not itterable. We really want the collection not the instance. Is this possible using DRF without resorting to an APIView? -
OpenSlide for django can't open tif format (and also other formats)
I'm trying to write adjust zoomable image app viewer for digital pathology and using django with python and OpenSlide. and the last one can't open tif (and also other formats) image that i upload. here is the error after uploading: OpenSlideUnsupportedFormatError at /upload_image/ Unsupported or missing image file how i can fix it? i'm sure that's images is saved in a supported format with openslide. -
Django Custom API Endpoint with two parameters
I want to build a fairly simple API endpoint in a Django app I inherited. I'm new to python and Django The app uses views.py with classes that extend ModelViewSet. It also uses a urls.py with entries like this: router.register('agent_licenses', views.AgentLicenseViewSet) and this one I came up with: router.register(r'agent_licenses/(?P<agent_id>\d+)/<state_id>\d+/', views.AgentLicenseViewSet) I need to build the fastest-responding endpoint possible and so I plan to use a custom SQL query that returns a True/False. Is there some straightforward way to build an endpoint (hopefully in views.py, although if that's not possible, that's ok.) that will show up in Swagger without having to wrestle with Models, ModelViewSet, urls.py, Serializers, etc? I have managed to get close, using the AgentLicenseViewSet, like this: (Ignore the actual code in the endpoint method - it's just test code at this point) class AgentLicenseViewSet(viewsets.ModelViewSet): """Agent license REST view """ queryset = models.AgentLicense.objects.all() serializer_class = serializers.AgentLicenseSerializer filter_backends = (django_filters.DjangoFilterBackend,) filterset_class = filters.AgentLicenseFilter @action(methods=["GET"], detail=True) # def has_license_in_state(self, agent_id: int, state_id: int) -> Response: def has_license_in_state(self, *_args, **_kwargs ) -> Response: #print(state_id) #print(pk) # return Response(data={'message': False}) return Response(data=False) # return False But - when I run this, I get an endpoint that appears to be ignoring the \d+ in … -
(Django) How can I enable cross site verification to my website?
I am building a third party comment section. How can I allow users to sign into my website and make comments on others sites? I already have the scripts for users to import but I can’t seem to allow users to sign in and pass a “request” to my website. I’m using django by the way. -
Vue Static files are not loading
So I am developing a django application and using vue for frontend. I have connected the vue app and the django app using views.py. But when I am trying to run the application for some reason django is not loading the static files properly. Here is my settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-^**********************************' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'store_closure.apps.StoreClosureConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'corsheaders', 'CapstoneProject', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware' ] ROOT_URLCONF = 'CapstoneProject.urls' CORS_ORIGIN_ALLOW_ALL = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'CapstoneProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'postgres', 'PASSWORD': '*****', 'HOST': 'localhost', 'PORT': '5432', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True ROOT_PATH = os.path.dirname(__file__) STATIC_URL = '/static/' # STATIC_ROOT = 'var/static_root/' STATICFILES_DIRS = … -
Allow locally hosted Django App Access over WAN
I am currently working on developing a webapp and working with a partner on the other side of the state. I would like to allow them to access the webapp for testing and development purposes but cant seem to be able to figure out how to get the connection working. I have enabled port forwarding for port 8000 and have already attempted to run the server using my local IPv4 address. I can connect via LAN, but my partner cannot connect through their browser. We already have an established MySQL connection and all we had to do was forward port 3306 and use my router IP for WAN but that does not seem to be working for Django. Any suggestions on getting this working? -
Iterate over Django Model object to translate (translate 3.6.1) specific fields (all TextFields and all JSONFields)
How does one iterate over a Django Model object to translate all TextFields and all JSONFields before sending to template. Let me elaborate. I have a Django model models.py like the following: SOME_TEXT_CHOICES = ( ('choice_one', _('Choice One')), ('choice_two', _('Choice Two')), ('choice_three', _('Choice Three')) ) from django.db import models class SomeModel(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) some_title = models.CharField(max_length=100, null=False, blank=False) some_address = models.CharField(max_length=100, blank=True) sometime = models.TimeField(default=datetime.time(15, 00)) some_choices = models.CharField(max_length=15, choices=SOME_TEXT_CHOICES, null=False, blank=False) some_text_one = models.TextField(max_length=1000, null=False, blank=False) some_text_two = models.TextField(max_length=1000) some_json_field = models.JSONField(help_text=_('JSON field: {"key_text1":"value_text1","key_text2":"value_text2"}'), null=True, blank=True) And I have a views.py: from django.shortcuts import render, get_object_or_404 from translate import Translator from .models import SomeModel def detail_view(request, slug): context = {} context_somemodel = get_object_or_404(SomeModel, slug=slug) translator = Translator(from_lang='en', to_lang='es') # How to iterate through the context_somemodel to update all # TextField(s) and JSONField(s) with the translator.translate() method # before sending to the template? context['somemodel'] = context_somemodel return render(request, 'templates/detail_template.html', context) The original content of the model is in English and it should be translated into Spanish. I tried to update/translate a single field with SomeModel.objects.filter(slug=slug).update(some_text_one=translator.translate(F('some_text_one'))) but I get an error message: name 'F' is not defined. -
How to find this function
See code below. It is crashing at the line import_recording(info, recording_path) The problem is, I can't debug this function because I cannot find where import_recording() is defined. I do not see it in any of our files, and I can't find any helpful info from Callable, typing, or @logme.log. I believe it is calling on info from a db, and we have the correct info in the db, but it is not possible to verify this without access to this function. How can I find where this function is defined? #!/usr/bin/env python3 # -*- coding: UTF-8 -*- import os from pathlib import Path from typing import Callable import logme # type: ignore from typing_extensions import Literal from librecval.extract_phrases import AudioSegment, RecordingExtractor, Segment from librecval.recording_session import parse_metadata from librecval.transcode_recording import transcode_to_aac ImportRecording = Callable[[Segment, Path], None] class RecordingError(Exception): """ The error that gets raised if something bad happens with the recording. """ Format = Literal["wav", "m4a"] @logme.log def initialize( directory: Path, transcoded_recordings_path: str, metadata_filename: Path, import_recording: ImportRecording, recording_format: Format = "m4a", logger=None, ) -> None: """ Creates the database from scratch. """ dest = Path(transcoded_recordings_path) assert directory.resolve().is_dir(), directory assert ( dest.resolve().is_dir() ), f"audio destination is not a folder: {dest.resolve()}" assert metadata_filename.resolve().is_file(), …