Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to define range in "for" at Django template
Django ListView returns object_list, and in Template I want to take the data only once using "for". So I wrote this code. {% for item in object_list(range(1)) %} But this code does not work. Here is the error code. Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '(range(1))' from 'object_list(range(1))' I know my for code is something wrong, please teach me how to write properly. I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you. -
how to display a form in function based view
I have got an error when I tried to display a form in function-based view in Django. I could display it in another HTML file and users can make their comments to the blog. But, I think it can be more convenient for users if they can make a comment on the same blog-detail HTML file, so I wanna implement it. When I tried, this error showed up. "NoReverseMatch at /blogs/blog/30/ Reverse for 'blog' with no arguments not found. 1 pattern(s) tried: ['blogs/blog/(?P[0-9]+)/$']" Any comments can help me and thanks for your time in advance!! Here are the codes I wrote... from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('user', 'text',) #views.py @login_required def blog(request, pk): blog = get_object_or_404(Blog, pk=pk) form = CommentForm() # if request.method == 'POST': # form = CommentForm(request.POST) # if form.is_valid(): # comment = form.save(commit=False) # comment.blog = blog # comment.save() # return redirect('blog', pk=blog.pk) # else: # form = CommentForm() if blog.link_1 is not None and blog.link_2 is not None: link_1 = blog.link_1 link_2 = blog.link_2 context = { 'blog': blog, 'link_1': link_1, 'link_2': link_2, 'form': form, } elif blog.link_1 is not None or blog.link_2 is … -
Python/Django read a cookie that was set with JavaScript
I am building an application using Python/Django. I have set a cookie using Javascript: document.cookie = "color=blue" In my Django-middleware-function I need to provide a choice to redirect or not based upon the value of the cookie. I do not know how to read the cookie. I don't even know if it is possible. Any advice would be appreciated. -
How to connect the m2m_change with pre_save signal?
I have a model MyTracingModel that track the changes that occur on the other models, i create a signal function that compares the old model with the instance and if they are equal then it will just pop the fields out so I keep only the changed fields. this function does not register the changes that accur on the ManyToManyfields, so I created a signal that registers the changes that occur on the many to many fields. Problem: I don't now how to append the fields that I got from the m2m_changed function in the data variable that is in the pre_save function. Goal: I need to have all the changed fields in one palce @receiver([m2m_changed]) def __init__(instance, sender, action, **kwargs): ... if action == "post_remove": data.append({fieldname:[ids..]}) @receiver([pre_save]) def __init__(sender, instance, **kwargs): data = modelfields ... for field in modelfields: if field == field: data.pop(key) if key != 'id' else None MyTracingModel.ojbects.create(data=data) Note: don't warry about infint recursoin issue I set if model.__name__ == MyTracingModel`:pass -
Change password form or link in abstractuser django custom user model
I created a custom user model using abstractuser and replace mobile with username and then recreate user page in admin but my problem is I don't have change password form (in default Django authentication) and if I put save method and change other data in the user model then empty password stored and user can not login any more models.py: class MyUser(AbstractUser): username = None mobile = models.CharField(max_length=15, unique=True) international_id = models.CharField(max_length=25, blank=True, null=True) company_name = models.CharField(max_length=255, blank=True, null=True) business_code = models.CharField(max_length=25, blank=True, null=True) otp = models.PositiveIntegerField(blank=True, null=True) otp_create_time = models.DateTimeField(auto_now=True) objects = MyUserManager() USERNAME_FIELD = 'mobile' REQUIRED_FIELDS = [] backend = 'custom_login.mybackend.ModelBackend' admin.py: class MyUserAdmin(admin.ModelAdmin): list_display = ['mobile','company_name'] search_fields = ['mobile'] form = UserAdminChangeForm fieldsets = ( (None, {'fields': ('mobile','email','password','otp')}), ('Personal Info', {'fields': ('first_name', 'last_name','international_id')}), ('Company Info', {'fields': ('company_name','business_code')}), (_('Permissions'), {'fields': ('is_active', 'is_staff','is_superuser','groups','user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) class Meta: model = MyUser admin.site.register(MyUser,MyUserAdmin) forms.py: from django import forms from .models import MyUser from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext as _ class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ # password = ReadOnlyPasswordHashField(label=("Password"), # help_text=("Raw passwords are not … -
virtualenv raises importerror because of changing app name in django
I've used [this link] to rename my django app. So I've edited some files and table's name and so on. But as it has been mentioned in that link, There is problem with virtualenv. So how can I fix it? I've change name "notes" to "blog". -
Django - divert all messages running in a Google Cloud Engine Instance into a file
How can I divert all messages of a Django application that runs in a Google Cloud Engine instance into a file ? This is my current settings for the logging options : LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/tmp/mylogs.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } It provides output (which are created with logging functions) to some extend, however when there is a stack trace and exception. It does not provide the output into the file. This is how I execute Django on the console : python3 manage.py runserver --noreload >> /tmp/mylogs.log -
HTML changes not reflecting in Django
I am new to Django and have started a project but I am facing an issue. All my pages are working fine and the changes I make are getting reflected on the webpage but when I make a changes to my login page, no changes are reflected on the webpage (It is a simple static page, I only used Django template and nothing else). I deleted all the content in the html file and even deleted the whole html file but no error or change was shown and the page loaded just the way it was when first created. I also tried pressing Shift+F5 but nothing worked :( The output in terminal was as follows (even after deleting the file): [25/Jun/2021 10:24:23] "GET /login HTTP/1.1" 200 8183 -
I am currently using DRF token based authentication where i want to give a role to the user of either a mentor or the student, how to achieve that?
serializers.py for authentication from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token', 'username', 'password') views.py for authentication from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token', 'username', 'password') models.py class NormalUser(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.IntegerField(default=0) email = models.EmailField() mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return str(self.name) class Mentor(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) name = models.CharField(max_length=30) email = … -
Local Development Server Errors
Exception happened during processing of request from ('127.0.0.1', 56261) Traceback (most recent call last): File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 720, in init self.handle() File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
My pipenv is not recognized whenever i try to create a virtual environment, how do i solve this?
I've installed pipenv on my terminal, however whenever I try to start pipenv shell to create a virtual environment this error shows up "pipenv : The term 'pipenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + pipenv shell + ~~~~~~ + CategoryInfo : ObjectNotFound: (pipenv:Strin g) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException" what is wrong and how do I get around it? -
how to get dropdown selected value and not text while submitting form in django views?
i have a dropdown list which you can see on left side. i want to fetch the value of dropdown in my views.py but when i cleaned_data['city'] it gives me the text of the selected value and not the value . how can i get this? can anyone help me models.py from django.db import models from .validator import validate_age # Create your models here. class City(models.Model): city_name=models.CharField(max_length=200) def __str__(self): return self.city_name class Employee(models.Model): name = models.CharField(max_length=200) pan_number = models.CharField(max_length=200, unique=True, null=False, blank=False) age = models.IntegerField(validators=[validate_age]) gender = models.CharField(max_length=10) email = models.EmailField() city = models.ForeignKey(City, on_delete=models.DO_NOTHING) def __str__(self): return self.name def clean(self): if self.name: self.name =self.name.strip() views.py def employee(request): context = {} if request.POST: form = EmployeeForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] pan_number = form.cleaned_data['pan_number'] email = form.cleaned_data['email'] age = form.cleaned_data['age'] city = form.cleaned_data['city'] gender = form.cleaned_data['gender'] print(city) with connection.cursor() as cursor: cursor.callproc('insert_employee', [name, pan_number, age, gender, email, city]) # qs_add = Employee(name=name, pan_number=pan_number, email=email, age=age, city=city, gender=gender) # qs_add.save() messages.add_message(request, messages.INFO, 'Employee save successfully') context['form'] = context['form'] = EmployeeForm() else: context['form'] = EmployeeForm(request.POST) else: context['form'] = EmployeeForm() return render(request, 'app/employee.html', context) -
How to insert into multiple postgres tables connected with foreign keys in Django ORM
I want to insert into two tables one table is Invoices other one is products. Invoice table connected to product table with product_id fk. A invoice can have multiple products at the same time and invoice detail and product details shall be insert at the same time (there is no existing product on products table) so I have to models: class Invoice(models.Model): ... product = model.Foreignkey (products, releted_name="invoice_product", on_delete=models.CASCADE) ... class Products(models.Model): id = models.Charfield() name = models.Charfield() ... -
How to set date limit to a user for a particular package in Django
I have a model named as Plans which is independent of user but when user buys a plan it stored in UserPlanSubscription model so problem is when user buys particular plan user will get that plan for a Month, Year or 6 Month so I want to set expiry of that plan for example if I buyed a Plan for 6 Month so it should expire after 6 Month how can I do this. this is my UserPlanSubscription model class UserPlanSubscription(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE,null=True,blank=True) plan = models.ForeignKey(Plans, on_delete=models.CASCADE,null=True,blank=True) paid = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False,null=True) and this is my Plans model class Plans(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) plan_name = models.CharField(max_length=255, null=True) plan_note = models.CharField(max_length=255, null=True) plan_price = models.CharField(max_length=255, null=True) access_to = models.ManyToManyField(Add_e_office) -
i am getting multivaluedictkeyerror while getting values from the form
i wanted some details to update in user details model but when i try to read valued in th request it show the multivaluedictkeyerror. error image error image 1, error image 2 views.py @csrf_exempt def updateuser(request): myuser=request.user obj=User.objects.get(id=myuser.id) if request.method == 'POST': p=request.POST['phone'] a=request.POST['add'] e=request.POST['edu'] em=request.POST['email'] c=request.POST['country'] s=request.POST['state'] userdetails.objects.create(user=obj,phone=p,address=a,edu=e,country=c,state=s) return render(request,'profile.html') html code <form action="updateuser" method="POST"> {% csrf_token %} <div class="row mt-3"> <div class="col-md-12"><label class="labels">PhoneNumber</label><input type="tel" class="form-control" placeholder={{uobj1.phone}} name="phone" required></div> <div class="col-md-12"><label class="labels">Address</label><input type="text" class="form-control" placeholder={{uobj1.address}} name="add" required></div> <div class="col-md-12"><label class="labels">Email ID</label><input type="email" class="form-control" placeholder={{uobj.email}} name="email" ></div> <div class="col-md-12"><label class="labels">Education</label><input type="text" class="form-control" placeholder={{uobj1.edu}} name="edu" required></div> </div> <div class="row mt-3"> <div class="col-md-6"><label class="labels">Country</label><input type="text" class="form-control" placeholder={{uobj1.country}} name="country" required></div> <div class="col-md-6"><label class="labels">State/Region</label><input type="text" class="form-control" value="" placeholder={{uobj1.state}} name="state" required></div> </div> <div class="mt-5 text-center"><button class="btn btn-primary profile-button" type="submit">Save Profile</button></div> </form> -
Page not found (404) on django
I am using django 3.2 to build a personal e-commerce project, Got Error-Page not found (404) on visiting my products page url Method:GET URL:http://127.0.0.1:8000/products Using the URLconf defined in main.urls. I have followed all the conventions and the other pages are all working but this one is giving me a[urls[\views][1][browser display] hard time as i feel everything is correct, i might be wrong, pls help and if u need to see more of my code, please let me know. This is my code for urls from django.urls import path from django.views.generic.detail import DetailView from django.views.generic import * from main import models, views app_name = 'main' urlpatterns = [ path('', views.home, name='home'), path('about_us/', views.about_us, name='about_us'), path('contact-us/', views.ContactUsView.as_view(), name='contact_us'), path( "products/<slug:tag>/", views.ProductListView.as_view(), name="products" ), path("product/<slug:slug>/", DetailView.as_view(model=models.Product), name='product'), ] my code for views from django.views.generic.edit import FormView from .forms import ContactForm from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.shortcuts import get_object_or_404 from main import models class ProductListView(ListView): template_name = "main/product_list.html" paginate_by = 4 def get_queryset(self): tag = self.kwargs['tag'] self.tag = None if tag != "all": self.tag = get_object_or_404( models.ProductTag, slug=tag ) if self.tag: products = models.Product.objects.active().filter( tags=self.tag ) else: products = models.Product.objects.active() return products.order_by("name") then my browser Page not found (404) … -
when I try to run my django server I get an error
The error is django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: something apparently I have 2 applications that are the same but I don't I checked. Not sure how to fix this. -
How to get form values in template before submit the form?
I created a form with Django. In this form I have a filefield. How can I find out if the user has filled in this field before the form is submitted? I want to pop up a warning screen if the file didn't load like "Are you sure?". How can I do that? This is an example form: <form method="post" enctype="multipart/form-data" > {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-warning">Submitbutton> </form> **model: ** class Pdf(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=customer_directory_path, null=True, blank=True) document_type = models.CharField(max_length=200, default='Select', choices=CHOICES) ... -
How to Display Category name of Product in Django?
I have a relation between category, subcategory, and sub-child category, and the product is related to the sub-child category, but I want to display the name of Category. Please let me know how I can do it. here is my models.py file... class Category(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) class SubCategory(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True) class SubChildCategory(models.Model): subcategory=models.ForeignKey(SubCategory, related_name='SubChildRelated', on_delete=models.CASCADE, default=None, verbose_name='Sub Category') name=models.CharField(max_length=50, default=None) slug=models.SlugField(unique=True, max_length=50) here is my product models.py file... class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ManyToManyField(SubChildCategory, related_name='pro_subchild', verbose_name='Select Category') here is my views.py file... def home(request): allProds=[] catprods= Product.objects.values('subcategory__subcategory__category', 'slug') cats= {item["subcategory__subcategory__category"] for item in catprods} for cat in cats: prod=Product.objects.filter(subcategory__subcategory__category=cat) n = len(prod) nSlides = n // 10 + math.ceil((n / 10) - (n // 10)) allProds.append([prod, range(1, nSlides), nSlides]) return render(request, 'main/index.html',{'allProds':allProds} here is my index.html file... {% for product, range, nSlides in allProds %} <div class="section small_pt pb-0"> <div class="custom-container"> <div class="row"> <div class="col-xl-3 d-none d-xl-block"> <div class="sale-banner"> <a class="hover_effect1" href="javascript:void()"> <img src="{% static 'front/assets/images/shop_banner_img6.jpg' %}" alt="shop_banner_img6"> </a> </div> </div> <div class="col-xl-9"> <div class="row"> <div class="col-12"> <div class="heading_tab_header"> <div class="heading_s2"> <h4>{{product.subcategory.SubChildRelated.subcategoryies.name}}</h4> </div> <div class="view_all"> <a href="{{obj.cat_slug}}" class="text_default"><i class="linearicons-power"></i> <span>View All</span></a> </div> </div> </div> </div> <div class="row"> <div class="col-12"> <div class="tab_slider"> … -
My point annotation in Chart.js 3.3.2 won't render in my Django template. Making a realtime graph of temperature for my wood-fired pizza oven
The goal and problem: I'm having trouble getting an annotation to render in Chart.js. My project is a Django/Chart.js-run graph that shows the temperature of my wood fire pizza oven. I would like to see the temperature graphed over time and be able to submit a model form indicating when I have shut the door, and to have that annotated on the graph. Specific issue The issue is that I can't get the annotation to render on my graph, partly because I am unsure what x/y coordinate to put in. This can be seen in the const options variable in my index.html. In order, have attached my base.html, index.html, view.py, and forms.py. I also included a link to a screen shot of the graph so far and of my pizza oven in case you're curious. :P Versions I'm using Python 3.9.5, Chartjs 3.3.2, and Django 3.2.4. Would be grateful for some help! -Mike <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!--Chartjs CDN--> <!--<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>--> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %} {% … -
How do I exclude values based on one model's queryset to in another model
I'm having two models, bike and BikeRentHistory. All I want to do is I want to search for the bikes which are available and not on rent on selected from_date, from_time, to_date, and to_time. I'm trying to filter all the bikes' IDs from the BikeRentHistory model which are on rent on the selected from date and time, to date and time and then excluding those IDs from the bike model so that I can get available bikes. Can anyone help me on how do I filter in this? models.py class bike(models.Model): BIKE_STATUS_CHOICES = [('A', 'Available'), ('R', 'On Rent')] operatorid = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, help_text='Enter operator id') bikename = models.CharField(max_length=50, help_text='Enter bike name', verbose_name='Name of Bike') brandname = models.CharField(max_length=50, help_text='Enter bike brand name', verbose_name='Brand Name') price_hr = models.IntegerField(help_text='Enter bike price per hour', verbose_name='Price Per Hour') price_day = models.IntegerField(help_text='Enter bike price per day', null=True, verbose_name='Price Per Day') registered_no = models.CharField(max_length=50, help_text='Enter bike registered number', verbose_name='Bike Registration Number') bike_image=models.ImageField(upload_to='bike_image', help_text='Add bike image', null=True) bike_manufactured_date=models.DateField(help_text='Add Manufactured date of bike') bikecolor = models.CharField(max_length=50, help_text='Enter bike color', verbose_name='Bike Color') bikestatus = models.CharField(choices=BIKE_STATUS_CHOICES, max_length=1, default='A', verbose_name='Select Bike Status') station_id = models.ForeignKey(Station, on_delete=models.CASCADE, verbose_name='Select Station Location') class BikeRentHistory(models.Model): customer = models.ForeignKey(Customer, on_delete=models.PROTECT, null=True, related_name='customer+') operator = models.ForeignKey(Customer, on_delete=models.PROTECT, … -
Django and Linux users
I'll send it through the translator, so I'm sorry for the mistakes ;) I have a webservice ( nginx gunicorn dhango). I connected django users and linux users using django_pam . Now I need to create a widget in the admin panel that will allow me to create new users. But the widget must also create a user in the operating system . The web service does not have a sudo. What should I do ? P.s. I can't get away from such a trick-the production of the authorities -
How to validate email before send mail and finding whether the mail send - django
I use - is_valid = validate_email(e) for validating email. It can detect if @ is not present or some more but not providing whether the email entered is active now. AND I used sendmail for sending email. I used try except block. Mail is sending but sometimes try code running and someother times except block is running. How to avoid this abnormal behaviour. -
Validating uploaded csv file with django forms
I've just created a simple admin template with such a form: class UploadProductForm(forms.Form): file = forms.FileField(widget=forms.FileInput(attrs={"accept": ".csv"})) Here is how it works: def open_upload_form(self, request): user = request.user if not user.is_superuser: return redirect(reverse("admin:index")) if request.method == "POST": form = UploadProductForm(request.POST, request.FILES) if form.is_valid(): self.generate_objects_from_csv(request.FILES["file"]) [...] else: form = UploadProductForm() context = {"form": form} [...] def generate_objects_from_csv(self, uploaded_file: InMemoryUploadedFile): dataframe = pd.read_csv(uploaded_file, index_col=0) df_records = dataframe.to_dict("records") model_instances = tuple(self.model(**record).to_mongo() for record in df_records) try: self.model._get_collection()\ .insert_many(model_instances, ordered=False) except BulkWriteError: pass Well... Users have a possibility to get the CSV's template to fill it but everyone knows that there's a possibility to change something - the column name or type or whatever and then they'll get a 500 error instead of the Django admin's error. Any ideas on how to make a validation? I would like to achieve this by using a self.model's clean() method or something similar. -
Allow HTML characters in Django Rest Framework serializers
I am returning HTML text from Django Rest Framework, but special characters are rewritten as "HTML safe" text. How do I prevent this behaviour? I know there is a mark_safe() function in Django, but that would require me to rewrite the serializer. Is there an easy way to do this offered by DRF? Here is my serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ("html_text",) Note that the text is safe and only input by admins, not by end users.