Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using for loop in django channels async consumer
I'm using AsyncConsumer for my app and at some point I realized I need to use a for loop to iterate through a queryset but I'm facing asynchronous issues. My code looks something like this: class ChatConsumer(AsyncConsumer): ... async def websocket_receive(self, event): .... chatgroup = await self.get_chatgroup(self.group_id) for member in chatgroup.member_chatgroup.all(): await self.new_notification() ... async def new_notification(self, member, message): await self.channel_layer.group_send( self.notification_group_name, { "type": "notify.message", "message": message, } ) Now I know that's totally incorrect, but the thing is I don't know what is correct, and I didn't find any answer on the internet. So I'd appreciate any useful help. -
How to Disable Preselection List Display from Django Admin
Hi I want to disable the preselection from django admin, here is my code from django.contrib import admin from django.db import models class Person(models.Model): name = models.CharField(max_length=50) birthday = models.DateField() def decade_born_in(self): return self.birthday.strftime('%Y')[:3] + "0's" decade_born_in.short_description = 'Birth decade' class PersonAdmin(admin.ModelAdmin): list_display = ('name', 'decade_born_in') -
How to convert python list to JSON array?
If I have python list like pyList=[‘x@x.x’,’y@y.y’] And I want it to convert it to json array and add {} around every object, it should be like that : arrayJson=[{“email”:”x@x.x”},{“ email”:”y@y.y”}] any idea how to do that ? -
Django - How I get a value from form and send it using a button?
I would like to get value from SKU field to GET request using button "Buscar medidas", that will call a function "fretemagalu" in my views.py (replacing test with SKU value) <p> <label for="sku"><b>SKU</b></label><br> <input id="sku" type="text" name="sku" value="{{ sku }}"> <button class="btn btn-primary ml-2" type="button" onclick="location.href='{% url 'fretemagalu' 'test' %}'">Buscar medidas</button> </p> The example from the form is in image bellow. Thanks in advanced. Form -
Nginx 502 bad getaway in Django register and login page
I've deployed a Django app with nginx and gunicorn. It's works fine except it's login form and register form. When I submit either of forms I get "502 bad get away" error message. /etc/nginx/sites-available/config server { listen 80; server_name croyal.net; server_name www.croyal.net; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
AttributeError: 'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute 'append' When running django gunicorn server
I have developed a road segmentation model with django. It works fine on development server. I am testing the application with gunicorn server. The application loads a tensorflow based Unet model from .h5 file. The model gets loaded successfully on development server. But not on gunicorn. System check identified no issues (0 silenced). April 23, 2022 - 10:23:03 Django version 4.0.4, using settings 'segmentation_site.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Works perfectly on development server. But not on production gunicorn --bind 127.0.0.1:8000 segmentation_site.wsgi.application [2022-04-23 03:24:15 -0700] [8192] [INFO] Starting gunicorn 20.0.4 [2022-04-23 03:24:15 -0700] [8192] [INFO] Listening at: http://127.0.0.1:8000 (8192) [2022-04-23 03:24:15 -0700] [8192] [INFO] Using worker: sync [2022-04-23 03:24:15 -0700] [8194] [INFO] Booting worker with pid: 8194 2022-04-23 10:24:16.356150: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory 2022-04-23 10:24:16.356246: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. tensorflow imported. 2022-04-23 10:24:19.782405: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory 2022-04-23 10:24:19.782526: W tensorflow/stream_executor/cuda/cuda_driver.cc:269] failed call to cuInit: UNKNOWN ERROR (303) 2022-04-23 … -
How to map the login template with built-in login form in Django?
I am quite new to Django and I am trying to create login template. I avoid using crispy-forms to have more control and knowledge on how the data is displayed on website. I am using Django built-in login form. Unfortunately I am stuck, because my current login.html seems to be invalid and nothing happens after sending POST with username and password. This is how it looks like: login.html <main class="form-signin"> <form method="post" class="from-group"> <h1 class="display-3 text-center mb-4 fw-normal" style="font-family:'Faster One'; box-shadow: none;">Test</h1> <h1 class="h3 mb-3 fw-normal">Please sign in</h1> {% csrf_token %} <div class="form-floating"> <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com"> <label for="floatingInput">Username</label> </div> <div class="form-floating mt-3"> <input type="password" class="form-control" id="floatingPassword" placeholder="Password"> <label for="floatingPassword">Password</label> </div> <button class="w-100 btn btn-lg btn-primary" type="submit" value="Log in">Sign in</button> </form> </main> urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('accounts/', include("django.contrib.auth.urls")), ] [23/Apr/2022 09:59:41] "POST /accounts/login/ HTTP/1.1" 200 2358 [23/Apr/2022 09:59:46] "POST /accounts/login/ HTTP/1.1" 200 2358 POST is sent with 200 OK message, but besides that nothing happens - I am still in the login page, user is not authenticated, validation doesn't work etc. So my question is what I did wrong and how does the mapping between login form/view and html template works exactly? -
'str' object has no attribute 'all',
I want to get last data choiced by the user of a field1(a foreignkey type) from a form1(model1) already submitted and display it on a another field2(Exist on form2(model2)), Here is my models.py: Model1: field1 = models.ForeignKey(ProfileSize, on_delete=models.CASCADE) Model2: field2 = models.ForeignKey(ProfileSize, on_delete=models.CASCADE) The story that I have declared a field2 as a foreignkey in model2 and I have did ModelChoiceField in forms.py To display to me just the last data entered by the user in the field1(exist in the form1) , Here is my forms.py: class FormAssembly(forms.ModelForm): field1 = forms.ModelChoiceField(queryset=Model1.objects.none(),) I have did it with this queryset in views.py def assembly(request): if request.method == 'POST': form = FormAssembly(request.POST, ) form.fields['field2'].queryset = Model1.objects.filter(user=request.user).last().field1.name it shows me error 'str' object has no attribute 'all', My Question how i can filter correctly the foreignkey to get data from another form using the queryset, -
Django no reverse match on heroku but not locally
I am getting NoReverseMatch at /post/1/ Reverse for 'blog_home' not found. 'blog_home' is not a valid view function or pattern name. this error on my django website hosted on heroku, but the code works fine when I host the website locally. I think that it has something to do with heroku. My urls.py urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail') ] Error: Environment: Request Method: GET Request URL: http://<appname>.herokuapp.com/post/1/ Django Version: 2.2.1 Python Version: 3.9.0 Template error: In template /app/django_web_app/blog/templates/blog/base.html, error at line 0 Reverse for 'blog_home' not found. 'blog_home' is not a valid view function or pattern name. 1 : {% load staticfiles %} 2 : <!doctype html> 3 : <html lang="en"> 4 : <head> 5 : 6 : <!-- Required meta tags --> 7 : <meta charset="utf-8"> 8 : <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 9 : 10 : Exception Type: NoReverseMatch at /post/1/ Exception Value: Reverse for 'blog_home' not found. 'blog_home' is not a valid view function or pattern name. Python version: 3.9 Django version: 2.2.1 -
Many to Many relationship between different types of users - Django
I am building a toy project consisting in a healthcare information system. I want to have two types of users: patients and doctors. A patient could have multiple doctors and a doctor could have multiple patients. What is the best way to represent this relationship? Currently I have something similar to this: class User(AbstractUser): def serialize(self): return { "id": self.id, "username": self.username, } class Doctor(models.Model): user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user)) patients = models.ManyToManyField(Patient) class Patient(models.Model): user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user)) doctors = models.ManyToManyField(Doctor) However I'm pretty sure this doesn't work. What is the right way to represent this type of relationship using django models? Thanks! -
Invalid field name(s) given in select_related: 'images'. Choices are: user_changed, video, prices, attributes, apiconnections
models.py: class ProductModel(models.Model): name = models.CharField(max_length=150, unique=True) type = models.CharField(max_length=100, blank=True) sku = models.CharField(max_length=100, unique=True) barcode = models.CharField(max_length=50, unique=True) description = models.TextField(blank=True) categories = models.ManyToManyField(CategoryModel, blank=True) video_url = models.CharField(max_length=190, blank=True) datetime_created = models.DateTimeField(auto_now_add=True) datetime_updated = models.DateTimeField(auto_now=True) user_changed = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) old_id = models.CharField(max_length=50, unique=True, blank=True, null=True, default="") def __str__(self): return self.name class Images(models.Model): product_id = models.ForeignKey(ProductModel, db_index=True, on_delete=models.CASCADE, verbose_name='Товар') image = models.ImageField(upload_to="products/images/", blank=True, default="products/noimage.jpeg") image_small = models.ImageField(upload_to="products/images_small/", blank=True, default="products/noimage.jpeg") image_ori = models.ImageField(upload_to="products/images_ori/", blank=True, default="products/noimage.jpeg") default = models.BooleanField(default=False) def __str__(self): return self.product_id.name class Video(models.Model): product_id = models.OneToOneField(ProductModel, db_index=True, on_delete=models.CASCADE) video = models.FileField(upload_to="products/videos/", blank=True) def __str__(self): return self.product_id.name in views.py this code works perfectly: products = ProductModel.objects.all().select_related('prices', 'apiconnections', 'video').prefetch_related('categories') while this one gives me error Invalid field name(s) given in select_related: 'images'. Choices are: user_changed, video, prices, attributes, apiconnections: products2 = ProductModel.objects.all().select_related('images') I've also tried to use prefetch_related to connect all my images to products. It didn't work. -
Remove default preselction from Django admin
Heyy guys, In my djan admin all the filter are getting pre selected by default and i do not want to do that ,can any one please help me . I do not want see all the filter getting preselcted . -
display user information with their corresponding profile picture in a table
I want to display user information from Django default User model in the table with their profile picture my Profile model is `class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) forget_password_token = models.CharField(max_length=100) image = models.ImageField(upload_to="images",default="default/user.png") def str(self): return f'{self.user} profile' ` I want to do like this user data in the profile column i want to display user profile picture please help me to achieve this -
How to place multiple values in another column by selecting one option?
I want to Select one option and auto-fill up the other column. For example: | Product Name| Price | | ----------- | --------- | | T-Shirt | 100 | | Mobile | 200 | | Laptop | 500 | Now, i will select Product Name and price will place automatically. To be clear please check the image! and Video -
I get this error when i try use django allauth
Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 455, in execute self.check() File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/usr/local/lib/python3.8/dist-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.8/dist-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/usr/local/lib/python3.8/dist-packages/django/core/checks/urls.py", line 61, in _load_all_namespaces url_patterns = getattr(resolver, "url_patterns", []) File "/usr/local/lib/python3.8/dist-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.8/dist-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py", line 689, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/platon/python/django/itmagazine/itmagazine/urls.py", line 27, in <module> path('accounts/', include('allauth.urls')) File "/usr/local/lib/python3.8/dist-packages/django/urls/conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.8/importlib/__init__.py", line … -
How can solve this problem to apply that for loop for every line of that csv file?
When i try this for loop to add data with a csv file it just adds the data of last line in csv file. from django.db import models # Create your models here. class product(models.Model): Number=models.CharField( max_length=40 ) name=models.CharField(max_length=40 ) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) p=product() f = open('b.csv', 'r') for line in f: line = line.split(',') p.Number=line[0] p.name=line[1] p.image=line[2] p.description=line[3] p.price=line[4] p.buy=line[5] p.save() f.close() csv file: Number,name,image,description,price,buy 1,a,1,1,1,1 2,bb,2,2,2,2 3,aa,3,3,3,3 4,bd,4,4,4,4 5,d,5,5,5,5 6,e,6,6,6,6 there is just one product with the data of last line of csv file: How can solve this problem to apply that for loop for every line of that csv file? -
OperationalError at /admin/ no such table: User
Here I have creates user model and inherited AbstractUser to the user model. but No such table showing here, I did migrations also but it is not showing. Please tell me what to do: Error: OperationalError at /admin/ no such table: User Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 3.2.13 Exception Type: OperationalError Exception Value: no such table: User Exception Location: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['E:\\Project\\S3_project', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Manoj\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Sat, 23 Apr 2022 09:10:23 +0000 models.py: class User(AbstractUser): address = models.TextField(max_length=500,null=False) contact_number = models.PositiveIntegerField(null=False) ut=(('Admin','Admin'),('Operator','Operator'),('Ticket generator User','Ticket generator User'),('Inspector','Inspector'),('User 80','User 80'),('Final Inspection','Final Inspection'),('Maintenance','Maintenance'),('Ticket admin','Ticket admin')) user_type = models.CharField(max_length=100,null=False,choices=ut) class Meta: db_table = "User" forms.py: class UserForm(forms.ModelForm): class Meta: model=User fields=['first_name','last_name','address','contact_number','user_type','username','password'] widgets = {'first_name': forms.TextInput(attrs={ 'class': 'form-control'}), 'last_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'address': forms.Textarea(attrs={ 'class': 'form-control' }), 'contact_number': forms.NumberInput(attrs={ 'class': 'form-control' }), 'user_type': forms.Select(attrs={ 'class': 'form-control' }), 'username': forms.TextInput(attrs={ 'class': 'form-control' }), 'password': forms.PasswordInput(attrs={ 'class': 'form-control' }) } settings.py: AUTH_USER_MODEL = 'Master.User' admin.py: admin.site.register(User) -
Is there anyway to compare two fields in two models and store a field in the first model in Django?
class Register(models.Model): prollno=models.CharField(max_length=8) full_name=models.CharField(max_length=100) drollno=models.CharField(max_length=9) email=models.EmailField() gender=models.CharField(max_length=7,default="Male") programme=models.CharField(max_length=100) course=models.CharField(max_length=100) yearofstudy=models.CharField(max_length=5) phone=models.BigIntegerField() city=models.TextField() pincode=models.IntegerField() address=models.TextField() isblacklisted=models.BooleanField(default=False) class Blacklist(models.Model): prollno=models.ForeignKey(Register) full_name=models.CharField(max_length=100) email=models.EmailField(max_length=55) phone=models.BigIntegerField() I have two models Register and Blacklist and I have to compare the prollno of Register and Blacklist and if the values stored in both prollno are same, then I have to save the field isblacklisted of Register Model to True. -
Filter queryset of django inline formset based on attribute of through model
I have a basic restaurant inventory tracking app that allows the user to create ingredients, menus, and items on the menus. For each item on a given menu, the user can list the required ingredients for that item along with a quantity required per ingredient for that item. Menu items have a many-to-many relationship with ingredients, and are connected via an "IngredientQuantity" through table. Here are my models: class Ingredient(models.Model): GRAM = 'Grams' OUNCE = 'Ounces' PIECE = 'Pieces' UNIT_CHOICES = [ ('Grams', 'Grams'), ('Ounces', 'Ounces'), ('Pieces', 'Pieces') ] user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=200) unitType = models.CharField(max_length=200, choices=UNIT_CHOICES, verbose_name='Unit') unitCost = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Unit Cost') inventoryQuantity = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Quantity') def __str__(self): return self.name + ' (' + self.unitType + ')' def totalCost(self): result = self.inventoryQuantity * self.unitCost return "{:.0f}".format(result) class Menu(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=200) timeCreated = models.DateTimeField(auto_now_add=True) timeUpdated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.name) class MenuItem(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=200) price = models.DecimalField(max_digits=10, decimal_places=2) ingredients = models.ManyToManyField(Ingredient, through='IngredientQuantity') menu = models.ForeignKey(Menu, on_delete=models.CASCADE, null=True) def __str__(self): return self.name def itemCost(self): relevantIngredients = IngredientQuantity.objects.filter(menuItem=self) cost = 0 for ingredient in relevantIngredients: cost += (ingredient.ingredient.unitCost * ingredient.ingredientQuantity) … -
How to change the status code that is recieved in the response in case of specific exceptions in Django rest framework
I am adding some details to my Django model from a react frontend. Everything is working fine and the API request is made with Axios. The data that is being submitted is an OneToOne Field with the user and hence submitting more than once raises an Integrity error of Unique Constraint. But the response I receive back has a status of 200. This triggers a notification in my frontend that says details submitted every time the button is pressed. However. that is not being submitted the second time because of the Integrity Error. My question is if I handle the Integrity Error exception separately how can I send a different status rather than 200 as shown below config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} data: {message: 'UNIQUE constraint failed: teacher_teacherdetail.user_id'} headers: {content-length: '39', content-type: 'application/json'} request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "OK" Currently I am handling the exception as below try: # some code except IntegrityError as e: message = { "error": str(e) } return Response(message) except Exception as e: message = { "message": "exception", "error": str(e) } return Response(message) -
How to synchronize Django database migration on VPS and inside django container?
I have a task to set up work with migrations. In this photo I am on the VPS and when I try to see apps migrations, there is only one migration file(0001_initial.py) in every app. And for example if I change something in models.py and run 'makemigrations & migrate' commands, the new migration file won't appear here on the VPS, it will only appear inside the django container And the question here is how can I set up migrations so that when I run docker-compose -f docker-compose.dev.yml exec web_dev python manage.py makemigrations docker-compose -f docker-compose.dev.yml exec web_dev python manage.py migrate commands from the VPS, migration files appear here in the VPS and not only inside the django container? -
Django with DRF APIs slows down after few weeks or months
I have Django with DRF sight and it has couple of APIs based on DRF with GenericAPI view and API view. The APIs is used to calculate XML vs XML and JSON vs JSON differences. Two objects are passed as body to these APIs and the API returns the no of differences and exact nodes at which the differences are found. It also respond with nodes which are added or removed. The sight and APIs work just fine when my environment is just up and running for few weeks say 2 weeks. I have recently observed that after a month or 3 weeks same APIs takes much more time to calculate the differences with same set of data. Usually it is very fast for example If we have large JSON object then 1k differences per second is processed. If we have pretty small JSON or XML object like 5 to 10 keys (very basic) the main library function which calculates the difference tales just about few milliseconds. So overall API time is like 200 ms. Now the issue that I have is after lets say 3 weeks or a month same very basic JSON object comparison (with just 5-10 keys) … -
What can i do to add a.csv data to my fields in django?
In this code i have a for loop that wants to add a.csv data to my django fields but when i run the server there is no data in fields of product model. from django.db import models # Create your models here. class product(models.Model): Number=models.CharField( max_length=40 ) name=models.CharField(max_length=40 ) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) p=product() f = open('a.csv', 'r') for line in f: line = line.split(',') p.Number=line[0] p.name=line[1] p.image=line[2] p.description=line[3] p.price=line[4] p.buy=line[5] p.save csv: Number,name,image,description,price,buy What can i do to add that csv data to my fields? -
Django Internationalization gettext() Not Creating message files from JavaScript source code
I am working with django internationalization. I did all setup its working fine in templates and .py files. I tried to create a translation text in .js file I setup that like This documentaion. After the setup I used the gettext() in my js file is not showing the error in console. Then I use the command to create messages file django.po using this command django-admin makemessages -d djangojs -l ta and the translation text not added in django.po file. urls.py urlpatterns = i18n_patterns( ..., path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), prefix_default_language=False ) js file console.log(gettext('Javascrit gettext')) //Print the text in console it was working. -
Folium - Django: How to make a folium marker a link to another page
I'm generating a map using Folium with Django like so: views.py def viz(request): dg_map= folium.Map(location=[50.38175,6.2787], tiles= 'https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png?api_key=<MY_API_KEY>', attr= '&copy; <a href="https://stadiamaps.com/">Stadia Maps</a>, &copy; <a href="https://openmaptiles.org/">OpenMapTiles</a> &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors', zoom_start=10) map_details = fetch_data("SELECT id, firstname, lat, long FROM map_details") #helper func to query the DB for item in map_details: location = [item[2], item[3]] popup = f"{item[1]}'s Garden" marker = folium.Marker( location = location, popup = popup, icon=folium.Icon(color='darkgreen', icon="heart", prefix='fa')) marker.add_to(dg_map); m = dg_map._repr_html_() context = {'map': m} return render(request, 'accounts/viz.html', context) This is working as expected. However, I'd like each marker to redirect towards another page on-click. To make matters worse, I'd need to use the id that's querried in the SELECT statement and include it in the destination link, because the urlpattern of the destination pages is this: urls.py path('garden/<str:id>/', views.garden, name="garden"). What I found out so far: I found several suggestions on how to add an href to the pop-up (e.g. here) but this is not what I want as it requires the user to click twice. Some ideas on how to add custom js to Folium's output are mentioned here, but I think it's not implemented yet. I also found instructions on how this can be done …