Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
do not display already selected items as choices in the dropdown in django admin inline but preserve already selected
I am using Tabularinline class inside the django admin for many to many relation. I want to filter the queryset so already selected can't be chosen. I tried to override formfield_for_foreignkey method and it partially does the job. Choices are in the desired they (What is already selected are not present in the choices) but the default state is empty for the fields which already exist and when I try to submit a form it throughs an error indicating that the field is required (which should be this way) I don't know how to achieve this goal without overriding the admin template This is how the admin panel looks like -
Django Rest API Cache with Radis & seeking sugestion
Problem I have a backend with Django (Wagtail CMS) and a frontend with react. I am using them as a news site. I am new in Django and my other teammate manages the front end. I am providing them with wagtail's default API with some customization(I have exposed all needed fields in BaseAPIView). In my API there were 25 blog posts for the first time and now there are 60 posts. The first time the API loading time was 1.02 sec and now the API load time is 1.69sec. I am afraid of what will happen when the posts hit 5000+! Because I am not limiting anything in the API. Plan I am planning to use radis cache for the API. But I can't understand what should I set in the API views! because my API views is this. #api.py from wagtail.api.v2.views import PagesAPIViewSet,BaseAPIViewSet api_router = WagtailAPIRouter('wagtailapi') class ProdPagesAPIViewSet(BaseAPIViewSet): renderer_classes = [JSONRenderer] filter_backends = [FieldsFilter, ChildOfFilter, AncestorOfFilter, DescendantOfFilter, OrderingFilter, TranslationOfFilter, LocaleFilter, SearchFilter,] meta_fields = ["type","seo_title","search_description","first_published_at"] body_fields = ["id","type","seo_title","search_description","first_published_at","title"] listing_default_fields = ["type","seo_title","search_description","first_published_at","id","title","alternative_title","news_slug","blog_image","video_thumbnail","categories","blog_authors","excerpt","content","content2","tags","story_type"] nested_default_fields = [] def get_queryset(self): return super().get_queryset().filter(story_type='Story').order_by('-first_published_at') name = "stories" model = AddStory api_router.register_endpoint("stories", ProdPagesAPIViewSet) Will adding radis cache in API solve the loading problem or should I add … -
Django - command createsuperuser creates superuser in the default database when passing the --database parameter
I have three Postgre databases in my project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'default', 'USER': 'user', 'PASSWORD': 'password', }, 'clients_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'clients_db', 'USER': 'user', 'PASSWORD': 'password', }, 'other': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'other', 'USER': 'user', 'PASSWORD': 'password', }, } And three apps: clients, users and myapp. The app clients have a router for the clients_db database: class ClientsRouter: route_app_labels = {'clients'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'clients_db' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'clients_db' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'clients_db' return None The other two apps uses the same database. I can run migrations and migrate just fine using the commands: python manage.py makemigrations Then, to apply migrations to the default database: python manage.py migrate And to apply migrations to the other database: python manage.py migrate --database other But when I try to run the command to create a superuser in the other database, it creates a superuser in the default database instead. The command: python … -
How can I allow the user to edit comments in a Django Blog using DetailView and UpdateView on the same page?
I've been at this for a couple days and have followed a few different tutorials to get what I want. I'm pretty close....I just can't figure out how to get the user to be able to edit their comment. I've tried several different approaches...Here's what I have so far... My Models... class Suggestion(models.Model): id = models.UUIDField(default=uuid.uuid4,primary_key=True,unique=True) created_by = models.ForeignKey(User,null=True,on_delete=models.DO_NOTHING,related_name='suggestion_created_by') last_update = models.DateTimeField(editable=False,null=True) suggestion_creation_date = models.DateTimeField(editable=False,null=True) suggestion_name = models.CharField(max_length=255,null=True) suggestion_status = HTMLField(blank=True,null=True) suggestion = HTMLField(blank=True,null=True) unique_identifier = models.CharField(max_length=64,null=True,blank=True) class Meta: ordering = ["suggestion_name"] def __str__(self): return self.suggestion_name def get_absolute_url(self): return reverse("Suggestions:suggestion_detail",kwargs={'pk':self.pk}) class SuggestionComment(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) comment = models.CharField(max_length=255,blank=True) created_on = models.DateTimeField(default=timezone.now) suggestion = models.ForeignKey('Suggestion',on_delete=models.CASCADE,related_name='suggestion_comments') upvotes = models.ManyToManyField(User,blank=True,related_name='suggestion_comment_upvotes') def get_absolute_url(self): return reverse("Suggestions:suggestion-detail", kwargs={"pk": self.suggestion.pk}) My Templates... DetailView.. <!DOCTYPE html> {% extends "base21.html" %} <title>{% block title %} LevelSet Suggestion By Name Detail {% endblock %}</title> {% block body_block %} <div class="box12"> <h1 class="title">{{ suggestion_detail.suggestion_name }}</h1> <div class="spacer281"> {{ suggestion_detail.suggestion|safe }} </div> {% if suggestion_detail.suggestion_status != None %} <div class="spacer280"> <h2>Status - </h2> </div> <div class="spacer76"> {{ suggestion_detail.suggestion_status|safe }} </div> {% endif %} <div class="spacer285"> {% include 'suggestion_comments.html' %} </div> </div> </div> {% endblock %} suggestion_comments.html ( Include ) <form method='POST' class="comment-form"> {% csrf_token %} <div class="spacer284"> {{ form.comment }} </div> <button … -
Programmatic login succeeds, but not recognized
I have a magnet link feature where my web app sends a login URL with a username & one-time token encrypted. When clicking the link on the email, the user is sent to an authentication where I programmatically log in and then redirect to the member page. Authentication and login are successful, but when I redirect to the main page, Django sends the user back to the login page. However, when I click the logo, the main page shows. authentication & login code def magnet_link_login(request, *args, **kwargs): if request.user and request.user.id != None: return redirect('stream:home') magnet_token = request.GET['key'] if 'key' in request.GET else '' decrypted_token = decrypt_text(magnet_token) split_texts = decrypted_token.split('&') if len(split_texts)<2: #invalid and redirect to an invalid magnet link page pass uname = split_texts[0].split('=')[1] auth_token = split_texts[1].split('=')[1] #fetch the user record acc = Account.objects.get(slug=uname) if not acc: #error and redirect to an invalid account name page pass #validate and login try: logged_user = authenticate(username=acc.username,password=auth_token) if logged_user is not None: login(request, logged_user) return redirect('stream:home') else: return redirect('invalid-link') except Exception as e: print(e) return redirect('invalid-link') My member page (stream:home) is a CBV. class Home(LoginRequiredMixin, ListView): paginate_by = 6 context_object_name = 'content_list' ***SOME STUFF HERE*** def get_queryset(self): *** SOME STUFF HERE*** def … -
Django: annotate a model with multiple counts is super slow
I'm trying to annotate a model that has multiple relationships, with multiple counts of those relationships. But the query is super slow. Campaign.objects.annotate( num_characters=Count("character", distinct=True), num_factions=Count("faction", distinct=True), num_locations=Count("location", distinct=True), num_quests=Count("quest", distinct=True), num_loot=Count("loot", distinct=True), num_entries=Count("entry", distinct=True), ) When I mean super slow, I mean it: it takes multiple minutes on my local MacBook Pro with the M1 Max 😰 And there aren't even that many row in these tables. If I simply fetch all campaigns, loop over them, and then get the counts of all these related objects in separate queries, it's a LOT faster (at the cost of doing number of campaigns * 6 queries). But that is so much more code to write, can't this query be optimized somehow? -
Django: How to get list of choices of choice field
I have Choices: all_choices= Choices( ('val1', _("val1 text")), ('val1', _("val2 text")), ('val3', _("val3 text")), ('val4', _("val4 text")), ) I am looking for function that returns list of all choices like: list=['val1', 'val2', 'val3', 'val4'] I could not manage to do it so far Is there any proper wat to get list of choices? -
self.request.user not returning in queryset
In my views, queryset is returning all the users when I want it to be only returning the user that is currently logged. I have a get self method which has the serializer set to the user but it is not being used. When I tried get_queryset, self.request.user still doesn't return the user. views.py: from rest_framework import viewsets from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework import status from rsm_app.api.v1 import serializer as serializers from rsm_app.users.models import User class CurrentUserView(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = serializers.UserSerializer #queryset = User.objects.filter(name=request.user.name) def get_queryset(self): return self.request.user def put(self, request): serializer = serializers.UserSerializer( request.user, data=request.data) if request.data and serializer.is_valid(): serializer.save() return Response(serializer.data) return Response({}, status=status.HTTP_400_BAD_REQUEST) Url.py: from rest_framework import routers from django.urls import path, re_path, include from graphene_django.views import GraphQLView from rsm_app.api.v1 import views app_name = "api.v1" # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r"user", views.CurrentUserView, basename="user") # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path("graphql", GraphQLView.as_view(graphiql=True)), re_path(r"^", include(router.urls)), re_path(r"user/", views.CurrentUserView, name='user'), re_path(r"^api-auth/", include("rest_framework.urls", namespace="rest_framework")), ] -
Get slug name list by url path name
I am reverse-engineering django urlpatterns. For my purpose, I need to dynamically know the list of slug names developers chose to use within url. Example: path("<slug:membership_slug>/<slug:parent_slug>/data/", rzd.ReportingUnitDataView.as_view(), name="hierarchy.item.data"), So, in the world, where everyone writes perfect code, my function should take "hierarcy.item.data" and spit out ["membership_slug", "parent_slug"] I looked at the reverse function, hoping it would return something useful without kwargs, but it does not. Have been googling like Neo, but to no avail. But the hope does not leave my heart... somewhere django should hold all that urlpatterns stuff! I still believe. Perhaps you can at suggest how to get a hold of list of urls, even if in the raw format, that would already be a help. Thank you. -
how to fix result display in project
How to adjust the project to improve the performance result: in myworld/members/view.py: def testing(request): template = loader.get_template('template.html') context = { 'heading': 'Hello &lt;i&gt;my&lt;/i&gt; World!', } print(context) return HttpResponse(template.render(context, request)) in myworld/members/templates/template.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>Learning_21_1_1</title> </head> <body> {% autoescape off %} <h1>{{ heading }}</h1> {% endautoescape %} <p>Check out views.py to see what the heading variable looks like.</p> </body> </html> result : enter image description here main result : enter image description here enter image description here please help me -
Django summernote don't form is not displayed outside the admin panel
I'm trying to add WYSIWYG editor django-summernote to my django project. I found the problem that the editor is not showing up when I try to add it to the page. On the form page, I don't have the summernote editor displayed. There is an error in the console with jQuery. Error: jquery-3.6.0.min.js:2 jQuery.Deferred exception: Cannot read properties of null (reading 'value') TypeError: Cannot read properties of null (reading 'value') at HTMLDocument.<anonymous> (http://127.0.0.1:8000/summernote/editor/id_description/:43:25) at e (http://code.jquery.com/jquery-3.6.0.min.js:2:30038) at t (http://code.jquery.com/jquery-3.6.0.min.js:2:30340) undefined S.Deferred.exceptionHook @ jquery-3.6.0.min.js:2 t @ jquery-3.6.0.min.js:2 Объект setTimeout (асинхронный) (анонимная) @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 fire @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 ready @ jquery-3.6.0.min.js:2 B @ jquery-3.6.0.min.js:2 jquery-3.6.0.min.js:2 Uncaught TypeError: Cannot read properties of null (reading 'value') at HTMLDocument.<anonymous> ((индекс):43:25) at e (jquery-3.6.0.min.js:2:30038) at t (jquery-3.6.0.min.js:2:30340) Screen enter image description here Code: # Settings.py INSTALLED_APPS = [ ... 'django_summernote', # WYSIWYG EDITOR 'editorapp', # my app ... ] MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' # Urls urlpatterns = [ ... path('editorapp/', include('editorapp.urls')), path('summernote/', include('django_summernote.urls')), ... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # models.py class NodesForm(forms.ModelForm): description = SummernoteTextField() class Meta: model = Nodes fields = ('node_description',) # urls.py path('', views.main, name='nodedoc_main'), … -
JS function not fired in Django dropdown onchange event
I've question, I've JS function which is used in Django project(downloaded from internet) , so in template.html I've <select class="select_filter" onchange="myFunc(this.value);"></select>, also this function is declareted in this template.html <script> function myFunc(val) { console.log(val); } </script> but in DevConsole in browser I got Uncaught ReferenceError: myFuncis not defined P.S Jquery was enabled in page-source (checked from Ctrl+U) Can anyone please guide and help with my problem? -
update only targeted element with ajax
I'm trying to update my cart page with ajax when someone increases or decreases the quantity of the products, my view logic is fine. My issue as I can infer is targeting the class "ajax_updater", as soon as I hit the quantity buttons ajax works, but instead on just the specific product, it targets all the products' quantity with the same class ".quantity-style" and changes the value as per the targeted product, so, if the quantity for product A is 4 after ClickEvent, the quantity for product B, D, F gets targeted and changed to 4 too, what could be a solution? {% for item in items %} <div class="quantity"> <p id="quantity-style" class="quantity-style">{{item.quantity}}</p> <div class="quantity-arrows"> <img data-product="{{item.product.id}}" class="ajax_updater" data-action="add" src="{% static 'shop/images/arrow-up.png' %}"> <img data-product="{{item.product.id}}" class="ajax_updater" data-action="remove" src="{% static 'shop/images/arrow-down.png' %}"> </div> </div> {% endfor %} function update_arrow() { $.ajaxSetup ({ cache: false }); var spinner = '<i class="fas fa-circle-notch fa-spin" style="font-size:15px;" alt="loading" ></i>'; $(".quantity-style").html(spinner).load(update_quantity_url); console.log(update_arrow_url); } $('.ajax_updater').click(function () { update_arrow(); console.log('hit hit'); }); -
What is the difference between SimpleTestCase.settings() and django.test.override_settings?
Django provides different ways to change settings(documentations) in a test in different levels (TestCase class, test method, context manager). I understand the difference between override_settings and modify_settings, but I can't get the difference between SimpleTestCase.settings() and django.test.override_settings() when being used as a context manager. Is there any difference in functionality or preference in which one to use? -
(Django / Nginx / Gunicorn) HTTPS fails to serve pathed directories on my site
Pretty new to Nginx and web deployment in general. I have a site I am aiming to deploy using a DigitalOcean droplet. Right now it is working, but only with http://[SERVER-IP] (here) Although the site does load with HTTPS (here), no domain.com/[ X ] sites work. The aim is to make get all URLs within https://rejesto.com functioning normally and leading to their respective sites. For context, all links on the page are provided by Djagno's {% url '[url]' %} tag system; they work as intended locally, and using http://[SERVER-IP]/[ X ]. I'm assuming that the issue is within the Nginx config files because: http://46.101.92.95/blog leads to the correct page. (for better or for worse) https://rejesto.com/blog does not work. Here is (what I believe to be) the relevant config file: /etc/nginx/sites-available/rejesto.com: server { server_name rejesto.com www.rejesto.com; location / { try_files $uri $uri/ =404; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/rejesto/myprojectdir; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/rejesto.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/rejesto.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by … -
UpdateAPIView | Django REST does not update data properly
I want to register values in a table of relations when updating data. Conversely, I want to generate an error if the value does not exist. models.py class CustomUser(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) email = models.EmailField(_('email address'), unique=True) role = models.OneToOneField('Role', related_name='user', blank=True, null=True, on_delete=models.PROTECT) # ommited... class Role(models.Model): slug = models.SlugField(unique=True) def __str__(self): return self.slug serializers.py from drf_writable_nested import WritableNestedModelSerializer from rest_framework import serializers from accounts.models import CustomUser, Role class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ('slug',) class UserSerializer(WritableNestedModelSerializer): role = RoleSerializer() class Meta: model = CustomUser fields = ('uuid', 'email', 'role', 'password') extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): return CustomUser.objects.create_user(**validated_data) views.py class UserUpdateView(generics.UpdateAPIView): queryset = CustomUser.objects.all() serializer_class = UserSerializer Role DB Table id:1 | slug:admin Expectation Request(PATCH) Parameter { "role":{ "slug":"foo" } } # error: foo does not exist in the Role table { "role":{ "slug":"admin" } } # OK!!! What should I do? Thank you very much. -
How to obtain a specific data from model in profile when person is logged in, Django?
I want to post a specific data in profile from user that is logged in. I have a model like this: class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=60) email = models.EmailField(max_length=100) class Wallet(models.Model): name = models.OneToOneField(User, null=True, on_delete=models.CASCADE) usd = models.FloatField(null=True) If for example 'user2' is logged in, and in database he has 10usd, I want in his profile to be shown 10usd. But I don't know how to request a specific data of user that is logged in Views.py @login_required(login_url='main') def profile_user(request): usd = wallet.objects.get (get his usd from db) return render(request, 'profile.html', {'usd':usd}) Thank you very much. -
Issue deploying Django webapp in OVH Hosting
I'm trying to deploy a Django App in OVH Hosting and, after some hard exploration and try-error, I keep getting an issue. File "/usr/share/passenger/helper-scripts/wsgi-loader.py", line 381, in <module> handler = RequestHandler(server_socket, sys.stdin, app_module.application) AttributeError: module 'passenger_wsgi' has no attribute 'application' OVH/Passenger proccess feedback Apart from all the files created at startapp by Django and all the code I wrote I added the following file 'passenger_wsgi.py' on the root of the app directory. I used two differents versions: First: import MyApp.wsgi application = MyApp.wsgi.application Second: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() In the runtime configuration of OVH hosting the application launch script set is 'manage.py'. SECRET_KEY and DJANGO_SETTINGS_MODULE are declared in the environment variables. -
How can I find 3 top or max value in django model?
I have a class in django model and how can I find 3 maximum value in it? Do I need for into for loop? or Do I need any class? class Prices (models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) Price = models.IntegerField() page = models.ManyToManyField(Listing_page,blank=True,related_name='Price') def __str__(self) -> str: return f"{self.id} : {self.Price}" I have follow code for top price but I need 3 top price too. big_price = None for num in post.Price.all(): if (big_price is None or num.Price > big_price.Price): big_price = num -
Using the URLconf defined in name, Django tried these URL patterns, in this order
I have a django project and in this project I have two apps: main and profiles. So I added both mini apps to the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'profiles', ] and I can run the main application - if I go to: http://127.0.0.1:8000/ It is running. But If I go to: http://127.0.0.1:8000/profiles Then I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/profiles Using the URLconf defined in schoolfruitnvwa.urls, Django tried these URL patterns, in this order: admin/ [name='index'] The current path, profiles, didn’t match any of these. So my question is: how to tackle this? Thank you -
How to mark words that match words from a list in a django form's textarea using javascript?
I have the following form: class TestForm(Form): testfield = CharField(widget=Textarea(attrs={'rows': 10, 'id': 'test'}), label='Input test text here') Rendered to my template along with the following list as context: dummy_list = ['hi', 'hello'] I'm trying to make a button which I can click in my template which makes words in the form bold if they are contained within the list. JS: <script type="text/javascript"> function Mark_words(id) { var form_content = document.getElementById(id); var dummylist = {{ dummy_list }} var new_form_content = "" for(var x in form_content.value) { if ( dummylist.indexOf(x) > -1 ){ x = x.bold(); new_form_content += x + " "; } else { new_form_content += x + " "; } } form_content.innerText = new_form_content; } </script> And the following button: <button type = "submit" class ="btn btn-info" value = "Click" onclick="Mark_words('test')">Mark words</button> Unfortunately, nothing happens when I click the button. What am I doing wrong? -
Django: relations between two objects of the same model
I have created this model: class Process(models.Model): name = models.CharField('Process name', max_length=50, unique=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, max_length=50, null=True, verbose_name='Process owner') I want to create multiple processes and from those build a hierarchy. Here is a hierarchy model: class Hierarchy(models.Model): name = models.ForeignKey('process.Process', on_delete=models.CASCADE, verbose_name='Sub process name') name = models.ForeignKey('process.Process', on_delete=models.CASCADE, verbose_name='Main process name') order = models.IntegerField('Process order', default='1') Obviously this doesn't work as the 'name' fields in hierarchy model interfere with each other. I wouldn't want to create models MainProcess and SubProcess as some SubProcesses might have more SubProcesses etc. What would be the right way to build this type of model/hierarchy? This might be very basic issue, but I couldn't find any related issues to apply a solution from, so any help would be appreciated. -
XXX is not defined - Importing Class from OpenLayers Node Module in Django
Having difficulty getting the Node OpenLayers to work within Django. npm and ol are installed and the files are in a node_modules folder in my project. I included the node_modules folder in my STATICFILES_DIRS in settings.py. I'm including the OpenLayers modules within my template, map.html: <script type="module" src="{% static 'ol/dist/ol.js' %}"></script> <script type="module" src="{% static 'ol/Map.js' %}"></script> <script type="module" src="{% static 'ol/View.js' %}"></script> <script type="module" src="{% static 'ol/layer/Tile.js' %}"></script> <script type="module" src="{% static 'ol/source/OSM.js' %}"></script> <script type="text/javascript"> import "{% static 'ol/layer/Tile.js' %}"; const map = new ol.Map({ target: 'my-map', layers: [ new ol.Layer.Tile({ source: ol.Source.OSM() }) ], view: new ol.View({ center: [40, -70], zoom: 2 }) }); </script> Which appears to be working as I can see the files load within my browser's dev tools. But when I try to use the classes within the modules I get the error: Uncaught ReferenceError: ol is not defined OTHER METHODS I'VE TRIED: I've also tried calling the class names directly: <script type="text/javascript"> const map = new Map({ target: 'my-map', layers: [ new Tile({ source: OSM() }) ], view: new View({ center: [40, -70], zoom: 2 }) }); </script> But get the same error: Uncaught ReferenceError: Tile is not defined The OpenLayers docs … -
Wagtail dumpdata modellogentry null values
Having a problem with dumpdata command in Wagtail v.3.0.3. Some of the entries for the table pagelogentry have data set to null and not the expected {}. It is not all the values. When I do dumpdata I have to edit the dump file by hand to allow it to work with loaddata. e.g. { "model": "wagtailcore.pagelogentry", "pk": 2, "fields": { "content_type": [ "home", "gallerypage" ], "label": "Excellence in Engineering", "action": "wagtail.publish", "data": null, "timestamp": "2020-08-18T16:25:08.456Z", "uuid": null, "user": [ "egomez" ], "content_changed": true, "deleted": false, "page": 2702, "revision": 7602 } } We have had this site for a few years and it has been updated through various Wagtail versions. I'm not sure what the right course to fix the data is here. -
django How do I get a value from a model recursive reference?
I am trying to implement the comment function of comments through self reference. error: models.ReComment.DoesNotExist: ReComment matching query does not exist. Parent_comment of ReComment model was ForeignKey as self I printed self.kwarg and got a value of {'pk': 3, 'comment_id': 8} models.py class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() feeling = models.CharField(max_length=50, validators=[validate_no_numbers, validate_no_special_characters]) score = models.IntegerField(validators=[validate_score, validate_no_special_characters]) dt_created = models.DateTimeField(auto_now_add=True) dt_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") likes = GenericRelation("Like", related_query_name="post") def __str__(self): return self.title class Comment(models.Model): content = models.TextField(max_length=500, blank=False) dt_created = models.DateTimeField(auto_now_add=True) dt_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") likes = GenericRelation("Like", related_query_name="comment") def __str__(self): return self.content[:30] class ReComment(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name="recomments") content = models.TextField(max_length=500, blank=False) dt_created = models.DateTimeField(auto_now_add=True) dt_update = models.DateTimeField(auto_now=True) parent_comment = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE, related_name="parent_comments") def __str__(self): return self.content[:30] form.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = [ "content", ] widget = { 'content': forms.Textarea, } class ReCommentForm(forms.ModelForm): class Meta: model = ReComment fields = [ "content", ] views.py class CommentCreateView(LoginAndVerificationRequiredMixin, CreateView): http_method_names = ["post"] model = Comment form_class = CommentForm def form_valid(self, form): form.instance.author = self.request.user form.instance.post = Post.objects.get(id=self.kwargs.get("pk")) return super().form_valid(form) def get_success_url(self): return reverse("post-detail", kwargs={"pk":self.kwargs.get("pk")}) class ReCommentCreateView(LoginAndVerificationRequiredMixin, CreateView): http_method_names …