Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to mention/tag users with '@' on a django developed project
I am trying to implement the "@" feature used on social sites such as twitter to tag or mention users on my django project. Say for example, "@stack" when clicked should go to stack's profile. How to do that would be helpful to me. -
How to render django inlineformset_factory using javascript
I have a model Post with Comment as ForeignKey. i used inlineformset_foctory to update releted answer to Question object with dajngo templates, but now i want to display formset using javascript. To be spacific, i want to create a link comment so when clicked it display a form that will update Post -
Contact names searching in huge database
I have a project where the main task is to search for contact names stored in database. For example, I have web application where I type in searching field some cell number: "777555444" and as result it returns me a proper name: "John Doe". If proper name was not found, cell number is appended to another database table of unknown numbers. The database could have a billion of contacts. So: 1) the searching should be performed in multithread fasion 2) the maximum memory saving by database (loading into RAM and loading memory from the disk in case of insufficiency) 3) regular database indexation in case of searching for proper "contact names - cell numbers" that where not found before. For example, admin uploaded some list of contacts to the database. But user have already performed searching for one of cell number existed in that uploaded list. It means that cell number is in the table with unknown numbers and now it should be deleted from there. So, what is the best way to implement all this specific features? What techology should I use? For example, my preferable choice is python/Django/mysql. But is that usable in my case? Off course, I … -
Django with Apache working for admin page but gives 404 for all other urls
I am a django beginner. I tried to deploy my django(1.10) site from local server using apache2 (2.4.7) Port opened. Admin page is getting opened properly but all other views are not getting opened. URLS.PY from django.conf.urls import url,include from django.contrib import admin from django.views.generic import RedirectView from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^treedump/',include('treedump.urls')), url(r'^$', RedirectView.as_view(url='/treedump/', permanent=True)), url(r'^accounts/', include('django.contrib.auth.urls')), ] .CONF FILE IN APACHE <VirtualHost *:80> ServerName ********* DocumentRoot /var/www/html/ Alias /static /data1/ekmmsc/webapp/ekmmsc/static WSGIDaemonProcess ekmmsc python-path=/data1/ekmmsc/webapp/ekmmsc python- home=/data1/ekmmsc/webapp/ekmmsc/ekmmscenv WSGIProcessGroup ekmmsc WSGIScriptAlias /ekmmsc /data1/ekmmsc/webapp/ekmmsc/ekmmsc/wsgi.py # Other directives here ... <Directory "/var/www/html/"> allow from all order allow,deny AllowOverride All AddType text/css .css AddType text/javascript .js </Directory> <Directory "/data1/ekmmsc/webapp/ekmmsc/static"> Require all granted </Directory> <Directory "/data1/ekmmsc/webapp/ekmmsc/ekmmsc"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> OUTPUT Not Found The requested URL /treedump/ was not found on this server. Any help will be appreciated , i have been working almost for 2 days on this. Please help. -
dynamic date range query in django
I have written the following function to get minimum date from MySQL table and to display 60 days of data. def listingpage(request): fields = ['promotion_name', 'period' , 'indicator', 'value'] cursor = connection.cursor() cursor.execute('''SELECT min(period) FROM promocal''') time_zone = cursor.fetchone() print(time_zone[0]) time_threshold = time_zone[0] + timedelta(days=10) qs = list(Promocal.objects.filter(period__lte=time_threshold)) json_data = serializers.serialize('json', qs, fields=fields) listing = json_data json_data1 = json.dumps(listing) response = HttpResponse(json_data1) return response Now I want to display the data for the next 60 days. Can anyone help me achieve this? -
django User permissions and Permission Required Mixin
In this code, Django will check for all the permission in the tuple permission_required and if the user having all the permission get access to the view. I want to provide the view if the user having any permission in the given list or tuple. Eg: In this particular case if the user only having the polls.can_open permission I want to provide the view from django.contrib.auth.mixins import PermissionRequiredMixin class MyView(PermissionRequiredMixin, View) permission_required = ('polls.can_open', 'polls.can_edit') -
Finding untagged objects in the Django admin
I am using django-taggit and the Django admin interface. I have some objects and would like to filter them by tag, for that I add my tags field to the ModelAdmin's list_filter. That works fine, and I can select "All" to get all items, or a specific tag, and it shows all items including this tag (using an URL like ?tags__id__exact=56). The filter list also includes an option "-", which generates an URL like ?tags__isnull=True. This list is always empty. I would assume the purpose behind this option would be to show all untagged items, but if that is the case it doesn't work. What can I do to get a list of untagged items in the admin? I have been thinking of subclassing SimpleListFilter, but then I'd have to replicate the logic in the existing list filter. Or, I could subclass the existing filter, but I don't know which class it is. Any ideas? -
combine model and detect changes of both model when submit form
I have combined two model form "User" and "UserPhone" using TabularInline in admin.py, but when i save both model data with single submit button i can only detect changes of "User" model def save_model(self, request, obj, form, change): print "form:",form.changed_data but i need to check changes of "UserPhone" model data also when i save both model data on a single submit. Admin.py class UserPhoneInline(admin.TabularInline): model = UserPhone class UserAdmin(admin.ModelAdmin): list_display = () inlines = [ UserPhoneInline, ] def save_model(self, request, obj, form, change): obj.save() print "form:",form.changed_data,"change:",change class UserPhoneAdmin(admin.ModelAdmin): list_display = () list_filter= [] -
Python Celery chain wait for remote service to finish
I'm using celery to upload video file to remote service, start some processing there and when they are ready - downloading results. I'm having problems with chaining this process. This is what I tried: chain( set_task_status.si(task_pk, TASK_UPLOAD), upload.si(task_pk=task_pk), set_task_status.si(task_pk, TASK_WAIT), start_service.si(task_pk=task_pk, service='transcriber').set( countdown=3), check_progress.si(task_pk), start_service.si(task_pk=task_pk, service='subtitling').set( countdown=3), check_progress.si(task_pk), set_task_status.si(task_pk, TASK_DOWNLOAD), get_transcript.si(task_pk=task_pk), get_subtitles.si(task_pk=task_pk), set_task_status.si(task_pk, TASK_FINISHED) ).apply_async() And it works but right now I use while loop with time.sleep(30) inside check_progress task. Remote service needs to process the video I sent and it takes some time. Function check_progress sends request to remote API and gets progress of this processing. Processing needs to finish before next task in chain can be executed. The problem with this is one celery worker will be constantly busy and won't be able to take another task while it waits for remote service to finish. Is it possible to loop one task in chain (using countdown to delay execution) until remote service finishes? Or maybe I can pause celery chain somehow? -
unable to run server when django toolbar is enabled
We are handling a very large django codebase, we are using django debug toolbar, the problem is so weird, if I put DEBUG_TOOLBAR=True in my django.settings , I am not able to perform any activity with manage.py like python manage.py runserver or python manage.py collectstatic any of it. When I press CTRL+C to terminate, I am unable to, it got stuck there. Here is my django debug toolbar configuration. DEBUG=True DEBUG_TOOLBAR = True if DEBUG and DEBUG_TOOLBAR: INSTALLED_APPS += ( 'debug_toolbar', ) INTERNAL_IPS = ( '127.0.0.1', 'XX.XX.XXX.XXX', ) DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', ] DEBUG_TOOLBAR_CONFIG = { 'RENDER_PANELS': True, 'RESULTS_CACHE_SIZE': 2, 'RESULTS_STORE_SIZE': 10, # Required for ddt_request_history 'SHOW_TOOLBAR_CALLBACK': lambda request: True } MIDDLEWARE_CLASSES += ( 'saul.middleware.profile.ProfileMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ) However, I have gone through the answers of below question, but none of it worked. django-debug-toolbar not showing up -
Not able to navigate to a different page using django views
I'm trying to go to a different page using login credentials,but for some reason Getting Template does not exist error,this is my views.py def checkLogin (request): if request.is_ajax(): param = request.POST.get('param', None) param1 = request.POST.get('param1', None) if (param=="admin" and param1=="admin"): Datenow = datetime.datetime.now().strftime('%H:%M:%S') return render(request,'./login.html',{'Datenow': Datenow}) else: Datenow = datetime.datetime.now().strftime('%H:%M:%S') return render(request,'../../sample.html',{'Datenow': Datenow}) return HttpResponseBadRequest() and this is my error, i know i'm messing p the path,but i'm not sure what the convention is in this case,tried ./ ..// ..//../ and so on,but doesn't seem to work TemplateDoesNotExist at /sample/checkLogin/ ./login.html Request Method: POST Request URL: http://127.0.0.1:8000/sample/checkLogin/ Django Version: 1.11.6 Python Executable: C:\Users\Halo\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.2 -
Need help to fetch required data from model in django
I have below two models, class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField(upload_to='img/') user_uploaded = models.CharField(max_length=50, blank=True) class share_files(models.Model): select_file = models.CharField(max_length=300) from_user = models.CharField(max_length=50) select_user = models.CharField(max_length=50,default=None) user_files stores file uploaded by respective user. and share_files stores shared file name yo user xx by user bb. I want to show shared files with logged in user in template, my function for it in view.py is, def user_files_all(request): if not request.user.is_authenticated: return render(request, 'accounts/logout.html') else: data = user_files.objects.filter(user_uploaded=request.user) data1 = share_files.objects.filter(select_user=request.user) data2 = user_files.objects.filter(Filename=data1.select_file,user_uploaded=data1.from_user) args = {'data': data,'data1':data1} return render(request, 'accounts/files.html', args) but i am getting error for line, data2 = user_files.objects.filter(Filename=data1.select_file,user_uploaded=data1.from_user) as attribute select_file is not present for data1. I want data from user_files model for all users and filename selected in data1. And then want to render that in template. How to achieve that? Need help. Thanks in advance. -
Cannot install Django 2 Beta 1 on Ubuntu Server 16.04
I'm trying to install Django 2 beta 1 on an Ubuntu Server 16.04 using the command line shown on Django's download page without success. The given command line is: pip install --pre django but when I run it, it is trying to install Django 1.11.6. (Downloading Django-1.11.6-py2.py3-none-any.whl (6.9MB)) Does anyone know how I can successfully install the beta ? -
How to update django admin changelist view context from ajax called?
I customized django admin changelist view with FullCalendar template, I would like to display my event when I click prev or next month button, but I cannot figure out how to update data back from changelist_view method. view.html $('.fc-prev-button').click(function(){ var d = $('#calendar').fullCalendar('getDate'); var currentYear = d.year(); var currentMonth = d.month()+1; $.ajax({ url: window.location.href, method: "get", data: { currentYear: currentYear, currentMonth: currentMonth }, success: function(e) { alert('success!'); } }); admin.py def changelist_view(self, request, extra_context=None): ... response = super(BookingAdmin, self).changelist_view( request, extra_context=extra_context ) # get current datetime currentYear = currentMonth = 0 if 'currentYear' in response.context_data: currentYear = response.context_data['currentYear'] if 'currentMonth' in response.context_data: currentMonth = response.context_data['currentMonth'] now = datetime.datetime.now().strftime('%Y-%m-01') if currentYear == 0 and currentMonth == 0 else datetime.date(currentYear, currentMonth, 1).isoformat() response.context_data['now'] = now # fetch booking after today qs = response.context_data['cl'].queryset bookings = qs \ .extra(select={'ci_date':"to_char(checkin_date, 'YYYY-MM-DD')", 'co_date':"to_char(checkout_date, 'YYYY-MM-DD')"}) \ .filter(checkin_date__gt=now).order_by('checkin_date') response.context_data['bookings'] = bookings return response error AttributeError: 'HttpResponseRedirect' object has no attribute 'context_data' I don't know if this is the correct way to do ajax in Django, need some hints to solve it out, thank you so much! -
Django get user by generic USERNAME_FIELD
Is there a nice way to get a user from Django User model making a query with the generic USERNAME_FIELD instead? In other words, instead of: User.objects.get(username='my_user') or User.objects.get(email='test@user.com') I would like to do something like: User.objects.get(User.USERNAME_FIELD=a_username_variable) Obviously, the latter throws a SyntaxError, but I am asking if there is a way to query based on USERNAME_FIELD -
%s must be from the same graph as %s with Tensorflow and django
I use the web framework Django to render service.I debug the code in the local,and it returns the correct result.However,it throws an exception when I post the data with fiddler. the code is below: from PIL import Image import numpy as np import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import random import base64 import io as stringIOModule from io import BytesIO IMAGE_HEIGHT = 50 IMAGE_WIDTH = 223 MAX_CAPTCHA = 5 CHAR_SET_LEN = 36 alphabet = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] def vec2name(vec): name = [] for i in vec: a = alphabet[i] name.append(a) return "".join(name) X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT*IMAGE_WIDTH]) Y = tf.placeholder(tf.float32, [None, MAX_CAPTCHA*CHAR_SET_LEN]) keep_prob = tf.placeholder(tf.float32) # define CNN def crack_captcha_cnn(w_alpha=0.01, b_alpha=0.1): x = tf.reshape(X, shape=[-1, IMAGE_HEIGHT, IMAGE_WIDTH, 1]) # 3 conv layer w_c1 = tf.Variable(w_alpha * tf.random_normal([5, 5, 1, 32])) b_c1 = tf.Variable(b_alpha * tf.random_normal([32])) conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1)) conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') conv1 = tf.nn.dropout(conv1, keep_prob) w_c2 = tf.Variable(w_alpha * tf.random_normal([5, 5, 32, 64])) b_c2 = tf.Variable(b_alpha * tf.random_normal([64])) conv2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2)) conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') conv2 = tf.nn.dropout(conv2, keep_prob) w_c3 … -
NoReverseMatch while using get_absolute_url in Django
Error Trace: NoReverseMatch at /search/ Reverse for '/about/murder-in-the-curtain' not found. '/about/murder-in-the-curtain' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/search/?q=mur Django Version: 1.11.6 Exception Type: NoReverseMatch Exception Value: Reverse for '/about/murder-in-the-curtain' not found. '/about/murder-in-the-curtain' is not a valid view function or pattern name. URL Conf: url(r'^about/(?P<slug>[-\w]+)$', about_pages, name="about_pages") Model: class Book(models.Model): slug = models.SlugField(default = "") def get_absolute_url(self): reverse("about_pages", kwargs = {"slug" : self.slug}) Template: {% for result in results %} <a href = {% url result.get_absolute_url %}>{{result.name}}</a> {% endfor %} Is my regex alright? I feel its generating the url correctly but not finding a matching pattern in URLConf to navigate to a view. -
Django template block code does not work when included as a snippet
I want to change the state of the navbar as highlighted in different pages. When I am normally placing the nav-bar in base.html and add a block content it works. <!DOCTYPE html> <html lang=en> <head> <title>Dashboard</title> {% include 'snippets/css.html' %} </head> <body> <!-- Sidebar Holder --> <nav id="sidebar"> <ul class="list-unstyled components"> <li{% block nav_live %}{% endblock %}> <a href="{% url 'live_now' %}"><i class="fa fa-users" aria-hidden="true"></i>Live Now</a> </li> <li{% block nav_out %}{% endblock %}> <a href="{% url 'outcome' %}"><i class="fa fa-crosshairs" aria-hidden="true"></i>Outcome Score</a> </li> <li {% block nav_customer %}{% endblock %}> <a href="{% url 'customer_search' %}"><i class="fa fa-search" aria-hidden="true"></i>Customer search</a> </li> <li {% block nav_journey %}{% endblock %}> <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false"><i class="fa fa-map-o" aria-hidden="true"></i> Journey Shaping</a> <ul class="collapse list-unstyled" id="homeSubmenu"> <li><a href="{% url 'persona' %}">-Persona</a></li> <li><a href="#">-Outcomes</a></li> <li><a href="#">-Action Maps</a></li> <li><a href="#">-Auto Responses</a></li> </ul> </li> <li {% block nav_analytics %}{% endblock %}> <a href="#analyticsmenu" data-toggle="collapse" aria-expanded="false"><i class="fa fa-bar-chart" aria-hidden="true"></i>Analytics</a> <ul class="collapse list-unstyled" id="analyticsmenu"> <li><a href="#">-Visitor Activity</a></li> <li><a href="#">-Visit History</a></li> <li><a href="#">-Action Map Performance</a></li> <li><a href="#">-Interactions</a></li> </ul> </li> <li{% block nav_settings %}{% endblock %}> <a href="#settingsmenu" data-toggle="collapse" aria-expanded="false"><i class="material-icons md-18" >tune</i>Settings</a> <ul class="collapse list-unstyled" id="settingsmenu"> <li><a href="{% url 'set_phone' %}">-Phone Number</a></li> <li><a href="{% url 'track_code' %}">-Tracking Code</a></li> <li><a href="#">-Action Map Performance</a></li> … -
Django weasyPrint fontconfig error
I have an application that I need to get pdf files from so I opted for weasyprint but after installing with PIP I imported import weasyprint I got an error in terminal OSError: ctype.util.find_library() did not manage to locate a library called fontconfig Then I tried to use from weasyprint import HTML, CSS from weasyprint.fonts import FontConfiguration I still got the same error. Without writing any further codes the import statements is stuck on the error. I’m running the lates django and weasyprint as of October. Thanks in advance -
Remove "django_ct" foreign key constraint from haystack queries
I have an existing SQL base, which is indexed by Solr. I want to use haystack, because of its abstraction and object creation from queries. The problem is that the haystack search forms and SearchQuerySet always add &fq=django_ct:(appname.model) to the query. Is there a way to remove this from the generated query. There is a way to rename it, but i did not find any way to remove it at all. This query always fails, because there isn't any fq which is called django_ct and why does it has to be there in the first place ? -
AttributeError at /login/ 'WSGIRequest' object has no attribute 'get' in Django
Ok more on forms. I have finally got my form to validate, post and redirect to page it needs to. Now my issue is when I return to the page with the form I get this error: python manage.py runserver I am facing issue. when i run python manage.py runserver getting error :- AttributeError at /login/ 'WSGIRequest' object has no attribute 'get' django version :- 1.5.2 views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required(login_url="login/") def home(request): return render(request,"home.html") app urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), ] main urls.py from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views from log.forms import LoginForm urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('log.urls')), url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}), url(r'^logout/$', views.logout, {'next_page': '/login'}), ] login.html {% extends 'base.html' %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} … -
Django join tables to show data on the intersection between rows and columns
I've two class models, in which the first one (Activity) is prefilled by the admin, while the second (workingDays) is used as an input form to be filled by the website users, as follows: class Activities(models.Model): activity= models.CharField(primary_key= True, max_length= 300) provider= models.CharField(max_length= 50) activity_id= models.CharField(max_length= 50) class WorkingDays(models.Model): user = models.ForeignKey(User) activity= models.CharField(choices=labels, max_length=200) activity_id = models.CharField(max_length=25) worked_hours= models.FloatField(max_length=3) worked_days = models.FloatField(max_length=2) I need to render a view template with the "user" on the column tags, "activity" on the rows, and the number of worked_hours on the intersection as follows: ------------------------------------------ Activity | user1 | user2 | user3 | user4| ------------------------------------------ act1 | 12 | | 10 | | ------------------------------------------ act2 | | 20 | 10 | 10 | ------------------------------------------ act3 | 5 | | 10 | 14 | ------------------------------------------ Any help using Django-ORM or django-tables ? -
Creating a API test environment in Django
I am in need of creating a test environment for a Django app. My app provides some REST APIs and it does http requests to other external APIs. In production, there is no problem. However, during development, my app needs to be able to provide fake responses by mocking the responses from external APIs, so that it should not rely on the external API server being up or down. I don't want to make my app code dirty. So, checking DEBUG=True and sending response is not a solution. After thinking for a while I came to a theoretical solution: Write a middleware which does the mocking work. But, I have not been able to make this work out. Can anyone provide me how to do this, or any other ways of creating a test server which does not have to rely on external API server and network issues? -
apps/goods/models.py 'apps.goods.models' apps is not package?
my project directories is: apps/ goods/ models.py views.py base.py trades/ users/ __init__.py apps/goods/base.py from django.views.generic.base import View from apps.goods.models import Goods class GoodsListView(View): def get(self, request): json_list = [] goods = Goods.objects.all()[:10] for good in goods: # json_dict = {} # json_dict['name'] = good.name # json_dict['category'] = good.category.name # json_dict['market_price'] = good.market_price # json_dict['add_time'] = good.add_time # json_list.append(json_dict) from django.forms.models import model_to_dict for good in goods: json_dict = model_to_dict(good) json_list.append(json_dict) from django.http import HttpResponse import json return HttpResponse(json.dumps(json_list), content_type='application/json') i'm debug base.py not get data, but get the error: from apps.goods.models import Goods ModuleNotFoundError: No module named 'apps.goods'; 'apps' is not a package and, i remove 'apps' in 'apps.goods.models', get the error: from goods.models import Goods ModuleNotFoundError: No module named 'goods' env: pycharm-2017.2 django-1.11.6 why get the error? -
Django - which are the permitted filters in if condition in a template? slice and first seems not working
I am getting the partition info and send it to template, in a <table>. If a partition's used percentage is above 90%, the percentage should be in red. Because there are more than one partition in the machine, so the conditional style of rows are independent, so it is better to decide when rendering, not in the view. The percentage come as integer (89), not in decimal(0.7). If it is decimal, I can use {% if '0.9' in value %}, but it is not the case. I have my template like this: (part.0 to part.4 are other data about partitions) <tbody> {% for part in partitions %} <tr> <td>{{part.0}}</td> <td>{{part.1}}</td> <td>{{part.2}} GB </td> <td>{{part.3}} GB </td> <td>{{part.4}} GB </td> {% if part.5|slice:"0:1" == "8" or part.5|slice:"0:1" == "9" %} <td><font color="red">{{part.5}}%</font></td> {% else %} <td>{{part.5}}%</td> {% endif %} </tr> {% endfor %} </tbody> Now, it does not complain, but does not turn red neither when the data matches the condition. In the documentation, I see this frase: Filters You can also use filters in the if expression. For example: {% if messages|length >= 100 %} You have lots of messages today! {% endif %} But, it mentions no other filters …