Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Generate same text with and without HTML tags?
I am working in Django 1.9. I would like to generate a couple of sentences in a template to use both in the front-end of the app, and in the meta description tag. In the template, I would like it to include links: <p><a href="{{ object.get_absolute_url}}">{{ object.name }}</a> blah blah...</p> But in the meta description, I obviously don't want to include those links - I just need it to be plain text (but the same content): {% block page_description %}{{ object.name }}</a> blah blah{% endblock page_description %} Ideally I would use a template tag to include the same sentence in both places in the template, but how can I generate one version without links and one with, in a DRY way? -
glyphicon is not displayed at all
I'm trying to build a web page. After I added the first glyphicon it worked just fine, but then I tried to add another one in order to enable to delete things for the user. But second glyphicon is not displayed. I do not understand why this happens. {% load staticfiles %} <html> <head class="page-header"> <title>WebPage</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'static/css/Auswertung_app.css' %}"> </head> <body> <div class="page-header"> <a href="{% url 'add_machine' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a> <a href="{% url 'delete_machine' %}" class="top-menu-waste"><span class="glyphicons glyphicons-sorted-waste"></span></a> <h1><a href="/">WebPage</a></h1> </div> base <div> {% block content %} {% endblock %} </div> </body> </html> This is my .css file: .top-menu, .top-menu:hover, .top-menu:visited { color: #ffffff; float: right; font-size: 26pt; margin-right: 20px; margin-top: 20px; } .top-menu-waste, .top-menu-waste:hover, .top-menu-waste:visited{ color: #ffffff; float: right; font-size: 26pt; margin-right: 60px; margin-top: 20px; } -
Django - Context Variables
I've been looking all over stack and I just can't get anything to work. The simpler for of my doubt is, I have a context variable, which I have to reassign inside a for loop, and I can, but when a new iteration begins, the variable is reset to it's original context value. So my question is, how do I keep the assigned value persistent throughout the loop? I am assigning the value like this: {% with task.new_stage as current %}{% endwith %} The full excerpt of the code follows: {% for task in tasks_list %} <h3>At Beg {{current}}</h3> {% if task.project_stage.id != current %} <div id="tasks-container-{{ task.project_stage.id }}" class="task-container btn-group-vertical col-md-3"> {% endif %} <div class="panel my-panel tasks-panel col-md-11 {% if task.project_stage.has_started and not task.project_stage.has_ended %}active{% endif %} "> <span class="text-uppercase">{{ task.task_name }}</span> <div class="col-md-12"> <img id="task-{{ task.id }}" class="download-pdf" src="{% static 'dpp/images/cloud.png' %}" /> </div> </div> {% if task.project_stage.id != current %} </div>{% with task.new_stage as current %}<h3>At End{{current}}</h3>{% endwith %} {% endif %} {% endfor %} -
Printing something continuously during no incoming request in Flask app
I have a simple flask app where I need to print continuously "no incoming request" when there is no request incoming, to a particular route. Can anyone please help me to solve it -
Django Url pattern regex for tokens
I need to pass tokens like b'//x0eaa@abc.com//x00//xf0//x7f//xff//xff//xfd//x00' in my Django Url pattern. I am not able to find matching regex for that resulting Page not found error. My url will be like /api/users/0/"b'//x0eaa@abc.com//x00//xf0//x7f//xff//xff//xfd//x00'"/ I have tried with following regex url(r'^api/users/(?P<username>[\w\-]+)/(?P<paging_state>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', views.getUserPagination), -
Croos global Variable python Thread
Hi can we help me ? I want change global variable in module1.py by module2.py. module1.py #!/usr/bin/env python import threading import module2 as module22 import time values=True def main(): print "m" def thread(): while(values): print "moduel1" time.sleep(0.50) print "END PROGRAM" def change(): print "change" values=False if __name__ == "__main__": t2=threading.Thread(target=module22.main()) t1=threading.Thread(target=thread()) t1.start() t2.start() t1.join() t2.join() module2.py #!/usr/bin/env python import module1 as module11 def main(): print "module2" module11.change() if __name__ == "__main__": main() When I run sudo python module1.py Resul is Here Result is Here module2 change moduel1 moduel1.. I want get resulet module2 change END PROGRAM -
Get selected values of ManytoMany field in django model save method
I am trying to add data to a table BillRecord from Django admin.I need to access selected values of ManytoMany field in model save method and need to do some logic depending upon the selected objects of ManytoMany field. class ProductType(BaseApplicationModel): name = models.CharField(max_length=128) class Product(BaseApplicationModel):[enter image description here][1] type = models.ForeignKey(ProductType,related_name="products") class BillRecord(BaseApplicationModel): products = models.ManyToManyField(Product, related_name="billrecords") def save(self, *args, **kwargs): super(BillRecord, self).save(*args, **kwargs) for product in self.products.all(): print product In the code when I tried to print the values of product it gives me billing.Product.None that is self.products.all() returns empty queryset I need to get the ID's of the selected objects in the ManyToMany field select box.It is shown in the picture -
ngInit not working properly with AngularJS and Django
I am passing the list of tuple from view to template as shown below in view.py: def index(request): page_index = int(request.GET["page"]) s_page = (page_offset*page_index) + 1 e_page = (page_index + 1)*page_offset user_statuses = get_user_status() user_statuses.sort(key=lambda user_statuses: datetime.datetime.strptime(user_statuses[0], '%Y-%m-%d'),reverse=True) print user_statuses user_statuses = user_statuses[s_page : e_page+1] print user_statuses return render(request, 'view_status.html', {'lists': user_statuses,'next_page':page_index+1,'prev_page':page_index-1}) The user_statuses is the list of tuples. Below is my template: <body> <div ng-app="appTable"> <div ng-controller="Allocation"> <h2><span>VIEW STATUS</span></h2> <a ng-href="/welcome_page/">Return to Welcome Page</a><br><br> Select start date: <input type="text" datepicker ng-model="start_date" /> <br> <br> Select end date: <input type="text" datepicker ng-model="end_date" /> <br> <br> <button ng-click="Submit()"> Submit </button> {%verbatim%} {{error}}{%endverbatim%} {%verbatim%} {{msg}}{%endverbatim%} <br> <table> <th bgcolor="#35a5f0"> <td bgcolor="#35a5f0">Date</td> <td bgcolor="#35a5f0">Project</td> <td bgcolor="#35a5f0">Release</td> <td bgcolor="#35a5f0">Feature</td> <td bgcolor="#35a5f0">Module name</td> <td bgcolor="#35a5f0">Hours spent</td> <td bgcolor="#35a5f0">Comment</td> </th> </thead> <tbody> {%for list in lists%} <tr> {{list.0}} {{list.1}} <td><input type="checkbox" ng-model="data.isDelete"/></td> <td> <div ui-view ng-init="data.date='{{list.0}}'" > <input type="text" datepicker ng-model="data.date" /> </div> </td> <td> <div ng-init="data.dept='{{list.1}}' " > <input type="text" ng-model="data.dept" /> </div> </td> <td> <select ng-model="data.release" ng-options="x for x in range"> </select> </td> <td> <select ng-model="data.feature" ng-options="x for x in feature"> </select> </td> <td> <input type = "text" ng-model = "data.modulename"> </td> <td> <select ng-model="data.hours" ng-options="x for x in hours"> </select> </td> <td> <input … -
How can I use different pagination class per action in Django?
I am using Viewsets. For example, to use different serializer per action I can override get_serializer_class() method. But what about pagination class? Is there any way to set pagination class other than pagination_class = <my pagination class>? I think this is not good as it will change the pagination_class for all the actions. -
restarting redis taking long time
I'm using redis as a broker for celery in my django project. As part of my deployment process I restart the services at the end, so redis, celery, gunicorn (django) etc starting with redis. However I run into an issue where redis will not shutdown. $ sudo systemctl restart redis $ And there it hangs, at time of writing for 15 minutes. journalctl shows no entries (logs have rotated overnight I assume), systemctl status shows the redis unit as deactivating (sig-term) but no indication what it's doing, other than: May 24 10:31:22 staging systemd[1]: Stopping Advanced key-value store... May 24 10:31:22 staging run-parts[305]: run-parts: executing /etc/redis/redis-server.pre-down.d/00_example I understand that sig-term allows redis to exit gracefully, so wondered if the celery beat tasks or the django server was accessing it, but having stopped those services it is still hung up. Are there any places I'm not aware of where I can check the status/what it's doing? -
Generate file in memory and serve it to users pc- Django
The user clicks an Export button, a file is generated in memory ( a .xlsx file using openpyxl) and is downloaded to users pc. How do i do this in Django? I'm inside my views.py where say i have file which is a openpyxl workbook. Normally u save a workbook from memory to disk like so: file.save('desired-name.xlsx') How do i serve this with Django? Thx! -
System statistics in browser using Django
Is it possible to display system statistics in the browser using Django? I have imported psutil library. And want to create a table which show processes like PID, User,CPU% etc.and update on real time basis. Something like this. Tried to add just PID and username it to Django Admin by creating models but dont know how to do it. models.py: from django.db import models import psutil # Create your models here. class Post(models.Model): pid = models.IntegerField(null=False) name = models.CharField(max_length=20,null=False) veiws.py: from .models import Post import psutil def p_details(request, pid, name): for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name']) except psutil.NoSuchProcess: pass else: print(pinfo) def p_details(cls, pid, name): for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name']) except psutil.NoSuchProcess: pass else: print(pinfo) note: new to django and using Windows -
Tiny MCE : custom css override by default css
I try to install Tiny MCE on my project (Django + Angular) but my custom css are override by the default tiny MCE style. I see my custom css in the inspector. Any idea ? Look at my code. tinymce.init({ selector: 'textarea', plugins: 'code', toolbar: 'undo redo | bold italic | link image | code', menubar: false, statusbar: false, content_css : 'my/path/skin.min.css', }); Thanks for your help, P. -
Invalid default value - Django and python
I have a model: class Project(models.Model): project_id = models.CharField(max_length=200) project_name = models.CharField(max_length=200) description = models.CharField(max_length=20) PROJECT_TYPE_CHOICES = ( ('E-Commerce','E-Commerce'), ('Business','Business'), ) APPLICATION_TYPE_CHOICES = ( ('Android','Android'), ('iOS','iOS'), ('Windows','Windows'), ) project_type = models.CharField(max_length=2, choices=PROJECT_TYPE_CHOICES, default='E-Commerce') application_type = models.CharField(max_length=3, choices=APPLICATION_TYPE_CHOICES, default='Windows') def __str__(self): return self.project_name when I do makemigrations it's working fine. but while does migrate it shows below error django.db.utils.OperationalError: (1067, "Invalid default value for 'application _type'") -
html code issues template for django
I have a template where this line is written. I know that each form has a primary key when it is saved in the database. But why in this case the primary key is tested to display the title ??? <div class="page-header"> <h1>Backtesting{% if form.instance.pk %}: {{form.instance.title}} -
Django Foreignkey id to value
I'm new to django. Below you will find the code structure. Let me explain. Basicly on the index.html page I show all Articles of today (publication_date is today). Now they are correctly showing, the problem is that I also want to show the Company Slug nexto it. Currently I just output the Company_id , how can I convert that? model.py class Company(models.Model): name = models.CharField(max_length=128, default='X') slug = models.SlugField(max_length=6, default='X', unique=True) def get_absolute_url(self): return reverse('news:detail',kwargs={'pk': self.pk}) def __str__(self): return self.slug class Article(models.Model): title = models.CharField(max_length=256, unique=True) publication_date = models.DateTimeField() url = models.CharField(max_length=256) Company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.title views.py class IndexView(generic.ListView): template_name = 'news/index.html' context_object_name = 'all_companies' def get_queryset(self): return Company.objects.all() def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) now = datetime.datetime.now() articlesToday = Article.objects.filter(publication_date__year=now.year,publication_date__month=now.month,publication_date__day=now.day) context['articlesToday'] = articlesToday return context index.html <table class="table"> {% for art in articlesToday %} <tr> <td>{{art.title}}</td> <td>{{art.Company_id}}</td> </tr> {% endfor %} </table> -
Expiring specific session variable in Django
It's easy to expire the request.session dictionary via request.session.set_expiry(seconds_until_end_of_day) or via SESSION_COOKIE_AGE. But how do I set the expiry of a specific session variable? E.g. I've alloted an unauth user a temp_id. I need this temp_id to cease to exist in 30 mins. What's the best, most performant way to achieve that? -
How does a Django ModelForm query the database for a ForeignKey meber in the corresponding Model
I have two models in models.py class Inner(models.Manager): name = models.CharField(max_length=256) class Outer(models.Manager): name = models.CharField(max_length=256) inner = models.ForeignKey(Data) I then have a ModelForm for Outer. class OuterModelForm(ModelForm): class Meta: model = Outer fields = ['name', 'inner'] My question is what gets called by ModelForm when displaying the possible inner values in the drop-down in the generated form. I have ruled out the following by overriding the objects with a custom models.Manager. (just by adding print in there and seeing what is called) values get get_queryset all filter -
Django Context processors not working?
I have made one Django context processor which is not working...and it is also showing warning messages.First will show you the warning message:- WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_CONTEXT_PROCESSORS. Now,i have created mym custum context processor this way in settings.py:- TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "cms.utils.context_processors.permission_based_hidding_of_sidebar" ) and created my fuction in utills,the custum context processors:- from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from cms.models.cmsUser import CmsUser from cms.models.masterUsersPermissionTabMappings import MasterUsersPermissionTabMappings @login_required @csrf_exempt def permission_based_hidding_of_sidebar(request): cms_user = CmsUser.objects.get(userId=request.user.id) print cms_user.id universityPermission = MasterUsersPermissionTabMappings.objects.filter(userId=cms_user).get(permissionTypeId=1) cmsUserPermission = MasterUsersPermissionTabMappings.objects.filter(userId=cms_user).get(permissionTypeId=2) promotedPermission = MasterUsersPermissionTabMappings.objects.filter(userId=cms_user).get(permissionTypeId=3) appUserPermission = MasterUsersPermissionTabMappings.objects.filter(userId=cms_user).get(permissionTypeId=4) newsPermission = MasterUsersPermissionTabMappings.objects.filter(userId=cms_user).get(permissionTypeId=5) emailPermission = MasterUsersPermissionTabMappings.objects.filter(userId=cms_user).get(permissionTypeId=6) pushPermission = MasterUsersPermissionTabMappings.objects.filter(userId=cms_user).get(permissionTypeId=7) chatPermission = MasterUsersPermissionTabMappings.objects.filter(userId=cms_user).get(permissionTypeId=8) frontendPermission = MasterUsersPermissionTabMappings.objects.filter(userId=cms_user).get(permissionTypeId=9) print universityPermission a='hello' return render(request,'templates/admin_user_management/admin_user_add.html',{ 'universityPermission':universityPermission,'cmsUserPermission':cmsUserPermission, 'promotedPermission':promotedPermission,'appUserPermission':appUserPermission, 'newsPermission':newsPermission,'emailPermission':emailPermission,'pushPermission':pushPermission, 'chatPermission':chatPermission,'frontendPermission':frontendPermission,'sayHello':a }) and i am trying to view it using this on my views:- return render(request,template-name,{},context_instance=RequestContext(request)) it is showing me the error context_instance is not define in views.Is there is any way i can use it in views. -
In django redirect every user to different pages depending on username
I am developing a django web-application, for authorization I have used django.contrib.auth.urls, is there a way that after authentication I can redirect user to a url like /myapp/history/{{ username }}. I tried couple of methods along with class-based views and login decorators but no luck. Any help would be really great. Thanks -
Django CMS toolbar - redirect after blog post created
I created a toolbar where I have 2 options. A list of all my articles and adding new blog post. It works ok but after I create a post and click save, I would like to automatically redirect to the page with a new post, using its slug. I have no idea how to do this and I think I need some help. My code looks like this: cms_toolbars.py @toolbar_pool.register class ArticleToolbar(CMSToolbar): watch_models = [InfBlogArticle, ] def populate(self): articles_menu = self.toolbar.get_or_create_menu('inf_app', _(u'Artykuly')) url = reverse('admin:inf_blog_infblogarticle_changelist') articles_menu.add_modal_item(_(u'Lista artykulow'), url=url) url = reverse('admin:inf_blog_infblogarticle_add') articles_menu.add_modal_item(_(u'Dodaj nowy artykul'), url=url) def post_template_populate(self): pass def request_hook(self): pass models.py title = HTMLField(blank=True, null=True, verbose_name='Tytuł') slug = AutoSlugField(populate_from='title', unique=True) -
BLOB field in database or directly in the file systeme for 1Go files?
I need to store large file (around 1Go) on my data warehouse. To explain the global contexte simply : the user selects some options in a webview and sends it to the middleware. The middleware uses these informations and sends new ones to a factory. The factory creates the 1Go file. Now I need to store it on the data warehouse in order to be download later by the user. I use the framework django for the middleware and the factory is programmed in python. So my question is : for this size of files, is it better to store it on a blob field on a database ? Or is it better to store it directly on the file systeme ? -
Django import csv whith carriage return
hi i'm creating a django app and i need to import several *.csv files. One's of this file has this structure: id|value (header) 12|¤this is the value¤ 34|¤this is another value¤ I use this code for import file: try: csvfile = open(path, "r", encoding='utf-16') except IOError: return False cursor.copy_from(csvfile , tblname, columns=['id', 'value'], sep='|') but when i try to import this file it gave me this error: psycopg2.DataError: ERROR: missing data for the column "value" Is there a way to import this file keeping carriage return inside text identifier ('¤')? -
Type error: sequence item 0: expected string or Unicode, long found django
I'm trying to reply with an email to a comment that was left on the contact by account_handler but I'm only replying to my self. I'm not sure how to properly setup this reply, I know that I can use reply_to from the emailmessage-object, and I'm doing that, but you will see that I'm only replying to my self. So can someone help me and show me or explain how can I properly reply with an email to a account_handler, additional problem is that I'm also an account_handler in this situation and this is all happening internally in the system, addition to that when I debug the mail function I've got this Type error: sequence item 0: expected string or Unicode, long found and I'm not sure what is that all about. My model where email system is: class LeadContact(models.Model): # this is the model field for account_handler account_handler = models.ForeignKey(User, blank=True, null=True, related_name='handling_leads', on_delete=models.SET_NULL) def __unicode__(self): return self.first_name + " " + self.last_name def generate_serial_number(self): return serial_number.generate_serial_number("lc", self.first_name, self, "LeadContact") @models.permalink def get_absolute_url(self): return 'vinclucms_sales:lead_contact_detail', (self.serial_number,) def get_view_url(self): return "{base_url}{leads_view_url}".format(base_url=get_base_url(), leads_view_url=self.get_absolute_url()) def get_authenticated_view_url_for_user(self, user): ret = self.get_view_url() + sesame_utils.get_query_string(user) return ret def get_clarifications_url(self): clarify_url = reverse('vinclucms_sales:leads_clarify', kwargs={'serial_number': self.serial_number}) return … -
React.js with Django
I need to use react.js as a server side rendering with Django. What is the best way to do it? I do know about django rest framework. But I have a need to build an application using django and react.js as a server side rendering.