Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Previously Working Model Query Now Returns Nothing
In my Django project, an instance of a model is created in the first view. Then, in the second view, it is accessed and a couple of previously empty fields are updated. In the third view, I am attempting to run a docusign API using the information that is contained in the model instance. However, when I query for it the same way as I have in the second view, it returns 'None'. def firstView(request): if request.method=='POST' or request.method=='FILES': form = myObjForm(request.POST, request.FILES) newObj = myObj( phonenumber = request.POST.get('phonenumber')#There are several other fields that are occupied, but I pass the "phonenumber" between views to be able to retrieve the same instance between views ) newObj.save() return HttpResponseRedirect('pdf/{}'.format(newObj.phonenumber)) #Some other code def secondView(request, phone_number): myobj = myObj.objects.filter(phonenumber=phone_number).order_by('id').last() #pull the most recent instance. This does work. myObj.pdf = 'path/to/pdf.pdf' myObj.save() return HttpResponseRedirect('sign/{}'.format(phone_number)) def ThirdView(request, phone_number): myobj = myObj.objects.filter(phonenumber=phone_number).order_by('id').last() #This is where I get a 'None' type response. #Do some things with the model return HttpResponseRedirect('../success/') def success(request): return render(request, 'myapp/success.html') I would expect the query in ThirdView to return the same result it did in secondView. However, instead of returning the correct instance of the model, it returns 'None'. If I visit … -
Django, using sqlite for static content and postgresql for everything else
I would like to get some comments on whether this is a totally crazy idea or not. I have a django project running postgresql as its main database. This project has reports that have a lot of dynamic text content depending on values when the report is generated. I also have things like blog posts which are stored in this database. Currently, it's quite annoying when moving things from my dev envionment to production because it means I need to replicate what I have done in the dev database into the production database. I was wondering if I could use sqlite for this kind of static content only, like text, so things that are read only. I could then have this sqlite db under version control and use automatically transfer changes to production this way? So I would have postgresql as my main db and then sqlite as kind of a static only db for particular content. Thoughts? -
inject param to raw query python
When using (where user_id=1) I can get the result but when inject param I got traceback like this: 'User' object is not iterable, any ideas for inject param to raw query, my views.py: class TransactionViews(viewsets.ViewSet): def list(self, request): user = get_object_or_404(User, pk=request.user.id) queryset = Transaction.objects.raw("SELECT product.name, transaction.* from product inner join variant on product.id = variant.product_id inner join transactions_variants on variant.id = transactions_variants.variant_id inner join transaction on transactions_variants.transaction_id = transaction.id where user_id=%s",user) serializer = TransactionSerializer(queryset, many=True) return Response(serializer.data, status=200) one more question: queryset = Transaction.objects.filter(user_id=user).exclude(deleted_at__isnull=False) how can i convert this ".exclude(deleted_at__isnull=False)" into my raw query (this exclude is condition for soft delete) Traceback: File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/viewsets.py" in view 116. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in dispatch 495. response = self.handle_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception 455. self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py" in dispatch 492. response = handler(request, *args, **kwargs) File "/code/yashoes/transaction/views.py" in list 29. return Response(serializer.data, status=200) File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py" in data 765. ret = super(ListSerializer, self).data File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py" in data 262. self._data = self.to_representation(self.instance) File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py" in to_representation … -
Django update_or_create is too slow with ORM
I have a table named MyTable, that is saving IoT data id and time is unique together id | time | field1 | field2 | field3 django code: kwargs['id'] = 1 kwargs['time'] = '2018-01-01 00:00:00' update_kwargs[field1] = 12.34 instance, created = MyTable.objects.update_or_create(**kwargs, defaults=update_kwargs) My data soruce like streaming, field1 or field2 and field3 will one by one streaming in. but now, I got a large number flow have to update or create, almost every second have data streaming, that number is about 1,000,000 hr/row, the upsert not so fast I thought, how can I improve that? by the way, I use postgresql. -
How to override objects.get() method?
How to override Django's objects.get() method like this: def get(?): try: return super().get(?) except ObjectDoesNotExist: return None I will accept custom get method too (e.g. get_or_none()). -
view that adds object to m2m
I want to create a view that says "Are you sure you would like to [add object to m2m]" and when the user clicks OK, the view adds the object to the m2m and the user is redirected to the detailview from whence they originally came. A simple myobject.mym2m.add(user). the pk of myobject will ideally be in the url. I was originally going to make this an ajax api call and just redirect with javascript because I didn't know any other way, but that seems hacky, so I thought I'd ask here. How can I do this? Thanks in advance. -
How to convert SQL states below to Django ORM
Having difficult time to convert the SQL statements below to Django ORM. Any help is much appreciated. SELECT a.state, a.city, a.postcode, b.rate_authority, b.rate, b.rate_descr FROM fileload_taxratemodel AS a INNER JOIN fileload_taxrateresponsemodel AS b ON b.jurs_id_id = a.id ORDER BY state ASC Django Models: Trying to pull fields from both model based on the foreign key. class TaxRateModel(models.Model): company_code = models.CharField(max_length = 10) document_date = models.DateTimeField() country = models.CharField(max_length = 30, default = "US") province = models.CharField(max_length = 100, null= True,blank= True) state = models.CharField(max_length = 100) county = models.CharField(max_length = 100,blank=True, null=True) city = models.CharField(max_length = 100,blank=True, null=True) district = models.CharField(max_length = 100, blank=True, null=True) postcode = models.CharField(max_length = 5, blank=True, null=True) rate_code = models.CharField(max_length = 30,default = "ST") Django 2nd Model : class TaxRateResponseModel(models.Model): jurs_id = models.ForeignKey(TaxRateModel,on_delete=models.CASCADE,related_name='rates') rate_authority = models.CharField(max_length = 100, blank=True, null=True, default='') rate_descr = models.CharField(max_length = 100, blank=True, null=True, default ='') rate = models.DecimalField(max_digits= 10, decimal_places=5) -
Can I use Telethon with Django and how do I do it?
Can I use Telethon with Django and how do I do it? Some info will be really appreciated. How to pass the scrap results from Telethon on the template i know, but how do i write the script in views.py to can be able to get a channel info by example ? I know to connect it to API. Thanks ! -
Django-Jet "Page Not Found"
I am attempting to install the Django Jet dashboard, but I'm unable to get anywhere with it. I've followed the installation instructions, but no matter what I'm getting "Page Not Found" despite the URLs for Jet being listed. There are a handful of Issues opened on this, but none offer a solution outside that it was resolved in newer versions, and I am using the recommended commit (latest). Issues: https://github.com/geex-arts/django-jet/issues/289 https://github.com/geex-arts/django-jet/issues/62 Urls.py: from django.contrib import admin from django.urls import path, include, re_path from depot import views urlpatterns = [ path('', include('depot.urls')), path('', include('stores.urls')), path('admin/', admin.site.urls), re_path(r'^jet/', include(('jet.urls', 'jet'))), re_path(r'^jet/dashboard/', include(('jet.dashboard.urls', 'jet-dashboard'))), ] I have no custom overriding admin templates. I have tried just visiting /admin/, but my admin looks like the default Django Admin (someone mentioned its supposed to take over the original admin templates). Installed Apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'depot', 'stores', 'jet', 'jet.dashboard', ] I have also verified I have django.template.context_processors.request under Templates in my settings.py as well. -
Django API throwing a 403 error when called from Azure Functions
I have an instance of Azure Functions which is calling a particular endpoint of a Django API. The Django API doesn't need any authentication and I have used the @csrf_exempt annotator in the views.py file. It's a POST request which takes request parameters from the URL. When I call the end-point from Postman, it works fine but when the Azure Functions is making a HTTP Post call, the API throws a 403 Forbidden error. There is no explicit 403 error that is coded in the Django API. Logs on AppInsights suggest that log.py line 228 is throwing the error. From what I understand, the relevant log.py file is present in django/utils/log.py I am not able to figure out why there is a 403 error from the API. Any suggestions? -
Using Django, how can I avoid the duplicity of code when showing the details of a row inside a bootstrap modal?
I have a table where I show some item fields. When the user clics a button it opens a modal with all the item information. I'm using a "for loop" to get the rows but I noticed that it also creates a modal for each row. This is the line that includes the modal template: {% include 'item_detail.html' with pin=item.pin %} If I place the modal out of the "for loop" it loses context and doesn't show the item information. This is my for loop: <tbody class="items-table-body"> {% for item in items %} <tr scope="row"> <td>{{item.client_name}}</td> <td>{{item.title}}</td> <td>{{item.amount}}</td> <td>{{item.creation_date}}</td> <td>{{item.get_status_display}}</td> <td><button type="button" class="btn btn-sm btn-primary" name="button" data-toggle="modal" data-target="#itemDetailModal"> <span class="fa fa-eye"></span> </button> {% include 'item_detail.html' with pin=item.pin %} </td> </tr> {% empty %} <p>No items created</p> {% endfor %} This is a short version of my modal: <div class="modal fade" id="itemDetailModal" tabindex="-1" role="dialog" aria-labelledby="itemDetailModalTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> ... </div> <div class="modal-body"> ... </div> </div> </div> </div> -
(admin.E012) There are duplicate field(s) in 'fieldsets[0][1]' when using ManyToManyField
I upgraded from Django 1.10 to 1.11 and now two of my models which previously worked are causing errors. They are the only two models that have a ManyToManyField that includes a related_name attribute. I have another ManyToManyField without a related_name and it works fine. The error that gets thrown is misleading: <class 'hadotcom.admin.CaseStudyAdmin'>: (admin.E012) There are duplicate field(s) in 'fieldsets[0][1]' I've found other SO posts that reference that error and confirmed that none of them match my issue. If I comment out the entire line it passes the check. I tried adding a through attribute and that didn't help. Sample code (using Mezzanine): class CaseStudyPage(Page): industries = models.ManyToManyField("IndustryPage", blank=True, related_name="industry_set", through="CaseStudyIndustries") class CaseStudyAdmin(HaPageAdmin): inlines = (Foo, Bar,) Happy to fill in any blanks, and thanks in advance. -
How do I install the yaml package for my PyCharm Python project?
I'm using PyCharm 2018.2.4 with Python 3.7. I want to run some seed data so in the Python management console, I tried running my yaml file, which ended in this error manage.py@mainpage_project > loaddata seed_data bash -cl "/Users/davea/Documents/workspace/mainpage_project/venv/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py loaddata seed_data /Users/davea/Documents/workspace/mainpage_project" Tracking file by folder pattern: migrations /Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 52, in <module> run_command() File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/davea/Documents/workspace/mainpage_project/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata self.load_label(fixture_label) File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 165, in load_label ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore, File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/core/serializers/__init__.py", line 140, in deserialize return d(stream_or_string, … -
Django Signal pre_save methode
i have tree table ( User , Company , Role ) class Company_Model ( models.Model ): company_Owner = models.ForeignKey ( User,on_delete = models.CASCADE) company_name = models.CharField ( max_length = 100,) class Roles_Model ( models.Model ): roles_user = models.ForeignKey ( User,on_delete = models.CASCADE ) roles_company = models.ForeignKey ( Company_Model,on_delete = models.CASCADE,null = True ) ============================================================================= so what i need is : whene the user is created i need to catch the id of user and create in Company table [ company_owner = user_id ] and in role table [ roles_user = user_id , roles_company = user_id ] -
django-sorcery isn't autogenerating migrations
I'm playing around with the django-sorcery library, and I've been trying to generate some migrations: django-admin sorcery revision -m "Second revision" --autogenerate -v 1 my_app When I first ran the command, I saw an error message: FileNotFoundError: [Errno 2] No such file or directory: [... snip ...]python3.7/site-packages/django_sorcery/db/alembic/script.py.mako Not sure why the template is missing from the pip package, I added it back in by hand. Now, the command just generates empty migration files, even though I specify the --autogenerate flag. Should I be throwing an env.py file somewhere? is this command actually supposed to work yet? Help appreciated. -
Django TestCase on form validation fails even tough input is valid
As in the title described I've got a form which validates correctly when I am using the FormView. However as I started writting tests today the same input fails in the TestCase and I get the following error: {'programming_language': ['Select a valid choice. That choice is not one of the available choices.']} These are the models, forms, views and the test I am using # models.py from django.db import models class Tag(models.Model): name = models.CharField(max_length=40, unique=True) class ProgrammingLanguage(models.Model): name = models.CharField(max_length=40, unique=True) class Snippet(models.Model): title = models.CharField(max_length=40) programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) explanation = models.TextField() code = models.TextField() tags = models.ManyToManyField(Tag) # forms.py from django import forms from django.utils.translation import gettext_lazy as _ from .models import Snippet class SnippetForm(forms.ModelForm): class Meta: model = Snippet exclude = ["creation_date"] # views.py from django.urls import reverse_lazy from django.views import generic from .models import Snippet from .forms import SnippetForm class SnippetFormView(generic.FormView): template_name = "snippets/snippet_form.html" form_class = SnippetForm success_url = reverse_lazy("snippets") def form_valid(self, form): # for testing purposes print(form.cleaned_data) form.save() return super().form_valid(form) # test_forms.py from django.test import TestCase from snippets.forms import SnippetForm from snippets.models import ProgrammingLanguage, Tag, Snippet class SnippetFormTestCase(TestCase): @classmethod def setUpTestData(cls): ProgrammingLanguage.objects.create(name="Javascript") Tag.objects.create(name="website") def test_forms(self): form = SnippetForm({ 'title': 'Test snippet … -
Django - Users inconsistently registered to Admin
This is the default User model, nothing custom, no modifications to Auth in any way. Depot/Admin.py import depot.models as models from django.contrib import admin from django.db.models.base import ModelBase from django.contrib.auth.models import User admin.site.site_header = "DSG IT Database" for model_name in dir(models): model = getattr(models, model_name) if isinstance(model, ModelBase): if model in admin.site._registry: admin.site.unregister(model) else: admin.site.register(model) Stores/Admin.py import stores.models as models from django.contrib import admin from django.db.models.base import ModelBase from django.contrib.auth.models import User admin.site.site_header = "DSG IT Database" for model_name in dir(models): model = getattr(models, model_name) if isinstance(model, ModelBase): if model in admin.site._registry: admin.site.unregister(model) else: admin.site.register(model) I do understand these are sort of redundant, but that isn't the problem because this was an issue when this was a single application project as well. What is happening is that Users is just completely missing from the admin site. I can register it again with admin.site.register(User), but then later down the road (seemingly randomly) I'll get an error that User is already registered. Then I unregister the model, and it'll work for a while then at some point Users will just disappear again and the only way to make it work again is by registering it again. I can't find where I need … -
PhantomJS bot and Django: cannot send a cookie
I am trying to implement a stored XSS CTF challenge. I have the instructions from this blog How to add an XSSable bot to your CTF However, I cannot send any cookie data with the phantom.addcookie(). I use the Django framework to develop the web application. This is my bot.js which uses the PhantomJS -based on the instructions from the blog I have already referred to: var page = require('webpage').create(); var host = "127.0.0.1:8000"; var url = "http://"+host+"/posts/; var timeout = 2000; phantom.addCookie({ 'name': 'Flag', 'value': 'CTF{44dc13922a2f0f7a59c5058703fae0b9}', 'domain': host, 'path': '/', 'httponly': false }); page.onNavigationRequested = function(url, type, willNavigate, main) { console.log("[URL] URL="+url); }; page.settings.resourceTimeout = timeout; page.onResourceTimeout = function(e) { setTimeout(function(){ console.log("[INFO] Timeout") phantom.exit(); }, 1); }; page.open(url, function(status) { console.log("[INFO] rendered page"); setTimeout(function(){ phantom.exit(); }, 1); }); My templates in connection visited by the bot are the following: post_list.html: {% extends "posts/post_base.html" %} {% load humanize %} {% block pre_post_content %} <div class="col-md-4"> {% if request.user.is_authenticated %} <div class="card card-with-shadow"> <div class="content"> <h5 class="title">Your Groups</h5> <ul class="list-unstyled"> {% for member_group in get_user_groups %} <li class="group li-with-bullet"> <a href="{% url 'groups:single' slug=member_group.group.slug %}"> {{ member_group.group.name }}</a> </li> {% endfor %} </ul> </div> </div> {% endif %} <div class="card card-with-shadow"> … -
How does the python module system work in django/salt
I am trying to understand certain aspects of the Python module system, but there are certain aspects I just can't seem to grasp. I'll use saltstack as an example. When you look at the file https://github.com/saltstack/salt/blob/develop/salt/minion.py#L30 they'll have this: from salt.utils.zeromq import zmq, ZMQDefaultLoop, install_zmq, ZMQ_VERSION_INFO This absolute import is part of the salt folder; I just don't understand why this works. When I try something like this locally, I'll get a ModuleNotFoundError. Can someone perhaps push me into the right path? Thank you very much! -
What are some Django best practice for creating objects to test on
The way I've been testing on code that requires a temporary Object to be created seems messy. I am hoping there is a cleaner and more intuitive way of doing it. On setup, I run a function setUpTestData that is in charge of creating temporary Objects that my tests may use later on. This has become a bit cluttered with the nested Objects I am having to create within it due to ForeignKey relationships. Here's an example of what I am working with: class Test_query_alarm(TestCase): @classmethod def setUpTestData(cls): Device.objects.create( site=Site.objects.create( group=Group.objects.create( name='TestGroup' ), name='TestSiteName', address='TestAddress', gps_coordinates='TestGpsCoordinates', contact=Contact.objects.create( first_name='TestFirstName', last_name='TestLastName', phone='TestPhoneNumber', email='test@gmail.com' ) ), ip_address='ip-here', snmp_port_number='port-here', http_port_number='port-here', location='Houston', snmp_version='SNMPV2', type='Modem', manufacturer='Commscope' ) As you can see, I am generating the Device object. But it's also requiring three other objects to be created alongside it. Is there any advice someone can give me here, whether it be database design, test design, or something else. -
Annotate Django queryset with a datetime
So, I have a queryset that I need to annotate with some additional fields, including integers, booleans, and datetimes. Something like this: def get_appointments_with_overrides(override_price, override_start_time, override_advance_booking_needed): return (Appointments.objects.annotate(override_price=Value(override_price, IntegerField())). annotate(override_start_time=Value(override_start_time, DateTimeField())). annotate(override_advance_booking_needed=Value(override_advance_booking_needed, BooleanField()))) Where override_price etc. are all properties (but not Django fields) in the Appointments model. When I try to use this (specifically, when I call first() or last() on the annotated queryset), I get the following error. AttributeError: 'DateTimeField' object has no attribute 'model' If I remove the datetime annotation, I don’t get any errors and the other two annotations work exactly as I expect them to. So what, if anything, am I doing wrong with this datetime annotation? -
Django, Nginx random 403/404 errors and redirect spam with HTTPS
I recently set up a Django web app using uWSGI, Nginx and Celery. All seemed to go well until I installed a Let's Encrypt certificate. My app SafeSpreadsheets will randomly throw a 403 error on the home page, and when I manually type in the login page location, will give a 404 error. On different systems (sometimes different browsers on the same system) the website might not load all the static files. Other times it will work 100% without an issue. I also tested whether the https redirect works on all my URLs (my Django and Nginx settings should force the redirect)but when I do, I can see the browser redirecting to iyfipun.com which is a known spam URL. The 403/404 errors don't show up in my logs (weirdly) and I don't get any admin/manager notifications from Django. My Nginx site configuration is as follows: server { server_name safespreadsheets.com www.safespreadsheets.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/xxx/yyy; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/yyy.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/safespreadsheets.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/safespreadsheets.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; … -
Django custom page based CMS
I am searching for django CMS that allows me to create something like custom pages build from predefined components. Every page should be builded from custom "inpage" components like: carousel with images gallery with images richtext field plain text field So as a developer I will build a template for every page of a website from this components and assing a CSS file for the given page. For example one page can look like: plain text field (heading) plain text field (some kind of page abstract) richtext field (part of the text) gallery with images (few specified images with some style) richtext field (another part of the text) Another page could be build in a different way. The key idea is, that every page will have predefined unique layout (template) that is not breakable by users in CMS. The CMS I would like to use, should allow the user to change content of the particular componets for particular page. So the CMS should create form to change the content of the particular components for a given page (heading, text, images in carousel). The changable content of the page (form fields) can be stored in database of files, it does not … -
Dynamically replace all urls to full absolute url in template
I have a template which I am going to send as an email. Thus I need to have absolute full urls (along with protocol and domain name) instead of relative ones. The content in the email is going to come dynamically from database (entered using ckeditor, so I CAN NOT do something like {{ protocol }}{{ domain_name }}{% static '' %}. This would work only for static files. However the media content uploaded via ckeditor will recide in media files and I have absolutely no control over it. Also i cant use javascript as it is an email template. Currently I have built a python function which scans the entire template after rendering and prepends the protocol and domain name to every src attribute in img tag and all href attributes. I would like to know if any better way exists -
I have a select list and I need to remake it on button group
I need to remake a select form to button group without loss of functionality. I surf all Net but I can't find solution. I can't do this without loss of functionality. <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to }}"> <select name="language"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> From: To: