Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PostDetail.post() got multiple values for argument 'slug'
I am trying to submit comments on my blog posts but I get faced with this traceback every time. When it succeeds the comment will then be subjected to moderation before showing on the website. If I could get any help it would be greatly appriciated! Here is the traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/blog/cubs/post/should-be-the-final-test-lmao/ Django Version: 4.1.2 Python Version: 3.10.6 Installed Applications: ['beavers.apps.BeaversConfig', 'cubs.apps.CubsConfig', 'scouts.apps.ScoutsConfig', 'accounts.apps.AccountsConfig', 'executive.apps.ExecutiveConfig', 'main_website.apps.MainWebsiteConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sitemaps', 'django.contrib.staticfiles', 'django_summernote', 'crispy_bootstrap5', 'taggit_helpers', 'taggit_labels', 'debug_toolbar', 'admin_reorder', 'crispy_forms', 'storages', 'taggit'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'admin_reorder.middleware.ModelAdminReorder') Traceback (most recent call last): File "/home/kiza054/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/kiza054/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kiza054/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "/home/kiza054/.local/lib/python3.10/site-packages/django/contrib/auth/mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/kiza054/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch return handler(request, *args, **kwargs) Exception Type: TypeError at /blog/cubs/post/should-be-the-final-test-lmao/ Exception Value: PostDetail.post() got multiple values for argument 'slug' PostDetail (views.py) class PostDetail(LoginRequiredMixin, DetailView): model = Post form_class = CommentForm template_name = "cubs/post_detail.html" def get_form(self): form = self.form_class(instance=self.object) return form def post(self, slug, *args, **kwargs): new_comment = None pk … -
Python: Need guidance with a dropdown list
I took over a web app from a user who left the company and I don't know what I'm doing. Basically I have a site table that has 2 columns I need, site and name. I want the name to display in the dropdown menu and site to be the value of the dropdown. This what it looks like now: In the views template def getWarehouseList(): warehouse_list = ['Warehouse'] + pd.DataFrame.from_records(Site.objects.filter(active=True).values('site')).sort_values('site')['site'].tolist() return tuple([(choice, choice) for choice in warehouse_list]) In the html/view: <select id="warehouse\_drop" name = "warehouse"> {% for warehouse in warehouse\_list %} <option value ="{{warehouse}}">{{ warehouse }}</option> {% endfor %} </select> How can I change the option value to be "name" instead of "site" (warehouse). Thank you. -
Django 'utf-8' codec can't decode byte 0x99 in position 5289: invalid start byte
I work on a website with python, before I change my database from sqlite to mysql I saves it as a json file python manage.py dumpdata > datadump.json after I changed my settings.py to the mysql database and migrate is I wanted to move data to mysql db by: python manage.py loaddata datadump.json but it cause this error: File "C:\Users\M.Hawa\Desktop\My_Django_Stuff\firstproject\deneme\lib\site-packages\django\core\serializers\json.py", line 67, in Deserializer stream_or_string = stream_or_string.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0x99 in position 5289: invalid start byte Not: I tried to change stream_or_string = stream_or_string.decode() to: stream_or_string = stream_or_string.decode("UTF-16") but it did not work I looking for solutions -
how to user django rest framework serializer outside of django in python console
I am using a DRF serializer in my project as below # my_serrializers.py from rest_framework import serializers class TssUpdateExtraVarsSerializer(serializers.Serializer): cluster_name = serializers.CharField(required=True) class TssUpdateSerializer(serializers.Serializer): extra_vars = TssUpdateExtraVarsSerializer(required=True) It works fine when I send a request and it handles the job. But if I open a python console (the one in my project's venv) as below: #python console from my_serializers import TssUpdateSerializer s = TssUpdateExtraVarsSerializer(data={"a": 1}) s.is_valid() I get this error django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. what is the reason for it and how to fix it. I want to be able to play with it outside of django. is it possible? how? -
I'm excluding the objects with None value, but all of them are being returned, why?
I'm using a function to get the URL and avoid the link if the foreign key (cve) is none. def get_absolute_url(self): try: return reverse('detail', args=[self.cve, self.id) except NoReverseMatch: pass But, where I'm using these URLs, I'm also FILTERING to exclude when the fk is None. class VSitemap(Sitemap): def items(self): return Vuln.objects.exclude(cve__in=[]).exclude(cve=None) Thus, I'm getting this: <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> <url> <loc>https://example.ioNone</loc> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> Everything I'm getting Is None even if I filter too much. -
How can I get the cards to appear next to each other in a row to fill up the grid before starting a new row?
I have data from a table and the cards are being created from that data and rendered onto the screen. However, they appear beneath each other on the left side rather than filling up a row first before starting a new row: (https://i.stack.imgur.com/dDgvB.png) My code is: <div class="container"> {% for class in all_classes %} </br> <div class="row-sm-3"> <div class="col-sm-4"> <div class="card-deck"> <div class="card text-center"> <div class="card-body"> <h5 class="card-title">{{ class.class_name}}</h5> <p class="card-text">{{class.teacher_id.username }}</p> <a href="#" class="btn btn-primary">Go To</a> </div> </div> </div> </div> {% endfor %} </div> How can I fix this? -
How can I analyze Django ORM query performance on a server with DRF Endpoints only?
Previous Django apps I've worked on have used HTML template rendering, and django-debug-toolbar has proven to be a valuable way to analyze ORM SQL queries and find places to optimize. The current app I'm working on uses Django for django-rest-framework REST endpoints only, and has no HTML views. Is there a way I can analyze queries in a similar way? I looked into django-debug-toolbar + django-debug-panel (with a Chrome extension), but it's quite a bit out of date, requiring Django 2.1 or earlier. -
Error Unable to lock the administration directory (/var/lib/dpkg/) are you root?
I am in my distant server ovhCloud whose python is version 3.5.3 and I would like to update it to 3.10 I have this error (Unable to lock the administration directory (/var/lib/dpkg/) are you root ?) and even the sudo command is not recognized `bele@cloudweb-ssh:˜ $ sudo apt update bash:sudo:command not found` How to solve this? I tried also su root I get permission denied -
My site is not displayed in the Google search list
I just uploaded a site with Django on pythonanywhere and it was indexed by Google and it is displayed in the English search list, but it is not displayed in the Persian search list. This is my website link: https://peshgaman.pythonanywhere.com/ I registered my site in google search console and also created a sitemap for my site -
Django throw empty validation error on admin field when using filter_horizontal. is it normal?
I have ThesisExamSchedule model that I registered in admin using ModelAdmin. class ThesisExamSchedule(models.Model): participant=models.ForeignKey(User,on_delete=models.CASCADE,related_name="thesis_participant") room=models.TextField() date=models.DateField() start_time=models.TimeField() end_time=models.TimeField() thesis_title=models.TextField() examiner=models.ManyToManyField(User) def __str__(self) -> str: return self.participant.first_name class ThesisExamScheduleAdmin(admin.ModelAdmin): list_display=['participant','date','start_time','end_time','thesis_title'] filter_horizontal=['examiner'] autocomplete_fields=['participant'] admin.site.register(ThesisExamSchedule,ThesisExamScheduleAdmin) After I choose multiple users to fill examiner field then hit save. Django admin throw empty validation error and the examiner field emptied. Scenario 1 validation error throwed: choose users from left box. chosen user show on the right box. validation error throwed. Scenario 2 Success: choose users from left box. chosen user show on the right box. select user (highlight the user). submit success. Is it normal? My expectation is there will be no error when using scenario 1 -
use python to estimate probability
Use python to estimate the probability. There are three Urns (A, B and C), which each contains the following balls: A: 1 white, 2 black and 3 red balls B: 2 white, 1 black and 1 red balls C: 4 white, 5 black and 3 red balls One urn is chosen at random and two balls are drawn which are white and red. What is the probability that they came from urn B or C? # It is easy to use Bayes' theorem to calculate the exact probability(the answer is 85/118), but when using "random" to estimate the probability in python, it is rather difficult. Can you help me? Thanks! -
Is there a solution to load html without asking me to store them in static folder?
My index is loading well on browser, but when I click home page, there is nothing 404 error, is responding static/index.html, (when I click home page or any other such as contact, it is searching for html in static) why is it asking for index.html in static files and how can I rectify that?[ I stored my html files on templates folder thinking that when i clicked my dropdown, they were going to apper on my web. -
Using Cache in UserViewSet in djoser in django / djangorestframework
i am currently using cache_page from decorators in django rest framework to cache the api. For authentication I am using djoser with django rest framework, but i dont understand how i can add cache_page decorator in djoser urls. This is my one of the viewset for cache class TagViewSet(viewsets.ModelViewSet): queryset=Tags.objects.all() serializer_class=TagSerializer permission_classes=[permissions.IsAuthenticated] authentication_classes= [authentication.TokenAuthentication] #Cache @method_decorator(cache_page(30)) def dispatch(self, *args, **kwargs): return super(TagViewSet, self).dispatch(*args, **kwargs) i want exactly the same with djoser urls but i dont have the userviewset and i dont know how to access it. views.py (user) empty Please guide me how i can add cache_page for djoser urls -
Group every objects by year
I had 3 objects [{u'criados': u'25/10/2022 00:50', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/9.pdf', u'id': 1, u'tipo': u'NAI', u'slug': u'Teste-1'}, {u'criados': u'25/10/2022 23:54', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/Profile.pdf', u'id': 2, u'tipo': u'NIP', u'slug': u'copa-06'}, {u'criados' : u'16/5/2020 21:25', u'arquivo': u'http://hml.static.detran.al.gov.br/media/infracoes/notificacoes/test.pdf', u'id' : 3, u'tipo: u'NIP', u'slug': u'test-02'}] this objects has different year and i want to display in html something like this: 2022 - Object 1 - Object 2 2020 - Object 3 please help me -
how to serve a media file in Django?
I have a Django project where I'm trying to create a card with an image that was uploaded by the user. I keep getting a certain error but I have already done every solution and its still coming up. any help would be appreciated. the {{image}} variable isn't working html page <div class="p-5 mx-4 bg-white border-2 border-gray-300 grow"> <button><img src="{{image}}" alt=""></button> <h3>{{title}}</h3> <span>{{currentBid}}</span> <span>{{sellor}}</span> </div> settings MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')\ urls urlpatterns = [ path("", views.activeListings, name="activeListings"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("createListing", views.createListing, name="createListing"), path("listingPage/<str:title>", views.listingPage, name="listingPage"), path("wishlist", views.wishlist, name="wishlist"), path("catagory", views.catagory, name="catagory"), path("catagoryListing/<str:catagory>", views.catagoryListingsPage, name='catagoryActiveListingsPage'), path("catagoryListing/listingPage/<str:title>", views.listingPage, name="catagorylistingPage"), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I also have the media url pattern line in the urls for my whole project error 04 4334 Not Found: /Screen_Shot_2022-10-10_at_5.42.19_PM.png WARNING:django.request:Not Found: /Screen_Shot_2022-09-19_at_2.39.14_PM.png Not Found: /images/Screen_Shot_2022-10-21_at_7.37.57_AM.png Not Found: /images/Screen_Shot_2022-09-20_at_3.08.27_PM.png WARNING:django.request:Not Found: /Screen_Shot_2022-10-10_at_5.42.19_PM.png [26/Oct/2022 12:01:48] "GET /images/Screen_Shot_2022-09-19_at_2.38.33_PM.png HTTP/1.1" 404 4355 WARNING:django.request:Not Found: /images/Screen_Shot_2022-10-21_at_7.37.57_AM.png Not Found: /temperature-anomaly_wlbvLbQ.png WARNING:django.request:Not Found: /images/Screen_Shot_2022-09-20_at_3.08.27_PM.png [26/Oct/2022 12:01:48] "GET /Screen_Shot_2022-09-19_at_2.39.14_PM.png HTTP/1.1" 404 4334 WARNING:django.request:Not Found: /temperature-anomaly_wlbvLbQ.png [26/Oct/2022 12:01:48] "GET /Screen_Shot_2022-10-10_at_5.42.19_PM.png HTTP/1.1" 404 4334 [26/Oct/2022 12:01:48] "GET /images/Screen_Shot_2022-10-21_at_7.37.57_AM.png HTTP/1.1" 404 4355 [26/Oct/2022 12:01:48] "GET /images/Screen_Shot_2022-09-20_at_3.08.27_PM.png HTTP/1.1" 404 4355 [26/Oct/2022 12:01:48] "GET /temperature-anomaly_wlbvLbQ.png HTTP/1.1" 404 4307 debug is … -
Slug in Djnago URL
I want to create a directory like mysite.com/user after user get logged In. i.e mysite.com/john Here is the corresponding views and urlpatterns. But after authorization I only left with http://127.0.0.1:8000/authorization instead of http://127.0.0.1:8000/user ? models.py user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) project/urls.py urlpatterns = [ path('authorization/', include('authorization.urls')), ] authorization/app/urls.py urlpatterns = [ path('', views.index, name='index'), path('<slug:user>/', views.user_name, name='user_name'), # here path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), ] corresponding views.py for that user_name @login_required @twitter_login_required def user_name(request, user): user = TwitterUser.objects.get(user=user) return render(request, 'authorization/home.html', {'user':user}) -
How to link to URL of related object in DRF
I’m making a music player with a DRF backend. I have two models, one is Song and the other is TrackQueue In the browser, the “nowplaying” instance of TrackQueue shows the meta of the queued song with a link to the file in its meta. What I need now is a url that always produces that instance of the “nowplaying” TrackQueue (id=1) What would that url be and how can I create it? Thank you models.py class Song(models.Model): title = models.CharField(max_length=24) file = models.FileField() def __str__(self): return self.title class TrackQueue(models.Model): title = models.CharField(max_length=64) is_song = models.OneToOneField(Song, on_delete=models.CASCADE) def __str__(self): return self.title Serializers.py from rest_framework import serializers from .models import Song, TrackQueue class SongSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Song fields = ('id' ,'title', 'file') class TrackQueueSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = TrackQueue fields = ('id' , 'title', 'is_song') views.py from django.shortcuts import render from .serializers import SongSerializer from rest_framework import viewsets from .models import Song, TrackQueue from music.serializers import SongSerializer, TrackQueueSerializer class SongView(viewsets.ModelViewSet): serializer_class = SongSerializer queryset = Song.objects.all() class TrackQueueView(viewsets.ModelViewSet): serializer_class = TrackQueueSerializer queryset = TrackQueue.objects.all() -
Django href link not routing to correct url
The links within my pages/templates/base.html which are used for a header template results in 404 error. The pages load correctly when manually written 'http://127.0.0.1:8000' 'http://127.0.0.1:8000/about/'. I am using class based views and following chapter 3 of Django for beginners (William Vincent). pages/templates/base.html: <header> <a href="{% url 'home' %">Home</a> | <a href="{% url 'about' %">About</a> </header> pages/urls.py: from django.urls import path from .views import HomePageView, AboutPageView urlpatterns = [ path("", HomePageView.as_view(), name="home"), path("about/", AboutPageView.as_view(), name="about"), ] portfolio/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("", include("pages.urls")), ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', ] pages/views.py: from django.views.generic import TemplateView # Create your views here. from django.http import HttpResponse class HomePageView(TemplateView): template_name = 'home.html' class AboutPageView(TemplateView): template_name = "about.html" The error is as follows: Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order: admin/ [name='home'] about/ [name='about'] The current path, about/{% url 'about' %, didn’t match any of these. Terminal error: Not Found: /{% url 'about' % [26/Oct/2022 11:40:02] "GET /%7B%%20url%20'about'%20% HTTP/1.1" 404 2497 I think the issue lies in pages/urls.py, as if click the 'home' link from 'http://127.0.0.1:8000/about/' the url is 'http://127.0.0.1:8000/about/%7B%%20url%20'home'%20%'. I've tried … -
Nth-child does not change colour for odd and even
This a Django project, in which I loop over folders and files. The background colour of each file should be different. For example, the odd ones should be purple and the even ones should be blue. But they are all shown as purple. Here is the file div from HTML: <div class="each_key">{{file}}</div> Here is the styling in CSS: .each_key:nth-child(odd){ text-align: left; width:197px; height:42px; background-color: purple; padding:10px; } .each_key:nth-child(even){ text-align: left; width:197px; height:42px; background-color: blue; padding:10px; } I've also tried "nth-of-type" and it still gives me purple instead of changing to purple and then blue. -
Django models - Custom jsonfield update method
So my intention is to be more effective when it comes to touching the database jsonfields in my postgres db. I could of course append the jsonfield data like so (both are lists with inner dicts): obj.jsonfield = new_data + old_data obj.update_fields(["jsonfield"]) but I wonder if there is a better way for doing so, because when I got this right, the database first removes old_data and afterward updates the field once again with the old_data. Is there a better way for me to just append to the old_data list in a custom update_fields method? If what do I need to consider there? Thanks a lot -
Need help for Creating Biometric Attendance web application using Django rest api
i'm very new to this it side coming from non-it, recently got placed as python developer through self learning. joined after my company asks me to develop the biometric attendance system for the internal purpose. can anyone guide me how to develop it, what are the model fields required, how should i integrate the device with my rest api application. somebody please help and guide me. i dont know where to start -
Hello everyone, please how do I call the constant messages that comes with a Validation Error into my program?
views.py I want each validation messages to be displayed in the home page according to the type of error message. for example: if the password input is too short, it should only display the password input when it redirects the user back to the home page. Thank you in advance! from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout #from django.contrib.auth.models import User from django.core.mail import send_mail from .models import User from django.contrib.auth.password_validation import validate_password,UserAttributeSimilarityValidator,CommonPasswordValidator,MinimumLengthValidator,NumericPasswordValidator from django.contrib.messages import constants as messages_constants MESSAGE_LEVEL = messages_constants.DEBUG # Create your views here. def signup(request): if request.method == "POST": username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") password2 = request.POST.get("password2") if password: try: new = validate_password(password,user=None,password_validators=None) except: messages.error(request, ) return redirect('home') -
psycopg2.OperationalError: SSL connection has been closed unexpectedly
My application is using Django==3.0.6 with psycopg2==2.8.6. I am using Django ORM not SQl-Alchemy. I get this error every 4-5 days randomly. Unable to reproduce this error on local. Any suggestions what can be the reason for this? If I restart my application container, application starts working normally without any errors till I get same error in next 4-5 days. Traceback (most recent call last): ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute ma-datamanagement_1 | return self.cursor.execute(sql, params) ma-datamanagement_1 | psycopg2.OperationalError: SSL connection has been closed unexpectedly ma-datamanagement_1 | ma-datamanagement_1 | ma-datamanagement_1 | The above exception was the direct cause of the following exception: ma-datamanagement_1 | ma-datamanagement_1 | Traceback (most recent call last): ma-datamanagement_1 | File "/insightsmax_datamanagement_app/datastaging/data_upload.py", line 97, in get_s3_bucket_name ma-datamanagement_1 | project_obj = models.Project.objects.get(display_project_id=project_id) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method ma-datamanagement_1 | return getattr(self.get_queryset(), name)(*args, **kwargs) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 411, in get ma-datamanagement_1 | num = len(clone) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 258, in len ma-datamanagement_1 | self._fetch_all() ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all ma-datamanagement_1 | self._result_cache = list(self._iterable_class(self)) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 57, in iter ma-datamanagement_1 | results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1151, in execute_sql ma-datamanagement_1 … -
Rpy2 Error in Django - Conversion 'py2rpy' not defined for objects of type '<class 'str'>
I have never used R before, and am trying to call an R function from python using rpy2. It works on a standalone python terminal, but not in Django. But rpy2 does not seem to be able to convert python strings to r objects. I am using a custom library given by a coworker and would like to know if the problem is on his side. Because I have seen other people on SO using the exact same method to run R functions from python. Here's the code from config import celery_app from rpy2.robjects.packages import importr from pathlib import Path import math base = importr("base") my_lib = importr("my_lib") @celery_app.task() def calculate_r_bindings(file_path): """ """ g = my_lib.fit_bindingCurves(input = file_path,tass = 200,tdiss = 530,conc_M = 1.2*math.exp(-7),generate_output = False) return g I am using rpy2 version 3.5.5 Here's the error: File "/Users/user.ali/Projects/ProjectDev/project_env/lib/python3.9/site-packages/rpy2/robjects/conversion.py", line 240, in _py2rpy raise NotImplementedError( NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'str'>' -
Django - why my widget is cleared out during save?
I'm struggling with a django custom widget used to present HTML data. I've started with a template from standard django's textarea: class Descriptionarea(forms.Widget): template_name = "widgets/descriptionarea.html" def __init__(self, attrs=None): super().__init__(attrs widgets/descriptionarea.html: <textarea name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> {% if widget.value %}{{ widget.value }}{% endif %}</textarea> Which works fine as an element of my inline form: class InlineForm(forms.ModelForm): description = forms.CharField(widget=Descriptionarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) which is part of my TabularInline (django-nested-admin in use): class TabularInline(NestedStackedInline): form = InlineForm fields = ("title", "description") readonly_fields = ("title", ) model = MyModel max_num = 0 I'd like to present the description as HTML document, so I've changed the template: <details> <summary>description</summary> <pre name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> {% if widget.value %}{{ widget.value | safe }}{% endif %} </pre> </details> Unfortunately, it does not work, as now I cannot use save on admin pages, as Django complains about: This field is required. Indeed during save, the whole widget is cleared out. Second question - when I add the description field to the list of readonly_fields, then it becomes a simple label. Is it possible to provide my own readonly widget?