Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No Change detect in table format
I face a problem in migrations when I run makemigrations command no change detect in my table and one more thing I get this error on just one table, all other tables create and change successfully. One more thing app name added in INSTALLED_APPS and I use xampp as a server. Thanks -
Generating continuous default names for new objects in Django
I want to create a model with a default name field. e.g If its the first object, the default name will be: new, then new1, new2 ... How do I accomplish this in Django models? -
Django Rest Framework cannot override viewset list() method
I have a model: class Investment(models.Model): status = models.CharField() @property def email_main(self): return self.account.email and a serializer: class InvestmentSerializer(serializers.ModelSerializer): email_main = serializers.ReadOnlyField() class Meta: model = Investment fields = '__all__' and finally a view: class InvestmentView(LoggingMixin, viewsets.ModelViewSet): queryset = Investment.objects.all() serializer_class = InvestmentSerializer permission_classes = [AllowAny] filter_backends = [DjangoFilterBackend] filterset_fields = ['email_main'] def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) print('request.query_params ', request.query_params) if request.query_params.email_main: queryset = Investments.objects.get(account__email='something') serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) I'm trying to override the list method to check if the parameter has email_main so I can filter the results with the email property. But I can't even see the print function inside the method. What might I be missing? -
Django-filters - How to add autocomplete feature
I have made filters using django-filters. As a result I get a dropdown menu. Is it possible to add an autocomplete/search field to this dropdown? I have already tried to add the Select2Widget widget as indicated in another post, but the only thing that changes is that it adds an empty field before the dotted line. But it won't let me write anything. Maybe something is missing in the template??? Stackoverflow don't let me add images yet so I share the code I have. filters.py import django_filters from django_select2.forms import Select2Widget from .models import Consumo, Cliente AÑO_CHOICES = (('2021', '2021'), ('2022', '2022'),) class ConsumoFilter(django_filters.FilterSet): año = django_filters.ChoiceFilter(choices=AÑO_CHOICES, label='Año', widget=Select2Widget(attrs={'style':'width: 20ch', 'class':'form-select form-select-sm'})) name = django_filters.ModelChoiceFilter(queryset=Cliente.objects.all(), label='Clientes', widget=Select2Widget(attrs={'style':'width: 85ch','class': 'form-select form-select-sm'})) class Meta: model = Consumo fields = ['name', 'año'] template {% extends 'clientes/base.html' %} {% load static %} {% block title %}Title{% endblock %} {% block head %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> {% endblock %} {% block content %} <div class="card" style="margin-top: 20px; margin-bottom: 20px;"> <div class="card-body"> <h4 class="card-title">Consumos</h4> <h6 class="card-subtitle mb-2 text-muted">Consumos por cliente</h6> <hr> <div class="container"> <div class="row"> <div class="col-lg-12"> <form method="get"> {{ consumo_filter.form }} <br> <button type="submit" … -
serialize a Post Table which has a Like table connected to it by Fk
hi,since I am just noobie in DRF I need your help in serializing the Post table. I have a Post model like this : class Post(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) title = models.CharField(max_length=255) descripotion = models.TextField(blank=True) link = models.CharField(max_length=255, blank=True) def __str__(self): return self.title And then there is a like Model which is related to Post model by FK class Like(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) post= models.ForeignKey( 'Post', on_delete=models.CASCADE ) def __str__(self): return self.id and this is my serializers.py for Post table class PostSerializers(serializers.ModelSerializer): user = UserSerializer( required = False ) class Meta: model = Post fields = [ 'id', 'title', 'link','user','descripotion'] read_only_fields = ['id'] this returns the following response { "id": 5, "title": "string", "link": "string", "user": { "email": "admin@mail.com", "name": "sia" }, "descripotion": "string" } But I want a response to have the Like counts in it { "id": 5, "title": "string", "link": "string", "user": { "email": "admin@mail.com", "name": "sia" }, "descripotion": "string", "like_count: 50 " } -
Django Rest Framework filtering against serializer method fields
In my serializers, I have added the custom field "step_type" that grabs a value from another model. class AccountSerializer(serializers.ModelSerializer): step_type= serializers.SerializerMethodField() class Meta: model = Account fields = '__all__' def get_step_type(self, obj): step = Step.objects.get(step_name=obj.step_name) return step.step_type I want to use query parameters to filter my REST API class AccountViewSet(viewsets.ModelViewSet): def get_queryset(self): queryset = Account.objects.all().order_by('-date') query_step_type = self.request.query_params.get("type") if query_step_type is not None: queryset = queryset.filter(step_type=query_step_type) return queryset However, this won't work because step_type isn't part of the original model fields. How can I filter the queryset using the step type serializer method field? -
How to extract data from json response made by an api in python, Django
I am creating a charge and I want from it to take its 'hosted_url' in order to redirect a user from page. I am trying to extract it from json, but I newbie and don't know how ... url = "https://api.commerce.coinbase.com/charges" payload = { "local_price": { "amount": 1, "currency": USDT }, "name": "Test for fun", "description": "Project 2", "pricing_type": "fixed_price" } headers = { "accept": "application/json", "X-CC-Version": "2018-03-22", "X-CC-Api-Key" : "**********", "content-type": "application/json" } response = requests.post(url, json=payload, headers=headers) print(response.text) This is a code to make a request to an api in order to create a charge and in JSON Response I get field: "hosted_url": "https://commerce.coinbase.com/charges/123DVAS", I want somehow to put this message '123DVAS' in variable or to make a redirect like this: return render(request, 'https://commerce.coinbase.com/charges/123DVAS') -
Django Serializer with Websockets not working due to request and HyperLinkedModelSerializer
I am trying to use a websockets to send a queryset to my frontend using a model serializer. When I test this out I receive the following message: "HyperlinkedIdentityField" requires the request in the serializer context. Add context={'request': request} when instantiating the serializer. This is my frontend test code: function websocket_test(){ ws.send(JSON.stringify({ action: "list", request_id: new Date().getTime() })) } This is my serializer: class InstructorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=Instructor fields='__all__' This is my consumer: class Instructors_Consumer( ListModelMixin, RetrieveModelMixin, PatchModelMixin, UpdateModelMixin, CreateModelMixin, DeleteModelMixin, GenericAsyncAPIConsumer): queryset=Instructor.objects.all() serializer_class=InstructorSerializer I don't quite understand what is going wrong. The error raised mentions adding a context keyword when I instantiate the serializer; however I have no clue on why it would need the request or where to instantiate. Any help would be greatly appreciated as I'm completely lost on how to fix this issue. Thank you. -
social-auth-app-django facebook authentication url blocked
My settings.py has the following : LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'login' SOCIAL_AUTH_URL_NAMESPACE = 'social' AUTHENTICATION_BACKENDS = [ 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.instagram.InstagramOAuth2', 'social_core.backends.linkedin.LinkedinOAuth2', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.google.GoogleOAuth', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_PIPELINE = [ 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.social_auth.auth_allowed', ] SOCIAL_AUTH_FACEBOOK_KEY = "..." SOCIAL_AUTH_FACEBOOK_SECRET = "..." INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'rest_framework', 'rest_framework.authtoken', "core", 'social_django', 'sslserver', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) myapp.urls.py: urlpatterns = [ path("admin/", admin.site.urls), path('', include('core.urls')), path('social-auth/', include('social_django.urls', namespace="social")), ] core.urls.py urlpatterns = [ path("", views.title, name="title"), path("home", views.home, name="home"), path("login", views.login, name="login"), path('logout', views.logout, name='logout'), ] core.views.py def title(request): return render(request, 'title.html') def login(request): return render(request, 'login.html') @login_required def home(request): return render(request, 'home.html') @login_required def logout(request): try: del request.session['uid'] except: pass auth.logout(request) return redirect('login') templates.registration.login.html <button class="btn btn-primary mb-2"> <a href="{% url 'social:begin' 'facebook' %}">Login with Facebook</a> </button> I've added localhost in I've added the full localhost website I've added the redicection url But still I get the blocked url error when clicking on the button "login with facebook" I've looked everywhere on the internet and could not find the issue. Any idea please? -
Django - effective method to check if one user follows another user (many-to-many relations)
Basically I'm implementing pretty straightforward feature - in which one user might go to another user profile page and follow/unfollow him. In order to steer the user interface logic I'd like to know if one user already follows another user (or not). I implemented a method in django that works, but I think it's rather nasty. Any suggestions how this query could be simplified with Django ORM queries? Thank you for your suggestions! class User(AbstractUser): follows = models.ManyToManyField("self", blank = True, null = True, symmetrical=False, related_name="followers") pass def serialize(self): return{ "followsCount" : self.follows.all().count(), "followersCount": self.followers.all().count() } def checkFollows(self, followCandidate ): # basically it checks if user of the application follows a candidate which profile is he viewing by iterating through a collection of users that he follows. for item in q: if item == followCandidate: return True return False -
Django wrap text inside form
Hi i try wrap a text inside my form but nothing works. I tried to style or insert {{ forms|crispy|wordwrap:50 }} but that doesn't work either,the text continues to overflow without a line break does anyone have a solution ? ===page.html=== {% extends 'accounts/main.html' %} {% load crispy_forms_tags %} {% load static %} {% block content %} <br> <style> #id_Note{ padding-bottom: 600px; word-break: break-all; } </style> <h4>Add note</h4> <div class="row"> <div class="col-md-12"> <div class="card card-body"> <form class="note" action="" method="POST"> {% csrf_token %} {{ forms|crispy|wordwrap:50 }} <input class="btn btn-primary" type="submit" value="Enregistrer" name="Enregistrer"> </form> </div> </div> </div> {% endblock %} -
Getting error while eb deploy : ERROR: NotAuthorizedError - Operation Denied. Access Denied
ERROR: NotAuthorizedError - Operation Denied. Access Denied Stack: Django application hosted on AWS using Elasticbeanstalk. Everything was working fine the last time I deployed using eb deploy for my QA environment. Now suddenly getting this error that I'm not authorized to perform this action. Checked the credentials and key-pair as well. Nothing in the settings has been updated after the last deployment. The only thing that is different from the previous deployment is packages since requiremnents.txt has been updated. eb ssh is working fine as well. -
React-Django csrf token Authentication
I'm really stuck here, and I've tried everything I've seen online. I followed this guide to perform react-Django csrf token Authentication. when I send a request to csrf cookie it looks like everything works in the backend (django) side: [05/Oct/2022 22:21:59] "GET /accounts/csrf_cookie HTTP/1.1" 200 29 @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({'success': 'CSRF cookie set'}) And same from the frontend (react) side: 1. {data: {…}, status: 200, statusText: 'OK', headers: {…}, config: {…}, …} 1. config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} 2. data: {success: 'CSRF cookie set'} 3. headers: {content-length: '29', content-type: 'application/json'} 4. request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} 5. status: 200 6. statusText: "OK" 7. [[Prototype]]: Object useEffect(() => { const fetchData = async () => { try { const res = await axios.get( `${process.env.REACT_APP_API_URL}/accounts/csrf_cookie` ); console.log(res); } catch (err) { console.log(err); } }; fetchData(); setcsrftoken(getCookie("csrftoken")); }, []); Again it seems as if the whole process was completed successfully, the problem is that in practice no cookie appears in my browser! If I manually enter http://127.0.0.1:8000//accounts/csrf_cookie I do get the cookie for the browser... I would appreciate … -
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?