Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PATCH for many-to-many field in Django
I have two models, modelA and modelB with a many-to-many relationship. I want a PATCH request on /test/{id} which points to TestView to update both modelA and modelB. models.py class modelA(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) class modelB(models.Model): field3 = models.CharField(max_length=100) field4 = models.ManyToManyField(modelA) serializers.py class modelAserializer(serializers.ModelSerializer): field1 = serializers.CharField() field2 = serializers.CharField() class Meta: model = modelA fields = ('field1', 'field2',) class modelBserializer(serializers.ModelSerializer): field3 = serializers.CharField() field4 = modelAserializer(read_only=True) def update(self, instance, validated_data): # **trying to update the models here** return super().update(instance, validated_data) class Meta: model = modelB fields = ('field3', 'field4',) views.py class TestView(Modelviewset): serializer_class = modelBserializer queryset = modelB.objects.all() This is the payload with which I am trying to PATCH. { "field3": "check1", "field4": { "field1": "check1", "field2": "check1" } } -
How a django channel websocket middleware can receive message
How a middleware can read all the websocket message ? From my understanding a django-channel middleware is like https://github.com/django/channels/blob/2a98606c1e0600cbae71ae1f02f31aae5d01f82d/channels/middleware.py. async def coroutine_call(self, inner_instance, scope, receive, send): """ ASGI coroutine; where we can resolve items in the scope (but you can't modify it at the top level here!) """ await inner_instance(receive, send) I know that if I call await receive() instead of await inner_instance(receive, send), I will get a websocket message, but in this case the websocket handler will not work anymore. How can a coroutine_call can receive the websocket message but also forward it to the next websocket middleware or handler ? -
Why doesn’t FloatField accept to input float value?
I’ve build a web app with Django. Although the FloatField was designated as ‘weight’ & ‘height’ model fields, my application refused inputting the float value, accepting only integer. I attempt to declare the FloatField at the forms, but it doesn’t seem to work. I have no idea what’s cause and desire to know how to be able to input the float value with solving this problem. Following are my code and Django is version 2.0 # Model.py class Profile(models.Model): class Meta(object): db_table='profile' user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, primary_key=True) weight=models.FloatField(_('weight'),blank=False) height=models.FloatField(_('height'),blank=False) bmi=models.FloatField(_('BMI')) def __str__(self): return self.user.nickname # Form.py class BioRegisterForm(forms.ModelForm): class Meta: model=Profile fields=('weight','height') help_texts={'weight':('Kg単位で入力してください'),'height':('cm単位で入力して下さい')} def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['weight'].widget.attrs={'placeholder':'Weight','required':True} self.fields['height'].widget.attrs={'placeholder':'Height','required':True} def clean_hight(self): value=self.cleaned_data.get('height') if value<50: raise forms.ValidationError('Type in with 「cm」') return value # View.py class BioRegisterView(CreateView): model=Profile template_name='mysite/bioregister.html' form_class=BioRegisterForm success_url=reverse_lazy('mysite/profile.html') and following are the bioregister.html, page in question <form method='post' action=""> {% for field in form %} <div> <div class='entry'> {{field}} </div> {%if field.errors %} <p> {{field.errors.0}}</p> {% endif %} </div> {% endfor %} {% csrf_token %} <input type="submit" value="Register" class='bottun2'> </form> Thank you -
Unable to pass django template variable array through post back to view
I am trying to develop some basic django templates where i initially pass the django template variable which is an array - {{array_list}}. I am able to perform operations on this dtv easily. But I am unable to post this variable back to views. Eg. I pass {'array_list': [1,2,3,4]} <form action="some_action" method="post"> {% csrf_token %} <input type="submit" value="sort"> <input type="hidden" name="array_list" value={{array_list}}> </form> And in views.py: array_list = request.POST['array_list'] return render(request, 'result.html', {'array_list': array_list}) But i don't get the full array back to result.html, and i only get [1, as the array_list. -
AttributeError: 'tuple' object has no attribute 'profilePic'
I have the following in my models.py profilePic = models.OneToOneField(Document, default=None, null=True, blank=True, on_delete=models.CASCADE) and in my views.py loggedinanon = Anon.objects.get_or_create(username1=loggedinuser) newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() loggedinanon.profilePic = newdoc I can't tell what the code should be to allow the document to be saved as part of the anon. -
getting this error: ModuleNotFoundError: No module named 'asgiref.local'
File "/home/user/myApp/venv/lib/python3.6/site-packages/django/db/utils.py", line 4, in from asgiref.local import Local ModuleNotFoundError: No module named 'asgiref.local' code looks like this: from asgiref.local import Local self._connections = Local(thread_critical=True) using python3.6 on ubuntu 16 please help -
How to create a shopping cart model with item variations
Hi im currently trying to implement a shopping cart model for my cs50w project. In this project we would have to create an online ordering system for a pizza joint. The problem lies where i try to create a cart application, im not sure on how to implement a model that will be able to represent adding a custom pizza (eg, size:s, type: regular, toppings = [Tomatoes, Cheese, Pepperoni]) Currently my models are as follows: | pizza_prices | type | size | topping_count | price | Topping |description | menu_items | desc | price How do you keep the variations that the customer selected into the shopping cart database? And what should the fields inside the model look like? Any help would be great !! been stuck here for quite a long time -
Django admin save and display data only for the logged in user
In my django admin project i have to save and then display data for different user, i would that when i save automatically field user take the loged in user value and when i re logged in i can see only the data saved for my user only. I have this kind of models.py: class TheLinks(models.Model): lk_name = models.CharField(max_length=20) def __str__(self): return self.lk_name class UserComLinks(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="User") l_id = models.ForeignKey(TheLinks, on_delete=models.CASCADE, verbose_name="Portal") l_link = models.CharField(max_length=100) def __str__(self): return str(self.l_id) now if i run my django admin i see this form: well, first i would to hide the username field and make my model save in automatic this data using the current logged in user then i would that when the user logged in can see only hos data. I try to manage admin.py in this kind of fashion: admin.py class UserComLinksAdmin(admin.ModelAdmin): list_display = ('l_id', 'l_link') def changeform_view(self, request, obj_id, form_url, extra_context=None): try: l_mod = UserComLink.objects.latest('id') except Exception: l_mod = None extra_context = { 'lmod': l_mod, } return super(UserComLinksAdmin, self).changeform_view(request, obj_id, form_url, extra_context=extra_context) but nothing change. Can someone pleas help me about? So many thanks in advance -
How to associate ForeignKey when using ModelForm to create an object?
I am trying to create a job board. I have the following models.py. The user creates a business once(but can create more than one), then posts multiple jobs from that business: class Business(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length = 200) address = models.CharField(max_length = 200) city = models.CharField(max_length = 100) state = models.CharField(max_length = 50) zip_code = models.CharField(max_length = 10) phone_number = models.CharField(max_length = 10) class Job(models.Model): business = models.ForeignKey(Business, on_delete= models.CASCADE) title = models.CharField(max_length = 200) description = models.TextField(blank = True) I am trying to use ModelForm to create a "post job" view. forms.py: from django.forms import ModelForm from .models import Job class JobForm(ModelForm): class Meta: model = Job fields = ['title', 'description'] Now, views.py: from .models import Business, Job from .forms import JobForm def post_job(request): if request.method == 'POST': form = JobForm(request.POST if form.is_valid(): # how do I associate a business with an instance of a job before saving the object? form.save() else: form = JobForm() return render(request, 'job/post_job.html', {'form':form}) I tried form.business = request.user.business thinking each Business was associated with a User but that did not work. Thanks for any help. -
Django ability to add and remove foriegn keys through django admim
I want to be able to allow my user to add or remove foreign keys on one of my models. The business logic behind this is that there are many unique products that relate to one "product bundle". I want users to create their own product bundles by creating a new bundle object, then adding or removing products as they see fit. from django.db import models # Create your models here. class Product(models.Model): product_name = models.CharField(max_length=128) def __str__(self): return self.product_name class ProductBundle(models.Model): bundle_name = models.CharField(max_length=128) product_dependencies = models.ForeignKey(Product, related_name="add_product", on_delete=models.CASCADE) def __str__(self): return self.bundle_name Currently its a list with all of the products, which is not the functionality I'm trying to achieve. A lot of posts talk about adding the related_name field to achieve this but for whatever reason it's not working for me -
Django template rendering error in Admin with ManyToMany field
Django is outputting an error while rendering a template for one of my models in the admin interface. Specifically, I am trying to add a new entry in a model, and I'm getting the following error and traceback : Template error: In template C:\ProgramData\Anaconda3\envs\django\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 'int' object is not iterable 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 : {% if field.is_checkbox %} 13 : {{ field.field }}{{ field.label_tag }} 14 : {% else %} 15 : {{ field.label_tag }} 16 : {% if field.is_readonly %} 17 : <div class="readonly">{{ field.contents }}</div> 18 : {% else %} 19 : {{ field.field }} 20 : {% endif %} 21 : {% endif %} 22 : {% if field.field.help_text %} 23 : <div class="help">{{ field.field.help_text|safe }}</div> 24 : {% endif %} 25 : </div> 26 : {% endfor %} 27 : </div> 28 : {% endfor %} … -
How I can I modify my data before serialization in Django rest framework
When User opens main page I have to show all posts from DB. My models look like this: class StoryAndComment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField(max_length=500) edit_date = models.DateTimeField(auto_now=True) pub_date = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Story(StoryAndComment): CATEGORIES_LIST = ( ('Different', 'Different'), ('Funny', 'Funny'), ('Dirty', 'Dirty'), ('Scary', 'Scary'), ('Hatred', 'Hatred'), ('Weird', 'Weird'), ('Mystic', 'Mystic'), ('Shame', 'Shame'), ('Politics', 'Politics'), ('Envy', 'Envy'), ('Cruelty', 'Cruelty'), ('Laziness', 'Laziness'), ('Cats', 'Cats'), ('Childhood', 'Childhood'), ('Dreams', 'Dreams'), ('Family', 'Family'), ('Job', 'Job'), ('Happiness', 'Happiness'), ('Friendship', 'Friendship'), ('Hobby', 'Hobby'), ('Love', 'Love'), ('Music', 'Music'), ) title = models.TextField(max_length=120) category = models.CharField(max_length=30, choices=CATEGORIES_LIST, default="Different") class Meta: verbose_name_plural = "Stories" def __str__(self): return self.title def get_absolute_url(self): return reverse("story_comments", kwargs={"pk": self.pk}) class Comment(StoryAndComment): story = models.ForeignKey(Story, related_name="comments", on_delete=models.CASCADE) class Meta: verbose_name_plural = "Comments" def __str__(self): return self.body[0:20] + "..." Main page view code is like this: My Serialization class is: The issue is I just want to show how many comments each story have, I don't want to fetch every single comment in json. Where and when I can modify my code to change data before sending it to client -
Django-admin is not recognized
I cannot seem to get django to work. I have tried uninstalling/reinstalling it and setting it to path. Here is what i typed in: django-admin startproject example Any ideas? -
Django: included template is not rendering
I've a List objects that is an umbrella for products selected. Inside my main html I'm including a chunk of html with a list of options. I need to do this so this options can be updated without updating the hole html. {% include 'scolarte/listas/listas-de-usuario.html' %} django.template.exceptions.TemplateDoesNotExist: listas-de-usuario.html Main html has a Modal, when the modal is activated it should show this chunk of HTMl included there: Modal shows but I can't see the expected options on the <select> tag. ** MAIN MODAL HTML:** <div class="modal fade" id="SelectListtoAddProduct{{ product.sku }}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <label for="pet-select">Elegir lista:</label> <select name="listas" id="listas-de-usuario"> {% include 'scolarte/listas/listas-de-usuario.html' %} </select> </div> <div class="modal-footer"> <button id="agregarProducto{{ product.id }}" type="button" class="btn btn-secondary" data-dismiss="">Agregar producto</button> </div> </div> </div> </div> listas-de-usuario.html: <option value="">--Eliga una de sus listas--</option> {% for lista in listas %} <option value="{{ lista.id }}">{{ lista.id }} : {{ lista.name }}</option> {% endfor %} Urls: from . import views app_name = "lists" urlpatterns = [ path('', views.AllLists.as_view(), name='my_lists'), path('agregar-producto/', views.add_product_to_list, name='add_product_to_list'), path('mis-listas/', views.update_lists_count, name='update_lists_count'), path('lista-detalles/<int:lista_id>/', views.list_details, name='list_details'), ] JS / JQUERY / AJAX: The first line makes the GET to complete the included chunk of HTML. The second one shows … -
Handle float values beyond the scope of numpy
I have a part of an integral quad function that does x * math.exp(a * b) Where a and b are huge values. a = 13.03 and b = 95.632154355654, for example. And this gave me a math range error. overflowError. Is there any exponential function that can handle extremely large values? I tried using numpy.exp(a * b) But this returned inf. Are there any other alternatives? -
AttributeError at /addimam 'int' object has no attribute '_meta' Django
I got this error when I'm trying to submit Data in my view. Masjid is Taking Data From a specific login user. I cannot understand where the error is coming because my form allow my to view the specific user. Kindly assist in checking for the error. * form = ImamForm(request.POST, instance=masjid) * Kindly check this line of code because the error message is coming from the line forms.py class ImamForm(forms.ModelForm): def __init__(self,user, *args, **kwargs): super(ImamForm, self).__init__(*args, **kwargs) try: masjid_id = Info.objects.values_list('user_id', flat=True).get(user=user) self.fields['masjid'].queryset = Info.objects.filter(user=masjid_id) print(masjid_id) except Info.DoesNotExist: ### there is not userextend corresponding to this user, do what you want pass class Meta: model = Imam exclude = ('updated_at', 'created_at', 'user') views.ppy class NewImam(CreateView): # template_name = "addimam.html" # model = Imam # form_class = ImamForm # #success_url = reverse_lazy('person_changelist') # def form_valid(self, form): # #if not UserProfile.objects.filter(recruiter=self.request.user).exists(): # p = form.save(commit=False) # p.user = self.request.user # p.save() # messages.success(self.request, 'The Imam Details Has Been Added Successully!') # return redirect('addimam') # # else: # # messages.warning(self.request, 'The Profile has been Added Before!') # # return redirect('recruiter:edit_recruiter_profile') def get(self, request, *args, **kwargs): form = ImamForm(user=self.request.user) context = {'form': form} return render(request, 'addimam.html', context) def post(self, request, *args, **kwargs): user … -
Retrieving Unrelated Objects in Django REST Framework
My model consists of 3 classes: Offer, Application, and Contract. Relationships are as follows: Application to Offer: One to One Application to Contract: One to One Is there a way for me to access Contract from Offer via Application in a single REST call? I know how to access Application from Offer since they are related. A way around this is to relate Offer to Contract but I would prefer not to do this because it would not be considered good relational database design. Any help would be greatly appreciated. Thanks. -
DisallowedHost at / Invalid HTTP_HOST header: Django & Lambda
I am uploading a django api built with the django3.0, postgreSQL and django rest framework. Locally everything works good but when I deploy the api to AWS Lambda I am getting the following error: invalid HTTP_HOST header: 'lpzyjitlr0.execute-api.us-east-1.amazonaws.com'. You may need to add 'lpzyjitlr0.execute-api.us-east-1.amazonaws.com' to ALLOWED_HOSTS. I have been combing stack overflow all day today and have tried many of to resolutions in other posts but none have worked for me. I have added the following to allowed hosts and still nothing ALLOWED_HOSTS = ['127.0.0.1', '*******.execute-api.us-east-1.amazonaws.com'] I am not sure what I am doing wrong at this point but would really like to get this up and running. Any help would be greatly appreciated. I have the full project on my github https://github.com/coffeeincodeout/membership -
admin redirects incorrect when hosting outside root url: django
I am running into an issue where when trying to access the django admin panel, I am redirected to the incorrect URL. For example, lets say my django app is located at: example.com/myapp If I try to access example.com/myapp/admin, I am redirected to example.com/admin which incorrect. When curling it looks like I am getting an incorrect location. > GET /myapp/admin/ HTTP/1.1 > User-Agent: curl/7.29.0 > Host: example.com > Accept: */* > < HTTP/1.1 302 Found < Access-Control-Allow-Headers: * < Access-Control-Allow-Methods: POST, GET, OPTIONS < Access-Control-Allow-Origin: * < Cache-Control: no-cache, no-store, must-revalidate, max-age=0 < Content-Length: 0 < Content-Type: text/html; charset=utf-8 < Date: Mon, 20 Jan 2020 23:52:01 GMT < Expires: Mon, 20 Jan 2020 23:52:01 GMT < Location: /admin/login/?next=/admin/ < Server: gunicorn/19.10.0 < Vary: Cookie, Origin < X-Frame-Options: SAMEORIGIN < This only seems to be happening with the admin panel, not my other apps. Any ideas how I can force the correct URL prefix? -
Django Form does not render
my Django form does not render, other forms in the project work without an issue, I am just lost This form is supposed to display in template file product_review.html that then is displayed through {% include %} to products.html I think I should point out that this is a separate Django app My Model: from django.db import models from django.conf import settings from ecommerce.models import Item STAR_CHOICES = ( ('0','0'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ) # Create your models here. class Review(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=40, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) review_content = models.CharField(max_length=300,blank=True, null=True) star_score = models.CharField(choices=STAR_CHOICES, max_length=1) item = models.ForeignKey('ecommerce.Item', on_delete=models.CASCADE) def __str__(self): return self.user.username My Form: from django import forms from ecommerce.models import Item from .models import Review STAR_CHOICES = ( ('0','0'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ) class AddReviewForm(forms.ModelForm): title = forms.CharField(required=True) star_score = forms.ChoiceField( widget=forms.RadioSelect, choices=STAR_CHOICES) review_content = forms.CharField(widget=forms.Textarea(attrs={ 'rows': 4 })) class Meta: model = Review fields = '__all__' exclude = ['user','timestamp','item'] My View: from django.shortcuts import render, get_object_or_404 from .models import Review from .forms import AddReviewForm from ecommerce.models import Item from django.shortcuts import redirect # Create your views here. def AddProductReviewView(View): def post(self, request, *args, **kwargs): item = get_object_or_404(Item, … -
Querying objects created within a time period
I am writing a query, that tries to get a list of users and returns them if they were created within 30 days (1 month). here is what I have tried, models.py class Showcase(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True) serializers.py class ShowcaseSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(read_only=True, slug_field='slug') created_on = serializers.SerializerMethodField(read_only=True) slug = serializers.SlugField(read_only=True) class Meta: model = Showcase exclude = ['id'] def get_created_on(self, instance): return instance.created_on.strftime("%d %B %Y ; %H:%M:%S %Z") views.py class MostLikedMonthShowcasesView(generics.ListAPIView): ''' Most liked showcases created within the past month ''' serializer_class = ShowcaseSerializer permission_classes = [AllowAny] def get_queryset(self): last_30_days = datetime.datetime.today() - datetime.timedelta(30) return Showcase.objects.filter(created_on__lte=datetime.datetime.today(), created_on__gt=datetime.datetime.today()-datetime.timedelta(days=30)).values('created_on') when I run the above code I get 'dict' object has no attribute 'created_on' -
How to post a react state as query parameters with Axios Async (django backend)
Works on postman but not react app. It did work a few months ago on react app. Goal: Want to post the state via axios async, to run a backend search (django). Situation: Currently the search output is all the available items in backend, which is a response reserved for a query with no content - so it is as though the state was sent empty even though the "value" did contain the correct state. Axios post request is as follows ("value" contains the state as an object and i have confirmed it does this successfully; "config" contains a token authorization check) const response = await Axios.post("URL",value, config); The response.data to this request is the whole list of items available, instead of just the ones matching the query params from the state carried by "value" FYI backend search done as below for each param, and then all categories joined in the end via .union() with the whole search output list is returned: ABC = params["ABC"] query = Q() for X in ABC: query = query | Q(X__contains=X) list = List.objects.filter(query) etc list = list_ABC.union(list_DEF, list_GHI, listings_JKL) return list Thanks for any tips on this! -
How to add a default value to fields in the Django Users model?
Currently, I have added a registration functionality to my website thanks to the Users model from the django.contrib.auth.models and I want to add a score field which will give by default 100 points once the user has registered. I have the following code for the user registration: forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): first_name = forms.CharField(max_length=25) last_name = forms.CharField(max_length=25) email = forms.EmailField() score = forms.CharField(max_length=5) # max value 99,999 class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2'] views.py from .forms import UserRegisterForm from django.shortcuts import render, redirect def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): return redirect('login') else: form = UserRegisterForm() return render(request, 'accounts/register.html', {'form': form} The current problem with my code is that the form displays the points field which shouldn't be the case and I am not sure how to indicate to Django that every time the user gets registered then the user should receive a 100 value in score. When I have used a postgresql db, I have implemented this as a default value,i.e., score = models.IntegerField(default=100) but this behavior doesn't work for the Users model from the from django.contrib.auth.models import User because you … -
Post Data to Outlook Calendar using Django, Requests, and Microsoft Graph
I have a function where I am trying to make a post request to my outlook calendar using Microsoft’s Graph API. def create_calendar_event(token, payload, **kwargs): """ Creates a new calendar event :param payload: json str :param token: str :return: dict """ graph_client = OAuth2Session(token=token) url_endpoint = "https://graph.microsoft.com/v1.0/me/events" events = graph_client.post(url=url_endpoint, json=payload) return events.json() In my view I am using a form to get the data from the user so I can in return post the user data to my outlook calendar. The form looks something like this: class CalendarFormView(TemplateView): template_name = "event-form.html" def get(self, request, **kwargs): form = CalendarEventForm() return render(request, self.template_name, {"form": form}) def post(self, request): form = CalendarEventForm(request.POST) token = client.get_token(request) # does get the token correctly if form.is_valid(): subject = form.cleaned_data["subject"] content = form.cleaned_data["body_content"] start = form.cleaned_data["start"] end = form.cleaned_data["end"] location = form.cleaned_data["location"] is_all_day = form.cleaned_data["is_all_day"] payload = { "subject": subject, "body": {"contentType": "html", "content": content}, “start”: { "dateTime": start.strftime("%Y-%m-%dT%H:%M:%S.%f"), "timeZone": "UTC", }, "end": { "dateTime": end.strftime("%Y-%m-%dT%H:%M:%S.%f"), "timeZone": "UTC", }, "location": {"displayName": location}, "isAllDay": is_all_day, } event = create_calendar_event(token, json.dumps(payload)) print(event) return render(request, self.template_name, context=event) return render(request, "event-form.html", {"form": form}) I am getting the access_token and the form data correctly passed into the payload dictionary, however, when … -
Django Template Auto Sanitization vs Bleach Filter
I'm displaying data that is sometimes sanitized before saving to the database, and sometimes its not. Right now, we never render it directly to the template, because Django templates auto sanitize the data, but the problem is that they sanitize the data that has already been sanitized whereas using the bleach filter does not do that. So, for example, say my text is D&W and D&amp;W. I want both to render as D&W. if I insert it into the template as {% for d in data %} {{ d }} {% endfor %} The template outputs D&amp;W D&amp;amp;W and the browser shows D&W D&amp;W But when I use the bleach filter, like: {% load bleach_tags %} {% for d in data %} {{ d|bleach }} {% endfor %} In the template output, I get D&amp;W D&amp;W And in the browser I get D&W D&W Like I want. I have found very little comparing these two filters, but it seems like they do very close to the same thing. My question is: is there any reason not to use the bleach filter here? I'd love to see somebody expand on the differences between the two. PS: You can read about the …