Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I make an internal API design where only react app can listen to `internal_api`?
I want to perform (get, post) operations to internal API without exposing the API to the world since it's just for creating new subscribers, managing the landing page, sending emails and mostly create, update, delete operations for administrators that I don't want to be publicly available /api/v1/? version: '3.7' services: internal_api: build: context: ./backend/services/internal_api dockerfile: Dockerfile container_name: internal_api command: gunicorn internal_api.wsgi:application --bind 0.0.0.0:8000 -w 2 volumes: - static_app:/home/app/app/static ports: - 8000:8000 env_file: - ./devops/.env.internal_api.prod depends_on: - database_01 landing: build: context: ./frontend/landing container_name: landing volumes: - ./frontend/landing:/usr/src/app networks: external_network: internal_network: internal: true``` -
django - Over time, Status value is how to update automatically
class Matching(SoftDeleteObject, models.Model): class MatchingStatus(models.TextChoices): REQUEST_REQUIRED = "RR" MATCHING_PROCEEDING = "MP" MATCHING_DONE = "MD" PAST_SCHEDULE = "PM" MATCHING_FAIL = "MF" matc_dt = models.DateField(validators=[validate_date], null=True) matc_time = models.TimeField(null=True) matc_stat = models.CharField(choices=MatchingStatus.choices, max_length=2, default="RR" ) After "matc_dt" and "matc_time" are over the current time, we would like to automatically update the status value to "PAST_SCHEDULE = PM". What should I do? -
Slug id not displaying (found) : http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily
Sir, I'm developing a slug project in Django. When I try to print the slug id post it will not display shows 404 error. Tried n number of times. Anyone, please help me to fix this in urls.py. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/postscommentapp/6/how-learn-anything-very-easily Using the URLconf defined in postscommentpro.urls, Django tried these URL patterns, in this order: admin/ postscommentapp/(?P\d+)/(?P[\w-]+)/$ [name='post_detail'] The current path, postscommentapp/6/how-learn-anything-very-easily, didn't match any of these. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'draft'), ('published', 'published') ) title = models.CharField(max_length=50) slug = models.CharField(max_length=50) author = models.ForeignKey(User, on_delete = models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft') def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post # Register your models here. class AdminPost(admin.ModelAdmin): list_display = ['title', 'slug', 'body', 'author', 'created', 'updated', 'status'] prepopulated_fields = {'slug':('title',)} list_editable = ('status',) admin.site.register(Post, AdminPost) views.py from django.shortcuts import render from .models import Post # Create your views here. def post_List(request): posts = Post.objects.all() return render(request, 'postscommentapp/post_list.html', {'posts':posts}) def post_detail(request, id, slug): post = Post.objects.get(id=id) return render(request, 'postscommentapp/post_detail.html', {'post':post}) url.py - postscommentapp from django.urls … -
How add guild user Discord
I try add member on guild documentation My code: views.py def login(request): template = loader.get_template('login.html') code = request.GET.get('code') at = Oauth.get_access_token(code) user_json = Oauth.get_user_json(at) id_user = user_json.get('id') invite = Oauth.join_server(id_user).get('message') context = { 'code': code, 'access_token': at, 'id_user': id_user, 'invite': invite, } return HttpResponse(template.render(context, request)) Oauth.py @staticmethod def join_server(user_id): guild_id = 'guild_id' url = f'{Oauth.discord_api_url}/guilds/{guild_id}/members/{user_id}' bot = 'token_bot' headers = {"Authorization": f"Bot {bot}", "Content-Type": "application/json", } link = requests.get(url=url, headers=headers).json() return link I get error: {'message': '405: Method Not Allowed', 'code': 0} {'message': 'Unknown Member', 'code': 10007} how fix it? -
Please correct the error below i can not add the data in the model
enter image description here Can someone suggest what I am doing wrong? I always get the erro model.py from django.db import models from datetime import datetime from ckeditor.fields import RichTextField Create your models here. class Youtuber(models.Model): crew_choices = ( ('solo','solo'), ('small','small'), ('large','large'), ) camera_choices = ( ('canon','canon'), ('nikon','nikon'), ('sony','sony'), ('red','red'), ('fuji','fuji'), ) category_choices = ( ('code','code'), ('mobile_review','mobile_review'), ('vlogs','vlogs'), ('comedy','comedy'), ('gaming','gaming'), ) name=models.CharField(max_length=254) price = models.IntegerField() photo = models.ImageField(upload_to='media/ytubers/%Y/%m') video_url = models.CharField(max_length=255) description = RichTextField() city =models.CharField(max_length=255) age =models.IntegerField() height = models.IntegerField() crew =models.CharField(choices=crew_choices, max_length=255) camera_type =models.CharField(choices=camera_choices, max_length=255) subs_count =models.CharField(max_length=255) category =models.BooleanField(choices=category_choices, default=False) is_featured =models.BooleanField(default=False) created_date =models.DateTimeField(default = datetime.now, blank=True ) admin.py from django.contrib import admin from .models import Youtuber from django.utils.html import format_html Register your models here. class YtAdmin(admin.ModelAdmin): # def myphoto(self,object): # return format_html('<img src="{}" width="40" />.format(object.photo.url)') list_display = ('id','name','subs_count','is_featured') search_fields = ('name','camera_type') list_filter = ('city','camera_type') list_dispaly_link = ('id','name') list_editable = ('is_featured',) admin.site.register(Youtuber,YtAdmin) -
Choices Field link to an attribute.Django
Is there a way to link a specific Choices field to an attribute? I've done some research and did not see anything posted. Models.py SIZES_CHOICES = ( ('Small', 'Small'), ('Medium', 'Medium'), ('Large', 'Large') ( class Item(models.Model): name = models.CharField(max_length=50) sizes = models.CharField(choices=SIZES_CHOICES, max_length=50, null=True, blank=True, default="Small") small_item = models.FloatField(null=True, blank=True, (code that will associate it to Small Size)) medium_item = models.FloatField(null=True, blank=True, (code that will associate it to Medium Size)) large_item = models.FloatField(null=True, blank=True, (code that will associate it to Large Size)) -
Is there any good Ebook for Django?
I am in search of a good ebook for Django python. The book shall be for beginners with step to step guide and introduction of models, urls, etc. If anyone knows such a book then please provide me with a link to download that book. Thanks -
How can i get value which i have entered in sweetify input field?
sweetify.success(request,"Enter Otp",content = 'input',button='Confirm',persistent = True) How can i get this value entered by user ? -
self.request.user does not work in Django REST framework
I want to give only the information of the user who requested with self.request.user, but for some reason, this way I get the information of all users. How can I improve this so that we can retrieve only the information of the user who requested it? Please let me know if you know anything about this. View class StatisticsViewSet(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = EntrySerializer def get(self, request): queryset = self.request.user.entries.all() serializer = StatisticsSerializer(queryset) return Response(serializer.data) Serializer class StatisticsSerializer(serializers.Serializer): daily_report = serializers.SerializerMethodField() daily_report_week = serializers.SerializerMethodField() def get_daily_report(self, obj): data = Entry.objects.all().values( 'created_at__year', 'created_at__month', 'created_at__day').annotate(Sum('time')).order_by( 'created_at__year', 'created_at__month', 'created_at__day') ........ ... ... -
How to add X-BULK-OPERATION with HTTP_AUTHORIZATION in session credentials (headers). Pytest, Django
I'm writing test for Django Rest Framework with PyTest. There was a problem with headers X-BULK-OPERATION because I can't add X-BULK-OPERATION with HTTP_AUTHORIZATION on header. my code session.credentials(HTTP_AUTHORIZATION=response.data.get("token", None), **{"HTTP_X-BULK-OPERATION": True}) error {'detail': "Header 'X-BULK-OPERATION' should be provided for bulk operation."} print request, as you can see I have Bulk-Operation in header 'HTTP_AUTHORIZATION': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjcm1fdXNlciI6MSwiY3JtX2lkIjoxLCJncm91cF9pZCI6MSwiZGVhbF9wZXJtIjp7ImNyZWF0ZSI6MSwiZGlzcGxheSI6MSwiZWRpdCI6MSwiZGVsZXRlIjoxLCJleHBvcnQiOjF9LCJjb250YWN0X3Blcm0iOnsiY3JlYXRlIjoxLCJkaXNwbGF5IjoxLCJlZGl0IjoxLCJkZWxldGUiOjEsImV4cG9ydCI6MX0sImxlYWRfcGVybSI6eyJjcmVhdGUiOjEsImRpc3BsYXkiOjEsImVkaXQiOjEsImRlbGV0ZSI6MSwiZXhwb3J0IjoxfSwidGFza19wZXJtIjp7ImNyZWF0ZSI6MSwiZGlzcGxheSI6MSwiZWRpdCI6MSwiZGVsZXRlIjoxLCJleHBvcnQiOjF9fQ.Wrd89a8jpRnNu1XhNsOKFAkNQR6v_Y_X0nKySocMtLM', 'HTTP_X-BULK-OPERATION': True} -
Like in the comments didn't work and return json page response `{"a_c_like": true}`
I build the comment system and when I click like in the first comment the like appears successfully but when I come to the next comment It returns the JSON response page {"a_c_like": true} instead of like appear and the like count in the span also didn't work (count). I build my comment system on the MPTTModel my view def add_like_to_comment(request, id): comment = Comment.objects.get(id=id) data = {} if request.method == 'POST': account = request.user if comment.likes.filter(id=account.id).exists(): comment.likes.remove(account) a_c_like = False else: comment.likes.add(account) a_c_like = True data["a_c_like"] = a_c_like print(data) return JsonResponse(data) my urls path('comment/like/<int:id>/like', add_like_to_comment, name='add_like_to_comment'), the html template <form method="POST" action="{% url 'video:add_like_to_comment' node.id %}" id="comment-like-form"> {% csrf_token %} <button style="color: #aaaaaa;" class="remove-default-btn p-0 border-0 " type="submit" style="border: none; color: #aaaaaa;" > <svg width="1.5em" height="1.5em" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16" > <path d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z"/> <span class="ml-1" >{{ node.likes.all.count }}</span></svg> </button> </form> Ajax file which handles the like comments $("#comment-like-form").submit(function(e){ e.preventDefault(); var form = $(this); let url = form.attr("action"); $.ajax({ type: "POST", … -
Showing model data as dropdown list in html Template in Django?
I am trying to access model's data for implementation as dropdown menu but I got stuck in this problem. Can anyone help me?? Here is what i have.... views.py def educationdata(request): obj = DegreeDetails.objects.all() context={ 'Data':obj } return render(request,'Education.html', context) This the view I have created for the model DegreeDetails Model.py class DegreeDetails (models.Model): degree = models.CharField(max_length=10) discipline = models.CharField(max_length= 15) def __str__(self): return '%s %s'%(self.degree, self.discipline) This is the model i am using and this model is used as a ForeignKey in another model as follows, hence i want to show it as dropdown field degree_details = models.ForeignKey(DegreeDetails, on_delete= models.CASCADE) Template.Html <div class="col-lg-8 col-md-8"> <label>Degree Details</label> <input type="text" name="degree_details" id="inputdegree_details" class="form-control" placeholder="Select from Dropdown" value="{{education_form.initial.degree_details}}"> <select class="form-control"> {% for data in Data %} <option>{{data}}</option> {% endfor %} </select> Look forward to your responses, Thank you -
DjangoCMS: Image/picture not showing on the UI
I am using the djangocms for the 1st and I am trying to add an image on the cms page, but it's not showing it's giving a 404 error. Steps performed: pip3 installed djangocms-picture>=2.3,<2.5 In INSTALLED_APPS added 'djangocms_picture' also sets following variables: MEDIA_URL = "/media/" MEDIA_ROOT = '/home/media' CMS_MEDIA_ROOT = MEDIA_ROOT CMS_MEDIA_URL = MEDIA_URL Files get uploaded for the plugins and respected folders too got created but on the CMS UI, it's showing a 404 error. am I missing something or whats steps need to perform more to show an image on the CMS UI. -
AWS S3 bucket returns 403 error when referencing a static folder path in Django project
I'm hosting static files in an S3 bucket for a Django web app. All has been well so far using the Appwork custom admin template: https://uxpowered.com/products/appwork/v160/ The files are rendered fine locally but unable to render from the S3 bucket. I believe the error is the script below that is referencing a folder path instead of a direct file. <script> window.themeSettings = new ThemeSettings({ cssPath: "{% static 'app/admin/assets/vendor/css/rtl' %}", themesPath: "{% static 'app/admin/assets/vendor/css/rtl' %}", }); </script> How can I solve this problem? I confirmed the bucket folder exists and contains the correct files. static files errors -
Django Dependent/Chained Dropdown/Combo List
Cascading not working. When I select Supplier, Services is not working. Nothing is happening. on form load, the "Services" is not empty even though the code is there I am not sure if forms.py is really needed or not. Models.py class supplierMaster(models.Model): # supplierId = models.AutoField(primary_key=True) supplierName = models.CharField(max_length=25) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return self.supplierName class servicesMaster(models.Model): # serviceId = models.AutoField(primary_key=True) serviceName = models.CharField(max_length=50) supplierid = models.ForeignKey(supplierMaster, on_delete=models.CASCADE) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) def __str__(self): return self.serviceName class milestonesTran(models.Model): # milestoneid = models.AutoField(primary_key=True) supplierid = models.ForeignKey(supplierMaster, on_delete=models.CASCADE, default=0) serviceid = models.ForeignKey(servicesMaster, on_delete=models.CASCADE, default=0) serviceDate = models.DateTimeField(default=timezone.now) SERVICES_STATUS_CHOICES = [(3, 'Pending'), (4, 'Completed')] servicestatus = models.IntegerField(choices=SERVICES_STATUS_CHOICES, default=3) status = models.ForeignKey(statusMaster, on_delete=models.CASCADE) createdOn = models.DateTimeField(auto_now_add=True) Views.py def add_maintenance(request): services = servicesMaster.objects.all() supplier = supplierMaster.objects.all() servicestatus = statusMaster.objects.filter(pk__in=[3, 4]) status = statusMaster.objects.filter(pk__in=[1, 2]) # print(supplier) return render( request, 'maintenance_add.html', { 'services': services, 'suppliers': supplier, 'servicestatus': servicestatus, 'status': status }) def add_maintenance_save(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: servicedate = request.POST.get("serviceDate") servicename = request.POST.get("servicelist") suppliers = request.POST.get("supplierlist") servicestatus = request.POST.get("servicestatuslist") status = request.POST.get("status") try: milstone = milestonesTran(serviceDate=servicedate, serviceid_id=servicename, supplierid_id=suppliers, servicestatus=servicestatus, status_id=status) milstone.save() messages.success(request, "Maintenance Added Successfully") return HttpResponseRedirect('/servicetracker/add/') except: messages.error(request, "Failed to Add Maintenance") … -
How to update an object and redirect back to home page?
I'm building a website where you can upload photos with name. You can also edit the name and/or the photo after uploading it and I'm having trouble with the edit function. This is my views.py def edit(request, id): photo = Photo.objects.get(id=id) form = PhotoForm(instance=photo) if request.method == 'POST': form = PhotoForm(data=request.POST, instance=photo) if form.is_valid(): form.save() context = { 'obj' : form.instance } # I want it to redirect back to the upload page which i set as '' in urls.py return redirect('/') else: context ={ 'form':form } return render(request, "edit.html", context) This is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',upload, name='upload_from'), path('edit/<int:id>', edit, name='edit_form'), ] This is my edit.html {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'main.css'%}"> </head> <body> <h2> What do you want to change? </h2> <form id= 'edit_form' action="." method = 'POST' enctype='multipart/form-data'> {% csrf_token %} {{ form.as_p }} <button type = 'submit'> Submit </button> </form> </body> </html> I get an error saying "Page not found" and the http in the browser shows up as: http://127.0.0.1:8000/edit/ I'm assuming is not working because the browser is looking for edit/ with no id, therefore the page is not found, but why is it … -
I want to update a DIV that will contain an image from a database PostgreSQL, without refreshing the entire page. Backend Django
I want to update a DIV that will contain an image, initially there is no image, the image is in a database (the images table will have a field with the image path) PostgreSQL. Every time the database loads an image (it can be at any time) the DIV must be updated, showing the new image, without refreshing the HTML page. If the user wants to see the next image loaded in the database, he will only have to refresh the page. Thank you very much for your support. -
Django Rest frame Work send email from contact form
I am not receiving emails sent from the contact form. I tried it with postman and it's not sending any emails. I just removed the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD detail when I want to post the question. Here is my code: Views.py from .serializers import * from rest_framework.permissions import AllowAny from rest_framework.views import APIView from django.core.mail import send_mail from rest_framework import status from rest_framework.response import Response from contactform.api.serializers import ContactSerailizer class ContactView(APIView): def post(self, request, *args, **kwargs): serailizer_class = ContactSerailizer(data=request.data) if serailizer_class.is_valid(): data = serailizer_class.validated_data w3lName = request.POST('w3lName') w3lSender = request.POST('w3lSender') w3lMessage = request.POST('w3lMessage') send_mail('Contact Form mail from ' + w3lName, w3lMessage, w3lSender, ['test@gmail.com'],) return Response({"success": "Sent"}, status=status.HTTP_200_OK) else: return Response({'success': "Failed"}, status=status.HTTP_400_BAD_REQUEST) Serializers.py from rest_framework import serializers class ContactSerailizer(serializers.Serializer): w3lName = serializers.CharField() w3lSender = serializers.EmailField() w3lMessage = serializers.CharField() Settings #Email config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = True Contact.html <form action="{% url 'contact' %}" method="post" class="signin-form"> {% csrf_token %} <div class="form-input"> <input type="text" name="w3lName" id="w3lName" placeholder="Your name"> </div> <div class="form-input"> <input type="email" name="w3lSender" id="w3lSender" placeholder="Your email address" required=""> </div> <div class="form-input"> <textarea name="w3lMessage" id="w3lMessage" placeholder="Your message" required=""></textarea> </div> <div class="text-right"> <button type="submit" class="btn btn-style btn-primary">Submit</button> </div> </form> -
Getting keyerror when trying to populate HTML via Django Template
I'm making an HTML template that populates a table. The show in value refers to my model, Show, with values title, network, release, and desc. Here is the HTML: {% for key, value in request.session.items %} {% for show in value %} <tr> <td>{{ show.id }}</td> <td>{{ show.title }}</td> <td>{{ show.network }}</td> <td>{{ show.release }}</td> {% endfor %} My request.session looks like this in my views.py: def shows(request): request.session['object_list'] = Show.objects.all() print("*"*500) for key, value in request.session.items(): print(key, value) for show in value: print(show) print("*", show.id) print("*", show.title) print("*", show.network) print("*", show.release) print("*", show.desc) print("*"*500) return render(request, 'shows.html') I can get the code to print in shell, as seen above. But when trying to populate my template, it throws an error: Traceback (most recent call last): File "C:\my_environments\djangoPy3Env\lib\site-packages\django\template\base.py", line 470, in parse compile_func = self.tags[command] KeyError: 'show.id' I'm not sure what base.py -> compile_func = self.tags[command] does. I'm assuming the problem comes from a miscommunication between my template and my views.py, but I can't figure it out. May or may not be important, but the KeyError isn't the only error code thrown. Python states that During handling of the above exception, another exception occured: and goes on to list a … -
set' object is not reversible Django
enter image description here Drive link for full code: https://drive.google.com/drive/folders/15VFgum8aNAgd0PhBpcMRb57AUZ0cWUOg?usp=sharing -
Django form, cascading/dependant dropwdown not submitting correctly
I used this tutorial to have a dependant or cascading dropwdown, which lists the state, county and neighborhood while submitting a form. It displays correctly, but when I hit submit, the following error is listed: "Choose a valid option. That option is not available". It has two apps: posts and location, I'll post the posts.models, posts.forms and templates of posts, but not the view because it is a simple CreateView. About the location app, I'll post the models, views and templates I pass the info to the posts app. I did the location app apart because I want to also use it for searching these posts. ANY advice is extremely appreciated. As a side note: Estado = State, Municipio = County and Colonia = Neighborhood Here's my code: posts.models class PostRoom(models.Model): colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=True, null=True) municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=True, null=True) estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=True, null=True) class PostPerson(models.Model): colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=True, null=True) municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=True, null=True) estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=True, null=True) posts.forms class PostPersonForm(forms.ModelForm): class Meta: model = PostPerson fields = ('colonia', 'municipio', 'estado') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['municipio'].queryset = Municipio.objects.none() self.fields['colonia'].queryset = Colonia.objects.none() class PostRoomForm(forms.ModelForm): class Meta: model = … -
Django Toggle Div on Search Query
I have a basic search query to find customers on one of my forms in my Django project. It returns results from the database in an HTML table. The query is executed by clicking the search button. I want to hide the div encapsulating the table when the query has not been executed. Because the JS function is executed when the search button is clicked, the table only shows momentarily until the page reloads. What is the convention for displaying a div after a query is executed, without having a constant toggle button? views.py @method_decorator(login_required, name='dispatch') class CustomerResultsView(ListView): model = CustomerName template_name = 'parent/child.html' context_object_name = 'filtered_customers' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['form1'] = FilterForm(initial={ 'name': self.request.GET.get('name', ''), 'filter_field': self.request.GET.get('filter_field', '') }) context['users'] = self.request.user context['form'] = Customer() return context def get_queryset(self): query = self.request.GET.get('name') filter_field = self.request.GET.get('filter_field') if query: return CustomerName.objects.filter( Q(('%s__icontains' % filter_field, query)) ) else: return {} child.html <form method="GET"> <legend class="border-bottom mb-4">Customer Lookup</legend> <fieldset class="form-group"> {{ form1|crispy }} </fieldset> <div class="form-group"> <input type="submit" class="btn btn-outline-info mt-4" value="Search" onclick="showDiv"> </div> </form> <hr> <div class="table-responsive" id="custTabDiv" style="display:none"> <table id="testTable" class="table table-striped table-hover" cellspacing="0" width="100%"> <thead> <tr> <th … -
Why is this Django DivErrorList being escaped?
I created a DivErrorList class as in these instructions or this stackoverflow answer. To repeat: from django.forms.utils import ErrorList class DivErrorList(ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return '' return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self]) When I use the class as an error_class in a form, I get escaped text. So instead of divs in my page, I get text saying <div class="errorlist">.... I had to add mark_safe to as_divs to get it to work. Is there a reason the example does not have mark_safe, but I need to add it to make it work? Is there some context I'm missing about what is escaped and what isn't? -
Django from github to PC without requirements.txt
wanted to ask if it is possible and if it worth to try to run a cloned Django repo which doesn't have a requirements.txt file ThankYou! -
Initializing Django model field with the model field from the same Model temporarily
I am building a trip reservation app in Django 2.1 and have some problem with updating available seats in the car for the trip. Your help would be greatly appreciated) Here below, I have my first model, I am trying to initialize available_seats with seats just for the first time when the model will be created. First, I tried below method class Trip(models.Model): origin = models.CharField(max_length=120) destination = models.CharField(max_length=120) time_date = models.DateTimeField(auto_now=True) arrival_time = models.DateTimeField() trip_cost = models.IntegerField() vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) seats = models.IntegerField() available_seats = models.IntegerField(default=seats) yes, this method doesn't work because it is not possible to assign a variable to the one which is not defined yet. Thus, I come with solutions that I need to rewrite the save() method of the model or use signals to accomplish what i want. So, I did: class Trip(models.Model): origin = models.CharField(max_length=120) destination = models.CharField(max_length=120) time_date = models.DateTimeField(auto_now=True) arrival_time = models.DateTimeField() trip_cost = models.IntegerField() vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) seats = models.IntegerField() available_seats = models.IntegerField() #rewriting save() method # def save(self, created=False, *args, **kwargs): # if created: # self.available_seats = self.seats # super().save(*args, **kwargs) #using signals @receiver(pre_save, sender=Trip) def default_available_seats(sender, instance=Trip, created, **kwargs): if created: instance.available_seats = instance.seats These two ways …