Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django crispy forms does not render css
I am trying to use django crsipy forms to render a really really simple form. Fiddling around for hours now but don't get it rendered using bootstrap (or for the sake of it any css-template). As I am just starting to get a grasp of Django in general I might miss anything substantial. I do not get any errors. Here is how i installed and setup the packages: Installed django-crispy-forms and django-bootstrap3 via pip. Both are listed under INSTALLED_APPS in settings.py CRISPY_TEMPLATE_PACK is set to 'bootstrap3' If I understood it correctly - thanks to the django-bootstrap3 package - I do not have to add any static files to my app nor do I have to load them in the template. Here is my models.py from django.db import models class Crispy_test(models.Model): pnumber = models.CharField("Projectnumber", max_length=5, unique = True) client = models.CharField("Client", max_length=20) pname = models.CharField("Projectname", max_length=40) status = models.CharField(max_length=20) forms.py from django import forms from .models import Crispy_test class Crispy_testForm(forms.ModelForm): class Meta: model = Crispy_test fields = ['pnumber', 'client', 'pname', 'status'] views.py from django.shortcuts import render, HttpResponseRedirect from .forms import ProjectForm, Crispy_testForm def index(request): if request.method == 'POST': form = Crispy_testForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('success') else: form = Crispy_testForm() return … -
Generate a One-Time URL with Apache and Django
It is pretty much the same as the following thread except that in my case, I'm using Python and Apache, and the use of databases (for storing UUIDs, creation and expiration timestamp) is recommended: Generate ip and time limited download link -
django-settings-export not showing on every page
I downloaded the django-settings-export https://github.com/jkbrzt/django-settings-export and followed the directions to get constants showing easily. I have a base.html file that holds my header banner, nav bar and footer banner. I have put the header and footer constants in the base.html file and it shows perfectly when the site is first loaded, however, if I navigate to a different page, which extends the base.html page, the settings constant text disappears. Any idea why this would be happening? Thanks much in advance! -
Match dictionary key to database to update with value
I have a points model for users that references certain categories through which users can earn points. I am trying to use a dictionary to update values (referral_score) that match keys (points_category) in a dictionary, d Users.models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=32, null=True, blank=True) class UserPoint(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='task_score') points_amount = models.FloatField(default=0.0, null=True, blank=True) referral_score = models.FloatField(default=0.0, null=True, blank=True) points_category = models.ForeignKey('categories.Task', on_delete=models.CASCADE) I want to update each user's referral score using a dictionary that I have successfully created that compiles their referral scores like so: {'points_category': referral_score}. I create the dictionary through a function that looks at all their referrals and compiles a score for each category. Example: d = {'apples':100.0, 'oranges':150.0, 'bananas': 200.0} Is it possible to use this dictionary to update their referral score? If they do not have a current score for a particular points_category, I would like to create a new entry with referral_score equal to the value in the dictionary that matches the points_category key. If they already have a matching points_category, I would like to update it to reflect the new value from the dictionary. I have tried using setattr from a previous answer but whereas they are trying to … -
Building a list from inheriting models
I have been trying to solve this in the most Pythonic way but have let to get this working in a few lines of code. Essentially I have 3 models: Model 1 -- foreign key -- > Model 2 -- foreign key -- > Model 3 From these, I would like to create a single object list that works like the following: Model 1a - Model 2a -- Model 3a -- Model 3b - Model 2b -- Model 3c Model 1b - Model 2c ... etc Essentially the object list should have the name of that model, a URL that takes it to the respective page (depending on which model it relates to: 1 2 or 3) and keep the order. Is there a best practice way to build these lists of objects that inherit from one another? I have created a dictionary and have 4 loops within each other than handle this nut don't believe this is very effective. -
Email as Username in an existing django app
I created an app where I used to require an email and a username for signup. Now I would like to change this so that any existing users have their username changed to their email. Any new users will not see the username field upon signup, but in the backend they'd be the same. I was thinking that I could just set the max_length to the length of email? Then in the backend, I could just set the username to the email when the user signs up. What am I missing here? -
NetworkError: Failed to execute 'send' on XMLHttpRequest': Failed to load
Server side is Django/python. Client environment is cordova/android. This request fails : $.ajax({ url: myAddress, type: 'POST', data: mydata, crossDomain: true, processData: false, contentType: false, async: false, success: function () { mycode}, error: function (xhr) { mycode} } }); When myAddress is 192.168.1.11 it works perfectly. When myAddress is dev.mysite.com i get the error: NetworkError: Failed to execute 'send' on XMLHttpRequest': Failed to load dev.mysite.com/../.. However, i can connect to the same django web server with chrome on the mobile device. config.xml contains : access origin="*" Do you have an idea to solve this problem? -
Exception errors while installing Django and virtualenvwrapper-win for python 3.6 on windows 10
I have installed python 3.6 and want to install Django. Earlier i was getting Exception error while installing virtualenvwrapper-win but after uninstalling and installing many times that error has gone now.(Don't know how it has gone) after installing virtualenvwrapper when i wrote mkvirtualenv myproject I got this error " 'virtualenv.exe' is not recognized as an internal or external command, operable program or batch file." After this I tried to install Django pip install django and I got this error:- C:\Users\Ali Abbas.Lenovo-PC>pip install django Collecting django Using cached Django-1.10.2-py2.py3-none-any.whl Installing collected packages: django Exception: Traceback (most recent call last): File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 317, in run prefix=options.prefix_path, File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 742, in install **kwargs File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 831, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files isolated=self.isolated, File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip\wheel.py", line 493, in move_wheel_files maker.make_multiple(['%s = %s' % kv for kv in console.items()]) File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip_vendor\distlib\scripts.py", line 383, in make_multiple filenames.extend(self.make(specification, options)) File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip_vendor\distlib\scripts.py", line 372, in make self._make_script(entry, filenames, options=options) File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip_vendor\distlib\scripts.py", line 276, in _make_script self._write_script(scriptnames, shebang, script, filenames, ext) File "c:\users\ali abbas.lenovo-pc\appdata\local\programs\python\python36\lib\site-packages\pip_vendor\distlib\scripts.py", line 212, in _write_script launcher = self._get_launcher('t') … -
sending the value of HTML checkbox to django view
I have the following HTML page <input type="checkbox" name="checks[]" value="1">REG_AGREED_SUITE01 </label> <hr> <label class="checkbox"> <input type="checkbox" name="checks[]" value="2">REG_AGREED_SUITE02 </label> <hr> <label class="checkbox"> <input type="checkbox" name="checks[]" value="3">REG_AGREED_SUITE03 </label> I have a Django view like this cd1 = "<command>" cd2 = "</command>" test_runner_path = "Abc - C:\git_new\evo_automation\ tests\TestRunner" test_runner_path2 = "Def - C:\git_new\evo_automation\ tests\TestRunner" STB = "VMS_01" TestSuite = "REG_AGREED_SUITE02" report_location = "C:\git_new\evo_automation\ tests\TestRunner\ReportFile C:\git_new\evo_automation\ reports" j = jenkins.Jenkins('http://localhost:8080', 'jenkins', 'jenkins123') mycommand1 = cd1 + test_runner_path + "\n" + STB + "\n" + TestSuite + "\nTrue \n" + report_location + cd2 mycommand2 = cd1 + test_runner_path2 + "\n" + STB + "\n" + TestSuite + "\nTrue \n" + report_location + cd2 mycommand3 = cd1 + "super" + cd2 # print mycommand # Getting the list of plugins info = j.run_script("println(Jenkins.instance.pluginManager.plugins)") # print(info) jobConfig = j.get_job_config('sample') tree = ET.XML(jobConfig) with open("temp.xml", "w") as f: f.write(ET.tostring(tree)) document = parse('temp.xml') actors = document.getElementsByTagName("command") for act in actors: for node in act.childNodes: if node.nodeType == node.TEXT_NODE: r = "{}".format(node.data) print r prev_command = cd1 + r + cd2 print prev_command # print(jobConfig) shellCommand = jobConfig.replace(prev_command, mycommand1) j.reconfig_job('sample', shellCommand) # print(jobConfig) # Build 'sample' jobq j.build_job('sample') Right now I am passing TestSuite value manually from views. But … -
Django - Variable not being set properly
So I am trying to run my users input through if elif statements in some arrays I setup. The goal is to have the variable set to a value if the input is found in the array. Right now the values are staying None. I am sure this is something silly that I am missing on my part, but any help would be greatly appreciated. views.py def fit_guide(request): if request.method == 'POST': form = FitGuideSizingForm(request.POST) chest = request.POST['chest'] waist = request.POST['waist'] hip = request.POST['hip'] if form.is_valid(): chest_size = None if chest in chest_size_0(): chest_size = 0 elif chest in chest_size_2(): chest_size = 2 elif chest in chest_size_4(): chest_size = 4 elif chest in chest_size_6(): chest_size = 6 elif chest in chest_size_8(): chest_size = 8 elif chest in chest_size_10(): chest_size = 10 elif chest in chest_size_12(): chest_size = 12 elif chest in chest_size_14(): chest_size = 14 elif chest in chest_size_16(): chest_size = 16 elif chest in chest_size_18(): chest_size = 18 elif chest in chest_size_20(): chest_size = 20 elif chest in chest_size_22(): chest_size = 22 elif chest in chest_size_24(): chest_size = 24 elif chest in chest_size_26(): chest_size = 26 elif chest in chest_size_28(): chest_size = 28 print(chest_size) form = FitGuideSizingForm() c = … -
Can't access model from another django app duration migration
My migration with custom logic attempts to useModel3 from otherapp but it fails with LookupError: App 'otherapp' doesn't have a 'model3' model. Model3 is not a new model, it's been in use for a while and I can access other models in otherapp during my migration. from __future__ import unicode_literals from django.db import migrations def update_items(apps, schema_editor): # apps shows references to models in 'otherapp' # This prints Model1, Model2 but is missing Model3 print apps.all_models['otherapp'].keys() # This works OtherAppModel1 = apps.get_model('otherapp', 'Model1') # This fails: LookupError: App 'otherapp' doesn't have a 'model3' model. OtherAppModel3 = apps.get_model('otherapp', 'Model3') # This works but should not be done in a migration from otherapp.models import Model3 class Migration(migrations.Migration): dependencies = [ ('thisapp', '0102_foo'), ] operations = [ migrations.RunPython(update_items) ] -
django 1.10 get individual objects out of query
I have a model set up for subscribers to get on our mailing list. Whenever a new blog post is created I want to email the user. How do I get individual email addresses and first names from the model to use to email, each person individually? I want their first name to be in the email. Here is my models.py: class EmailUpdates(models.Model): email = models.EmailField(max_length=100, blank=True, unique=True) first_name = models.CharField(max_length=100, blank=True) def __str__(self): return self.email def __unicode__(self): return self.email Here is my views.py: def post_create(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404() notification_subscribers = EmailUpdates.objects.all() form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() messages.success(request, "Successfully Created") for user in notification_subscribers: user.first_name = notification_subscribers.filter('first_name') user.email = notification_subscribers.filter('email') user_data = { 'user_email': user.email, 'user_first_name': user.first_name, } plaintext = get_template('email/post_create_email/email_text.txt') htmly = get_template('email/post_create_email/email_template.html') text_content = plaintext.render(user_data) html_content = htmly.render(user_data) subject = "{0}, a new blog post has been made, Hurray!".format(user.first_name) from_email = 'xx@gmail.com' to_email = user.email msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email]) msg.attach_alternative(html_content, "text/html") msg.send() return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, } return render(request, "posts/post_form.html", context) -
django ListView, CategoryListview in blog_post.html
iam new to django and started a blog app, everything works fine so far. No I have a question. I started to put the blogposts in categories and let them show in a extra url pattern categories. Now my question is: Is there a way that i can show my CategoryListView in the blog_post_list.html / blog_postListView . I tried it with the include tag {% include 'blog/category_list.html' %}. But it doesnt work like this, there i get shown in the blog_post_list.html just all post titles but NOT the categories. In summary i just want to show a list of the categories in the homepage as a widget. Thanks a lot. I hope it wasnt that confused what I wrote main url from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from blog.views import AboutPageView, ContactPageView, blog_postCreateView urlpatterns = [ url(r'^about/', AboutPageView.as_view(), name='about'), url(r'^contact/', ContactPageView.as_view(), name='contact'), url(r'^create/', blog_postCreateView.as_view(), name='blog_post_create'), url(r'^categories/', include('blog.urls_categories')), #url(r'', include('blog.urls')), url(r'^blog/', include('blog.urls')), #admin and login url(r'^admin/', admin.site.urls), url(r'^accounts/', include('registration.backends.default.urls')), url(r'', include('blog.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) url categories from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import … -
Django server killed frequently
I'm developing a Django project and testing it on a dedicated server. The project is running on: django 1.9.6 virtualenv python 2.7 cx_Oracle 5.2.1 Running python manage.py runserver 192.168.30.17:8080 & all goes well. Project running and with ps aux I get, for example: root 8437 0.0 0.9 461108 39036 pts/0 S 15:17 0:00 python manage.py runserver 192.168.30.17:8080 root 8861 3.5 1.5 1319364 64232 pts/0 Sl 15:24 0:14 /new_esmart/esmart_env/bin/python manage.py runserver 192.168.30.17:8080 THE PROBLEM: Frequently server goes down with no error showed on shell. I simply receive: Killed How can I retrieve more information to find the cause of this killing? -
Django ImportError: No module named although it is already in my python search path
I am solving this for quite a long time already. I print like this. python2.7 -c "import sys; print sys.path" And I saw my module directly there. ['', '/home/khantthulinn/lib/python2.7/pip-8.1.2-py2.7.egg', '/home/khantthulinn/lib/python2.7', '/home/khantthulinn/lib/python2.7', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/home/khantthulinn/.local/lib/python2.7/site-packages', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/PIL', '/usr/lib64/python2.7/site-packages/geos', '/usr/lib/python2.7/site-packages'] But I always get this error. How shall I solve? Unhandled exception in thread started by Traceback (most recent call last): File "/home/khantthulinn/webapps/mmspeaker/lib/python2.7/Django-1.8.14-py2.7.egg/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/home/khantthulinn/webapps/mmspeaker/lib/python2.7/Django-1.8.14-py2.7.egg/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/home/khantthulinn/webapps/mmspeaker/lib/python2.7/Django-1.8.14-py2.7.egg/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/home/khantthulinn/webapps/mmspeaker/lib/python2.7/Django-1.8.14-py2.7.egg/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/home/khantthulinn/webapps/mmspeaker/lib/python2.7/Django-1.8.14-py2.7.egg/django/init.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/khantthulinn/webapps/mmspeaker/lib/python2.7/Django-1.8.14-py2.7.egg/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/khantthulinn/webapps/mmspeaker/lib/python2.7/Django-1.8.14-py2.7.egg/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/lib64/python2.7/importlib/init.py", line 37, in import_module import(name) ImportError: No module named push_notifications -
Django in sub-directory
When i build my django application, i'll use the runserver command in order to test my website, but in deploy, let's say that i'll publish my website under: www.test.com/django. My IIS it's configure with an application under my default website called "django". I'm expecting that everything will works fine, but django doesn't recognize my url schema, that is the following one: urlpatterns = [ # Examples: url(r'^$', app.views.home, name='home'), url(r'^contact$', app.views.contact, name='contact'), url(r'^about', app.views.about, name='about'), ] and in this case, i need to modify my urlpatterns like this, in order to serve the application via www.test.com/django: urlpatterns = [ url(r'^(?i)django/', include([ #Application name # Examples: url(r'^$', app.views.home, name='home'), url(r'^contact$', app.views.contact, name='contact'), url(r'^about', app.views.about, name='about'), ])), ] It's a good approach? it's working but i'm not sure about the quality of this solution. -
how i can go in admin panel is it possible when use sqlite
I try to go in http://127.0.0.1:8000/admin but i dont have idea about user pass, during python manage.py migrate didnot ask about new user so how i can do that DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.DEC_DB'), } -
Restrict Django Rest Framework for all users except super users
Can I restrict my Django Rest Framework to be only accessed by super users? Can I add a decorator to the urls so that the url is only accessed by super users: url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), -
django 1.10 cycle to add hr tag every 4th element
I want to add an hr element every 4th child element in my html doc. This is what I have so far: <div class="row blog-post"> {% for obj in object_list %} <div class="col-sm-3"> <div class="thumbnail"> {% if obj.image %} <img src="{{ obj.image.url }}" class="img-responsive"/> {% endif %} <div class="caption post-detail-item"> {% if obj.draft %}<h3>Staff only: <span style="color:red;">Draft</span></h3> {% endif %} {% if obj.publish > today %}<h3>Staff only: <span style="color:red;">Future Post</span></h3>{% endif %} <h3><a href='{{ obj.get_absolute_url }}'>{{ obj.title }}</a><small> {{ obj.publish|timesince }}</small></h3> {% if obj.user.get_full_name %} <p>Author: {{ obj.user.get_full_name }}</p> {% endif %} {{ obj.get_markdown|truncatechars_html:350 }} <p><a href="{{ obj.get_absolute_url }}" class="btn btn-primary" type="button">View</a></p> </div> </div> </div> {% cycle "" "<div class='col-sm-12'><hr/></div></div><div></div><div class='row'>" %} {% endfor %} </div> The cycle bit I have there works to separate every second element, but I want it to be every 4th. Without it, I get 4 elements per line. This is what I want. Basically, I'm trying to make a standard height per column. -
Django Form Error: 'QueryDict' object has no attribute 'method' when POST assigned
I'm having trouble with a specific form that is not permitting me to post data to a function I've defined. I'm very confused as to why this is giving me errors because I use an almost identical form to do another action in the same website. When I post this data, Django throws "'QueryDict' object has no attribute 'method'" even though I've assigned the method as POST. It renders the form just fine when it's not posting, it's only when I submit I have a problem.\ The error that Django throws points to this line in views: if request.method == "POST": this is the first line in the "cancel" function below. Can anyone identify what I've done wrong here? I'm at a loss. Here's the function in view.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.shortcuts import redirect from .apps.instant import orderlist, orderdetails, cancel from .forms import cancelorder def cancel(request): if request.method == "POST": form = cancel(request.POST or None) if form.is_valid(): response = cancel(request.session['token'],form.cleaned_data['orderId'], form.cleaned_data['reason']) return render(request, 'instant/review.html', {'data':response}) else: form = cancelorder() return render(request, 'instant/cancel.html', {'form':form}) else: form = cancelorder() return render(request, 'instant/cancel.html', {'form':form}) here's the forms.py: from django import forms class cancelorder(forms.Form): orderId = forms.CharField(label='Order Id', … -
Get objects which have NO relation to the current object
I am currently workong on an update for a X-Y matrix of subscribers (customers) on different products. Originally it's a matrix containing approx. 500 customers and 24 products. To speed up the rendering, we implemented some filtering methods (A-Z / buisness type filtering, valid/expired, etc). Another request was to be able to filter on customers which have no subscriptions at all, like Customer C and D in the table below. | | subsc A | subsc B | subsc C | subsc D | subsc E | |-----------|---------|---------|---------|---------|---------| |customer A | valid | - | - | expired | - | |customer B | - | ended | - | valid | - | |customer C | - | - | - | - | - | |customer D | - | - | - | - | - | |customer E | expired | - | valid | - | - | The subscription table has looks like the following (simplified): class Subscription(models.Model): product = models.ForeignKey(Product) customer = models.ForeignKey(Customer) startDate = models.DateField(default=datetime.date.today) endDate = models.DateField() blank=True, null=True) ended = models.BooleanField(default=False) Is there any django-magic to get the list of customers who have NO subscription listed? If not, any suggestions … -
Creating an object with more than 1 foreign key in a Django project with multiple databases causing error
In my Django project, I have 2 databases. Everything works perfectly except for when I try to create a model with 2 foreign keys. The database router locks up and gives me a Cannot assign "<FKObject: fk_object2>": the current database router prevents this relation. even if both foreign keys come from the same database and I've yet to save the object in question. Code below 1 fk_object1 = FKObject.objects.using("database2").get(pk=1) 2 fk_object2 = FKObject.objects.using("database2").get(pk=2) 3 4 object = Object() 5 object.fk_object1 = fk_object1 6 object.fk_object2 2 = fk_object2 7 object.save(using="database2") The problem arises on line 6, before the object is even saved into the database so I'm assuming that Django somehow calls Object() with database1 even though it hasn't been specified yet. Does anyone know how to deal with this? -
The way to write <a href=""> on Django
I haven't used Django for a while, so I forgot many things of Django. When I click url link on this site, it moves to another pages, but the pages don't work properly. But if I reload the page or retype the same url, the pages work. I wrote like these, <a href="{% url 'slideup_like_magic' %}">slideUp header</a> or <a href="/carousel/">carousel</a> I read several pages, but I don't know what to do. Would you please help me? index.html {% load staticfiles %} <!DOCTYPE html> <html lang="en-EN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- for IE --> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0"> <title>Welcome to my Samples!</title> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css"> <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" /> <style type="text/css"></style> </head> <body> <div> <span>Welcome to my samples!!</span> <dl> <dt>Bootstrap</dt> <dd><a href="{% url 'affix' %}">affix</a></dd> <dd><a href="/carousel/">carousel</a></dd> <dt>BxSlider</dt> <dd><a href="/bxslider/">responsive</a></dd> <dt>Magic</dt> <dd><a href="{% url 'slideup_like_magic' %}">slideUp header</a></dd> </dl> </div> <!-- JavaScript --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js" type="text/javascript" ></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js type="text/javascript" ></script> <![endif]--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script> <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script type="text/javascript"></script> </body> </html> url.py from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() import hello.views # Examples: # url(r'^$', 'gettingstarted.views.home', name='home'), # url(r'^blog/', include('blog.urls')), urlpatterns = [ url(r'^$', hello.views.index, name='index'), url(r'^bxslider/$', hello.views.bxslider, name='bxslider'), … -
Python/Django: how exactly works the ugettext_lazy function with operator %?
I am using python 2.7 and had issue with lines like: LOG.warning(_("text")) This won't work as LOG.warning is expecting a string (str) and ugettext_lazy only knows how to render unicode. Now the solution I found was to force unicode rendering before calling the logger: text = 'Test trans' LOG.warning(u"%s" % _(text)) However, I was surprised to noticed that theses code also work: LOG.warning(_(Test trans %(test)s.') % {'test': 1}) LOG.warning(_('Test trans %s.') % 1) Can somebody explain why ? Does the "%" operator calls for unicode rendering before replacing the variable ? Thanks in advance. -
Can't add css class to some form fieds
maybe it is just a bug or well known feature, but didn't found anything with google. Snippet from a form(RegisterForm for django-registration): widgets = { 'username': HiddenInput(), 'email': EmailInput(attrs={'class': "form-control"}), 'password1': PasswordInput(attrs={'class': "form-control"}), 'password2': PasswordInput(attrs={'class': "form-control"}), 'first_name': TextInput(attrs={'class': "form-control"}), 'last_name': TextInput(attrs={'class': "form-control"}), } Snippet from template: <div class="container"> {{ form.non_field_errors }} <form method="post"> {% csrf_token %} {% for field in form %} {% if field.name != 'username' %} <div class="form-group row {% if field.errors %}has-danger{% endif %}"> {% if field.errors %} <div class="form-control-feedback">{{ field.errors.as_text }}</div> {% endif %} <label for="{{ field.id_for_label }}" class="col-form-label col-xs-2">{{ field.label }}</label> <div class="col-sm-10"> {{ field }} </div> </div> {% endif %} {% endfor %} <div class="form-group row"> <div class="offset-sm-2 col-sm-10"> <button type="submit" class="btn btn-primary">Register</button> </div> </div> </form> No rocket science at all. Passwords and email do not get the css class, but textfields! Am i missing something?