Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django where to specify application related settings
At present my application related variables like external server IP / default pattern etc.. These variables are specific to my application. It includes my external server username and password. Now how can I have a single common place so that I can externalise this from my application. The options which I thought are below: Have one conf.ini file and use configparser and read this during the start of the django app But I am not sure from where I should have method to read this so that it will be done in the startup. Other option is to save this in a py file itself and import this file in my modules Please suggests me the good and standard approach for above issue. -
Django is showing CSS style in base template, but not in other files that they derive from
in Django 1.11 I have base template with navbar and copyright sections that show on every page. That base template loads static files including CSS file. The problem begin when I try to use the same css file to style other html files that open in the same time. I tried to inspect css file in browser and classes that are used by other files doesn't show in browser. Path to css file is relative. I don't know why Django doesn't load that last class from style.css Here is the code of 'base.html' file: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <title>Dadilja.hr</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="{% static "css/style.css" %}"> </head> <body> ... {% block content %} {% endblock %} ... </body> </html> This is html file that I try to style with the same css file. Problematic class is "profilna": {% extends "accounts/base.html" %} {% block content %} {% for dadilja in dadilja_list %} <div class="container"> <div class="col-md-2"> <a href="{{ dadilja.id }}"> <img src="{{ dadilja.slika_profila.url }}" alt="{{ dadilja.ime }} {{ dadilja.prezime }}" class="profilna"> </a> </div> <div class="col-md-10 profilna"> {{ dadilja.ime }} {{ dadilja.prezime }} {{ dadilja.mjesto }} </div> <br><br> </div> {% endfor … -
Django Add fieldset legend to ModelForm
I have a model: models.py class Doc(models.Model): series = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) number = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) name = models.CharField(max_length=150, help_text="3") citizenship = models.ManyToManyField(Citizenship, help_text="4") forms.py class DocForm(ModelForm): class Meta: model = Doc fields = '__all__' How do i add 2 legends for these fields? 1 for series and number and 1 for name and citizenship? template {% for field in form %} <div class="form-group"> <label for="{{ field.id_for_label }}" class="control-label col-md-3">{{ field.label }} {% if field.field.required %}<span class="required"> * </span> {% endif %} </label> <div class="col-md-4"> {{ field }} {% if field.errors %} {% for error in field.errors %} <span id="{{ field.id_for_label }}-error" class="help-block help-block-error">{{ error }}</span> {% endfor %} {% endif %} </div> </div> {% endfor %} -
django printing a table to pdf using weasyprint
Morning, I've created a table for a document template and when a user is attempting to save the document after making amendments to text it saves as a pdf but will not apply the table border i'm currently trying to use weasyprint and this is my css: body { font-family: "Calibri", Calibri, Helvetica, Arial, "Lucida Grande", sans-serif !important; font-size: 11pt; border: 10px; table-border-color-dark: black; } I've tried adding it as table in the css but still no luck i would add my template but am unsure on how to display html on stack overflow as the help doesn't describe very well. This is part of the code i'm using to write to pdf. Code: pdf_file = HTML(string=form.cleaned_data.get('contents')).write_pdf( stylesheets=[ CSS(staticfiles_storage.path('stylesheets/site/pdf.css')) ] ) -
Google container Engine django deployment is raising error
I have set up my Django project to deploy on the container engine based on documentation https://cloud.google.com/python/django/container-engine. After creating kubernetes resources with kubectl create -f project.yaml I try to get the status of the pods with kubectl get pods Each of the pod has status **CrashLoopBackOff** Can you please suggest on debugging this error? -
What are the drawbacks of template tags in django?
It is more of a discussion as I just to know what are the drawbacks of template tags if there are any.I use a lot of template tags in my projects because it solves hell lot of problems.But I do have one query regarding template tags is that does it makes the application slow? Should I avoid using it or there are no drawbacks of template tags? -
Generating the Django route
Tell me, please, why the route is not generated correctly? viewSet: class MyViewSet(BaseViewSet, CreateModelMixin): http_method_names = ['post'] queryset = User.objects serializer_class = MySerializer permission_classes = (AllowAny,) @detail_route(methods=['get'], permission_classes=[IsAuthenticated], url_name='my') def my(self, request, version, pk=None): serializer = MyInfoSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls: users_router = DefaultRouter() users_router.register(r'users', MyViewSet) When you try to navigate to the specified address (http://127.0.0.1:8000/api/v1/users/my/), page 404 appears. Routes are formed like: ^api/ ^(?P<version>(v1))/ ^ ^users/$ [name='user-list'] ^api/ ^(?P<version>(v1))/ ^ ^users\.(?P<format>[a-z0-9]+)/?$ [name='user-list'] ^api/ ^(?P<version>(v1))/ ^ ^users/(?P<pk>[^/.]+)/my/$ [name='user-my'] ^api/ ^(?P<version>(v1))/ ^ ^users/(?P<pk>[^/.]+)/my\.(?P<format>[a-z0-9]+)/?$ [name='user-my'] -
How to solve Jenkins Build trouble?
I have a Django project on BitBucket, so I was going to use Jenkins for CI, but the build keeps failing! Here is the script: cd $WORKSPACE virtualenv -q env . ./env/bin/activate cd requirements pip install -r base.txt cd .. cd manage python test_manage.py test --settings=test_site Here is the result(Jenkins console): ImportError: No module named test_site Build step 'Execute shell' marked build as failure [Cobertura] Publishing Cobertura coverage report... Finished: FAILURE How can I solve this problem ? -
How to increase RAM usage of Celery
I was using 8 GB ram machine, when i ran celery task in that system that particular task able to complete in 45mins Now i have switched to a machine of 40 GB ram, but still i am able to complete the same task in 35 mins. I hope celery is not able to make use of the 40 GB ram properly, how can i customize ram usage of Celery. Please help me with this problem. Thanks! -
How to add DateTimeField in django without microsecond
I'm writing django application in django 1.8 and mysql 5.7. Below is the model which I written class People(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() create_time = models.DateTimeField() class Meta: db_table = "people" Above models create table like below. mysql> desc people; +-------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(20) | NO | | NULL | | | age | int(11) | NO | | NULL | | | create_time | datetime(6) | NO | | NULL | | +-------------+-------------+------+-----+---------+----------------+ Here Django create datetime field with microsecond datetime(6) But I want datetime field without microsecond datetime I have other application, which also using same database and that datetime field with microsecond raising issue for me. -
django pass model fields to BetterForm
I am trying to use BetterForms to group the fields and add a legend to each group. For example i have this model: models.py class Doc(models.Model): series = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) number = models.CharField(max_length=50, help_text="2", blank=True, null=True, default=None) name = models.CharField(max_length=150, help_text="3") citizenship = models.ManyToManyField(Citizenship, help_text="4") forms.py class DocForm(BetterForm): name = forms.CharField(max_length=150, help_text="3") class Meta: model = Doc fieldsets = [ ('main', {'fields': ['name', 'citizenship'], 'legend': 'I. PERSONAL DATA'}), ('main1', {'fields': ['series', 'number'], 'legend': 'II. PROFESSIONAL IDENTIFICATION'})] I have many more fields than i've written here. Is there a possibility to pass the model fields as in ModelForm instead of writing each field in the form again? -
Django manage.py runserver unhandled exception in thread error
In django when I am trying to run manage.py runserver its giving an unhandled exception in thread error. I am using 'ENGINE': 'django.db.backends.sqlite3' Unhandled exception in thread started by Traceback (most recent call last): File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django-1.11.5-py2.7.egg\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) File "C:\Users\MY\Desktop\myproject\firstproject\firstproject\urls.py", line 18, in url(r'^admin/', admin.site.urls), NameError: name 'url' is not defined -
Django Rest Framework authtoken not migrating in MySql but migrating in SQLite
Django Rest Framework authtoken not migrating in MySql but migrating in SQLite Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747...Traceback (most recent call last): File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\django\base.py", line 177, in _execute_wrapper return method(query, args) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\cursor.py", line 515, in execute self._handle_result(self._connection.cmd_query(stmt)) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1091 (42000): Can't DROP 'user_id'; check that column/key exists During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Guest01\Envs\qcrb\Lib\site-packages\django\tokentutor\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "C:\Users\Guest01\Envs\qcrb\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result raise errors.get_exception(packet) django.db.utils.ProgrammingError: Can't DROP 'user_id'; check that column/key exists -
count views for anonymous users in django
I am creating a blog just for practice and i recently added the views counter function the problem is when an anonymous user open the post django raise an error because in the post_detail view i request the username this is the view: def post_detail(request, post_id): post = Post.objects.get(id=post_id) if UserSeenPosts.objects.filter(post=post, user=request.user).exists(): print "all ready" else: post.views += 1 post.save() UserSeenPosts.objects.create(user=request.user, post=post) return render(request, 'blog/detail.html', {'Post': Post.objects.get(id=post_id)}) the UserSeenPosts model: class UserSeenPosts(models.Model): user = models.ForeignKey(User, related_name='seen_posts') post = models.ForeignKey(Post) -
unable to install mysqlclient on mac
Hi guys i'm attempting to install mysqlclient using the command: pip install mysqlclient but i get the following error: Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-ifu54299/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-ifu54299/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/8d/xdwdnphs1w5b_vtxrc67__5h0000gn/T/pip-build-ifu54299/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found I uninstalled python3 using brew uninstall --force python3 and downloaded the binary from pythons website but to no avail. I also attempted to download mysql connector from oracle website and again to no avail. I have tried upgrading pip again still doesnt work. PS mysql is running in a docker container and i'm running django on my local machine. Any suggestions on why i'm getting an error attempting to install mysqlclient -
Django-admin inline default value
admin.py class CaseNoteInline(admin.TabularInline): model = CaseNote extra = 1 max_num = 5 i have a some column in CaseNote which is "User" and i want to set default value for that. -
Caching a frequently used queryset in django
I have a model which is being used a lot in my app (and the data in it almost never changes, unless a dev wants to change something). I'd like to cache this queryset to see what difference it will make for the speed of my views, but can't really get my head around it. I'm using redis and i set the cache like this: m = MyModel.objects.all() cache.set('m', m, timeout=None) And then I get it like this: c = cache.get('m') for x in range(1,200): o = c.get(pk=x) ... which of course leads to 200 DB queries. How can I store everything in the cache so that every lookup I do gets the data from the cache? Should I set each individual entry in the cache such as cache.set(primary_key, object)? Or should I convert it to a dictionary or something? -
How to create models in django with interrelationship between tables?
Most of the examples i googled were related to blogpost and i couldnt figure out how i could use django model/views(ORM) for practicing custom application. I have three tables:- user,license and common. Here is the use case i thought of mysql> describe user; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | userid | int(11) | NO | PRI | NULL | | | email | varchar(55) | NO | UNI | NULL | | | fname | varchar(22) | NO | | NULL | | | lname | varchar(22) | NO | | NULL | | +--------+-------------+------+-----+---------+-------+ mysql> describe license; +-----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+-------------+------+-----+---------+-------+ | licenseid | int(11) | NO | PRI | NULL | | | category | varchar(11) | NO | UNI | NULL | | +-----------+-------------+------+-----+---------+-------+ mysql> describe common; +-----------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+---------+------+-----+---------+-------+ | licenseId | int(11) | NO | | NULL | | | userId | int(11) | NO | | NULL | | The common table will store the userid and licenseid which will be … -
CSRF verification failed. Request aborted. Django 1.9
i'm just starting to implement post request on my project but i have trouble with the csrf token. Even if it seem i used it correctly (I use render, have cookie enable, {% csrf_token %} is in the html code and i have the middleware in django settings) view.py : form = mouvementForm(request.POST or None) if form.is_valid(): pont = form.cleaned_data['pont'] dateheure = form.cleaned_data['dateheure'] poid = form.cleaned_data['poid'] dsd = form.cleaned_data['dsd'] typepesee = form.cleaned_data['typepesee'] #Connection to 'erp-site' DB return render(request, 'mouvementCreation.html', locals()) template : <form name="Form1" method="post" action="" enctype="text/plain" id="Form1"> {% csrf_token %} <input type="text" id="Editbox9" style="position:absolute;left:87px;top:46px;width:86px;height:16px;line-height:16px;z-index:173;" name="pont" value="" spellcheck="false"> <input type="text" id="Editbox34" style="position:absolute;left:87px;top:80px;width:86px;height:16px;line-height:16px;z-index:174;" name="dateheure" value="" spellcheck="false"> <input type="text" id="Editbox35" style="position:absolute;left:87px;top:114px;width:87px;height:16px;line-height:16px;z-index:175;" name="poid" value="" spellcheck="false"> <input type="text" id="Editbox36" style="position:absolute;left:88px;top:153px;width:84px;height:16px;line-height:16px;z-index:176;" name="dsd" value="" spellcheck="false"> <input type="text" id="Editbox37" style="position:absolute;left:87px;top:187px;width:86px;height:16px;line-height:16px;z-index:177;" name="typepesee" value="" spellcheck="false"> <input type="submit" id="Button14" name="submit" value="Submit" style="position:absolute;left:361px;top:65px;width:96px;height:25px;z-index:178;"> </form> Middleware settings : MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] i have searched on multiple post and tried alot of fix but so far nothing worked and i'm still getting "Reason given for failure: CSRF token missing or incorrect." -
Django retrieve saved image as base64 string
I am trying to upload image to file system using python django as base64 string and retrieve the same as base64 string. in my model.py: Class Test(object): mission = models.TextField(blank=True) image = models.ImageField(upload_to='documents/images/',blank=True) account = models.OneToOneField(Account, related_name='account') def __str__(self): return '{}:{}'.format(self.mission, self.image) in my view.py def add_image(request, account): req = get_request_json(request) data = Test.objects.add_image(account, req) in my manager.py Class TestManager(models.Manager): def add_image(self, account, input): acc = self.get(account=account) format, imgstr = input_data.get('image').split(';base64,') ext = format.split('/')[-1] img = ContentFile(imgstr, name='temp.' + ext) acc.save() return acc; def get_doctor_profile(self, account): try: profile = self.get(account=account) except self.model.DoesNotExist: profile = [] except (MultipleObjectsReturned, ValueError, Exception) as e: profile = [] raise IndivoException(e) else: pass finally: return profile The path where the image is saved is added in the database but while returning the response I get the following error after saving and while using get TypeError: <ImageFieldFile: documents/images/temp_fRRD2oc.jpeg> is not JSON serializable. I think the error is in my models.py def __str__(self): but I am not aware of how to fix this. I need to return the saved image file as base64 string in the response. Can anyone point me in the right direction on how to fix this. -
Wagtail admin icons disappear when running collectstatic and putting everything on S3
I've been working locally and on my server and everything looks good. Then I configure django-storages to store static files and media on my S3 bucket. Everything works except for the icons/glyphicons on the admin interface. Instead of the nice pretty graphic icons, I see letters. For example once you log in, you have the search bar on the left side. Normally you would see a looking glass in the search box. I lost the looking glass and now I just see a lowercase f. My question is this. What do I search for to start debugging this? What wagtail file is collectstatic not collecting? Steps to Reproduce Set up a wagtail site Set up a bucket on s3 Install django-storages Configure django-storages to use your bucket ./manage.py collectstatic Technical details Python version: 3.5.2 Django version: 1.11.5 Wagtail version: 1.12.2 Browser version: firefox, chromium, chrome -
Input from is only 1 in html
Input from is only 1 in html.Im making Login form in index.html like <form class="my-form" action="{% url 'accounts:regist_save' %}" method="POST"> <div class="form-group"> <label for="id_username">Username</label> {{ form.username }} {{ form.username.errors }} </div> <div class="form-group"> <label for="id_email">Email</label> {{ form.email }} {{ form.email.errors }} </div> <div class="form-group"> <label class="control-label" for="id_password1">Password</label> {{ form.password1 }} {{ form.password1.errors }} </div> <div class="form-group"> <label class ="control-label" for="id_password2">Password(Conformation)</label> {{ form.password2 }} {{ form.password2.errors }} <p class="help-block">{{ form.password2.help_text }}</p> </div> <div class="form-group"> <div> <input type="submit" class="btn btn-default" value="SEND"> </div> </div> {% csrf_token %} </form> in forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' in urls.py like urlpatterns = [ url(r'^login/$', login,{'template_name': 'index.html'},name='login'), ] Only Username field is shown in browser, but others are not there.By using Google validation,only Username field has input tag, but others do not have.Why does it happen?How should i fix this? -
Django: how to use a template tag as an arguments for another template tag
I need to use a template tag inside another tag that is a custom tag and it gives me this error: Could not parse the remainder: '{{message.tags}}' from '{{message.tags}}' How can I fix this? TIA for any help! html: <div class="bootstrap-iso"> {% if messages %} <div class="messages "> {% for message in messages %} <div {% if message.tags %} class="alert {{ message.tags }} alert-dismissible" role="alert" {% endif %}> <strong> {% get_message_print_tag {{message.tags}} %}: </strong> {{ message }} <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> </div> {% endfor %} </div> {% endif %} </div> -
Unknown code being added to HTML template when running local server
I was building a profile picture feature, it was working fine so I left it for a while, probably a week. I came back to it and ran the local server, but when I do there's a few lines that appear in the console. But do not exist on the source file. Source file: <script type='text/javascript'> Dropzone.options.myDropzone = { autoProcessQueue : false, paramName: 'uploaded_image', dictDefaultMessage: "Drag and drop files or click here to upload picture", init: function() { var submitButton = document.querySelector("#submitBtn") myDropzone = this; submitButton.addEventListener("click", function() { myDropzone.processQueue(); }); // Automatically overwrites file so the user can only upload one this.on("addedfile", function() { document.getElementById('submitBtn').style.visibility = "visible"; }); this.on('addedfile', function(){ if (this.files[1]!=null){ this.removeFile(this.files[0]); } }); } }; </script> <!-- Modal --> <div id="picModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close"></span> <form action="{% url 'profile_test' %}" method='POST' enctype="multipart/form-data" class="dropzone" id="my-dropzone">{% csrf_token %} <!-- submit button stays hidden by default, until user selects a picture --> <button id='submitBtn' type='submit' class='pic-submit-button' style='visibility: hidden;'> Submit </button> <input id='submit-all' type='file' name='uploaded_image'/> {{form}} </form> </div> </div> Now the code I'm seeing when I run the server is only a few lines, and it's in the HTML that creates the modal: <!-- Modal --> <div … -
saving html content as json in django db
I'm using DJango to save some html designs in my db. For example here 'Body' has some html content: When I serialize the content into json, it seems like the html tags get eliminated: from django.core import serializers def list_templates(request): # retrieve all the templates from the DB all_templates = Template.objects.all() return HttpResponse(serializers.serialize('json', all_templates)) Here is what I see: Any recommendations on best practices for saving html codes and their serialization?