Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to fetch all data which is in my timeline but it is returning either first or last. DjangoRestMultipleModels
i have two models from which i want to fetch details for a particular user i am using DjangoRestMultipleModels querylist is inside for loop but it is returning only one data either first or last class UserTimelineAPIView(MultipleModelAPIView): def get_queryList(self): user = self.request.user.id obj = SubscriberFollower.objects.filter(user=user) for ab in obj: queryList = [ (Post.objects.filter(institute_id=ab.institute.id), PostSerializer), (Event.objects.filter(institute=ab.institute.id, active=True), EventSerializer), ] return queryList -
Django Add custom button to each column of Model that connects to a view
I am working on Django web app which logs the data from IOT sensors to a database. From Django admin page, want to add buttons to the columns of Model that when clicked connects to a view which shows the matplotlib graph of that column. Worked on URL and views and got the graph view part working, now need to add clickable buttons to columns of the Model. DOn't know how to do and very new to DJango. Please give me some directions and help me in achieving this. Thanks for your valuable time. -
Using Trello API Key in a Django Project
I've checked Stackoverflow and I haven't been able to find a answer to my question, so I'm asking here. I'm trying to create a dashboard which uses the Trello API in order to display specific metrics. The code section where I'm having trouble is here: from django.conf import settings from dashing.widgets import NumberWidget from trello import TrelloApi trello = TrelloApi(settings.API_KEY) class TrelloCards(NumberWidget): title = 'The Difference Dashboard' def get_more_info(self): return ' {} closed'.format(len(trello.boards.get_card_filter('closed', 'BOARD_ID'))) def get_change_rate(self): return ' {} open'.format(len(trello.boards.get_card_filter('closed', 'BOARD_ID'))) def get_value(self): return len(trello.boards.get_card_filter('all', 'BOARD_ID')) Where API_KEY is my Trello Developer API KEY and BOARD_ID is the id of the board I'm currently using. When I go to run this code, I get an error message saying: AttributeError at /dashboard/ 'Settings' object has no attribute 'API_KEY' I've tried changing the code to say trello = TrelloApi(API_KEY) In line with what the docs say, but this does not fix the issue. If someone could just point me in the right direction with what I'm doing wrong, I'd be grateful! -
Receive angular formdata object in django
$scope.sendFile = function(data){ console.log("New chunk arrived,,",data) // $http({ // method:'POST', // url:'/post_resume_viascript/', // data:{"resume_chunk":data}, // transformRequest: angular.identity, // headers: {'Content-Type': undefined} // }) // .success(function(data){ // console.log("Sucess/////////////////") // }); $http({ method: 'POST', url: "/post_resume_viascript/", headers: { 'Content-Type': undefined }, transformRequest: function (data) { var formData = new FormData(); formData.append("files", data[0].files); transformRequest: angular.identity; return formData; }, data: {"resume_chunk":data} }).success(function (data, status, headers, config) { alert("test"); }); I need to send myfiles by appending it to the angular formdata object.But i dont know how to receive it in the Django backend(views.py) -
django filter queryset based on count of another queryset
Assume my models: model book charfield name model review charfield bookname Is there a way to filter/exclude the books with review count zero? I looked this up throughly on stackoverflow but couldn't find an answer. This is not a homework question. I have a queryset approx. size around 200,000, from which I concluded that it is not smart to filter by converting the queryset to a python list, filter, then convert back. Can someone help me with this? Thanks -
Django Ajax Submission Merging View Methods
My question is how can I "merge" the two view functions into one? I would like to be able to call submit() via AJAX and have that function return the file. Currently submit() only generates the file and then send() actually serves the file. AJAX code in my HTML file $.ajax({ type:'POST', url:'/submit/', data:{ data that I submit }, dateType: 'json', success:function() { document.location = "/send"; } }) My Views Function for /submit/ and /send to return file def submit(request): #Receive Data #Create a File with the Data and save it to the server return HttpResponse() def send(request): lastName = get_last_name() +'.docx' filename = get_full_path() # Select your file here. wrapper = FileWrapper(open(filename , 'rb')) response = HttpResponse(wrapper, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=' + lastName response['Content-Length'] = os.path.getsize(filename) return response How can those two methods be merged into one? So when submit is called it returns the file? Because when I merge them, the file does not get downloaded. -
How to get filename of file uploaded to imagefield?
I need to past in template a filename of file which uploaded in instance imagefield. My class: def conference_directory_path(instance, filename): return 'dialogues/conferences/conference_{0}/avatar/{1}'.format(instance.id, filename) class Dialogue(models.Model): ... avatar = models.ImageField(upload_to=conference_directory_path, blank=True) ... Template: <img src="/static/dialogues/conferences/conference_{{ dialogue.id }}/avatar/{{ dialogue.avatar.filename }}" alt=""> But dialogue.avatar.filename is empty string after rendering. What's wrong? dialogue is an instance of Dialogue model. -
Why do I get this ImportError "No module named router" when it's clearly here?
when I try to run the Django server I'm treated with this error: ImportError "No module named router" I have no problems with the imports, I'm sure as this problem is only when I try to work with routers, for example; viewsets in my views.py work perfectly, this means that viewsets are successfully imported and restframework is installed. Thanks! from django.conf.urls import url, include from django.contrib import admin from rest_framework.routers import SimpleRouter router = SimpleRouter() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/v2/', include('router.urls')), ] -
Pass array of objects to another model call djano
I am trying to select all class for a user and then load all of the classes objects that are corresponding. Here is my model.py file: from django.db import models from django.contrib.auth.models import User class Class(models.Model): name = models.CharField(max_length=150) description = models.TextField() teacher = models.ForeignKey(User) class UserClasses(models.Model): class_name = models.ForeignKey(Class) user = models.ForeignKey(User) And here is the call i'm making: def index(request): //grab all classes for a user users_classes = UserClasses.objects.filter(user=request.user) //pass the array of class objects and get their info classes = Class.objects.select_related(self=users_classes) context_dict = {} return render(request, 'dashboard/index.html', context_dict) How can I achieve the above? -
How to make a seperate view function for AJAX requests?
My views function is getting fairly messy, so is it possible to call my ajax requests from a seperate function within my views file? Here's my view def article(request, category, id): name = resolve(request.path).kwargs['category'] for a, b in CATEGORY_CHOICES: if b == name: name = a instance = get_object_or_404(Post, id=id, category=name) allauth_login = LoginForm(request.POST or None) allauth_signup = SignupForm(request.POST or None) #comments comment = CommentForm(request.POST or None) ajax_comment = request.POST.get('text') comment_length = len(str(ajax_comment)) comment_list = Comment.objects.filter(destination=id) score = CommentScore.objects.filter(comment=comment_list) if request.is_ajax(): username_clicked = request.GET.get('username_clicked') profile = Profile.objects.get(username=username_clicked) if username_clicked: print(profile.age) if comment.is_valid(): comment = Comment.objects.create(comment_text=ajax_comment, author=str(request.user), destination=id) comment.save() score = CommentScore.objects.create(comment=comment) score.save() username = str(request.user) return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username}) else: print(comment.errors) context = { 'score': score, 'comment_list': comment_list, 'comment': comment, 'instance': instance, 'allauth_login': allauth_login, 'allauth_signup': allauth_signup } return render(request, 'article.html', context) For example, for the username_clicked, i'd like to take that out and make it's own function like this within the same views file: def raise_profile(request): if request.is_ajax(): username_clicked = request.GET.get('username_clicked') profile = Profile.objects.get(username=username_clicked) if username_clicked: print(profile.age) return HttpResponse() Is this possible? Keep in mind these are all at the same URL url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article') Is this possible? -
django custom login using old database
My Project Directory Structure(image) This is my code (backends.py): from django.contrib.auth.hashers import make_password from django.contrib.auth.hashers import MD5PasswordHasher # from django.contrib.auth.models import User from .models import Users class UserAuthBackend(object): def authenticate(self, email=None, password=None): try: user = Users.object.get(user_email=email) if make_password(password, hasher=MD5PasswordHasher) == user.user_password: return user except Users.DoesNotExist: return None def get_user(self, user_id): try: user = Users.objects.get(pk=user_id) return user except Users.DoesNotExist: return None My Users class in models.py: class Users(models.Model): user_id = models.BigAutoField(primary_key=True) user_name = models.CharField(max_length=25) user_fname = models.CharField(max_length=40, blank=True, null=True) user_lname = models.CharField(max_length=40, blank=True, null=True) user_email = models.CharField(max_length=60) user_password = models.CharField(max_length=255) joining_date = models.DateTimeField() user_dob = models.DateField() user_country = models.CharField(max_length=3, blank=True, null=True) user_gender = models.CharField(max_length=1) user_pic = models.CharField(max_length=255, blank=True, null=True) user_about = models.CharField(max_length=512, blank=True, null=True) class Meta: verbose_name = 'Users' verbose_name_plural = 'Users' managed = False db_table = 'tbl_users' settings.py AUTH_USER_MODEL = 'myWebsite.Users' AUTHENTICATION_BACKENDS = ['myWebsite.backends.UserAuthBackend', ] In my database I have a table 'tbl_users' which has user_email and user_password columns and corresponding to that I wish to authenticate. I read the django documentation Custom Authentication and as far as I understood I have implemented correctly ( which I doubt ). There are a few queries : Why do I need from django.contrib.auth.models import User , if I have my own model … -
Import in models.py
I've implemented a dictionary in the settings.py of my project. In app/models.py, I'd like to implement a property in using that dictionary. Do I have to import something in this model? -
Invalid redirect URI with Stripe on Django
I'm trying to integrate Stripe connect with django-allauth, when I try to connect through stripe I'm getting an error message : Invalid redirect URI '...herokuapp.com/accounts/stripe/login/callback/'. Ensure this uri exactly matches one of the uris specified in your application settings I've set up stripe redirect_uri on the stripe connect settings page to my heroku app url : (http://...) - Development In the admin page of my website I've also set up the cliend_id and the secret_key correctly specifying the site where it should work (my site). here's how I configured stripe on my settings.py : INSTALLED_APPS = [ ... 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.stripe', ] SITE_ID = 2 LOGIN_URL = '/accounts/login' LOGIN_REDIRECT_URL = '/' ... other allauth configurations template/account/login.html : <div class="facebook_login"><p><a href="{% provider_login_url 'stripe' %}">Stripe</a></p></div> Why do I get the error above? Where is my mistake ? -
Django multiple queries optimization
I have a Django view that return a map of the edit distance between thousands of strings. These strings are arguments of the MyModel class. I calculate the distance in the myView function. I profiled this code and realized that the queryset consumes a lot of time. How could I optimize this? # models.py class MyModel(models.Model): str1 = models.CharField(max_length=300) str2 = models.CharField(max_length=300) class OtherModel(models.Model): ... my_model = models.ForeignKey(MyModel) ... # views.py def myView(request): query_set = MyModel.objects.filter(....) size = query_set.count() arr = numpy.zeros(size ** 2).reshape(size, size) for i in range(size): for j in range(size): m1 = query_set[i].str1 m2 = query_set[j].str1 arr[i][j] = some_comparison_algorithm(m1, m2) json_out = json.dumps({'data': arr.tolist()}) return HttpResponse(json_out, content_type="application/json") -
Why it does not remove the line breaks?
Why it does not remove the line breaks? Number of pages determines line breaks are not removed. def save(self, *args, **kwargs): self.full_text = re.sub('\n+', '', self.full_text) self.pages_count = str(math.ceil(len(self.full_text.split(' ')) / 20)) super(Book, self).save(*args, **kwargs) -
Websocket using Django Channels
I am trying to use Django channels to establish a websocket connection with the browser. The websocket fails to connect with the server: [2017/01/23 23:51:50] HTTP GET / 200 [0.03, 127.0.0.1:60445] [2017/01/23 23:51:51] WebSocket HANDSHAKING /chat/ [127.0.0.1:60451] [2017/01/23 23:51:56] WebSocket DISCONNECT /chat/ [127.0.0.1:60451] Javascript used for websocket: socket = new WebSocket("ws://" + window.location.host + "/chat/"); socket.onmessage = function (e) { alert(e.data); }; socket.onopen = function () { socket.send("hello world"); }; // Call onopen directly if socket is already open if (socket.readyState == WebSocket.OPEN) socket.onopen(); settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", "ROUTING": "django_chat_server.routing.channel_routing", } } Routing.py channel_routing = { # Wire up websocket channels to our consumers: 'websocket.connect': ws_add, 'websocket.receive': ws_message, 'websocket.disconnect': ws_disconnect, } On loading the page, ws_add fires up but the connection eventually get's disconnected. Any lead on how can I debug this, or what the problem could be. I am running the server using the command python manage.py runserver -
Django will not recognize a settings module
I'm trying to set up a settings module for a Django app per this guide. I have the settings module created, which contains the __init__.py, common.py, and dev.py. However, when I attempt python manage.py runserver --settings=settings.dev, I get the import error: "No module named 'settings" If I attempt python manage.py runserver --settings={APP_NAME}.settings.dev, I get the import error: "No module named 'common' I feel like I'm missing something simple here, but can't seem to figure it out. Here are the contents of my files: dev.py: from common import * # from os.path import join, normpath # DEBUG CONFIG DEBUG = True ALLOWED_HOSTS = [] # END DEBUG CONFIG # DATABASE CONFIG # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Local instance wampmysqld64', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '3306', } } # END DATABASE CONFIG common.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'sk5u2-*6knezfnui#o*%&_e9bwa#q(k_h9%96conoesr1t0vko' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = … -
Scrapping Microsoft Outlook Meeting data
I'm trying to build a predictive model on meeting rooms availability for my personal project. I was wondering if any of you have any experience scrapping data from Microsoft Outlook - the data I am looking for are the meeting rooms availability and the person booking. Preferably in Node.js or Python. Thanks in advance! -
Change Django Shell Plus Kernel default specs
I'm trying to create a kernel that uses the libraries in my virtualenv, however, everytime I change the kernel.json in the django_extensions folder, it will always re-instantiate again with the defaults. For example, I want my kernel.json to look like this {"display_name": "Django Shell-Plus CUSTOMADE", "language": "python", "argv": ["/Users/home/Envs/virutalenv/bin/python", "-m", "ipykernel", "-f", "{connection_file}", "--ext", "django_extensions.management.notebook_extension"], "env": {}} In which the argv points to the python directory that my libraries are in. But no matter how often I change it, everytime I run python manage.py shell_plus --notebook, the kernel will always revert to {"display_name": "Django Shell-Plus", "language": "python", "argv": ["/usr/bin/python", "-m", "ipykernel", "-f", "{connection_file}", "--ext", "django_extensions.management.notebook_extension"], "env": {}} I end up having two kernels, one for the CUSTOMADE which works because the libaries are loaded correctly, while the other one keeps throwing an import error ImportError: No module named 'django_extensions', which I'm sure is because it's not importing from the right python directory. I have even tried deleting the django_extensions one but it will always come back.Thoughts on overcoming this? -
Django, Apache2 and Nginx : Long loading time
I use Django as a technology for my website. Let's say that the domain name I use is example.com. I use Apache2 as my main web server and Nginx to serve static files. I first installed Apache and tested it. It worked perfectly (Without css and other static files, just the html). I then installed Nginx (I have never used it before today) and this is where I encountered problems. Indeed when I want to access my website I get the html well as before. But the loading continues and the static files are not recovered. I do not see any error in the Mozilla terminal. Here is "Site-available" configuration : <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. … -
How to programmatically add columns to Postgresql database tables in Django?
I'm working on a project dealing with data uploading and retrieval. Basically, I have a database with one giant table, and I want to make it so that if someone uploads a csv file, the backend code grabs the headers and data from that file, and adds new columns to the database table based on the headers. So if the table currently has columns A, B, and C, and the user uploads a csv file with columns A, B, C, and D, I want the table to permanently add column D. What would be the best way to accomplish this in Django? I'm currently using Postgresql as the database. -
Linking Html pages together in Django
I have 3 HTML pages; 1 main page that directs to 2 different options. My html mainpage is directed to the other pages within the Django folder but I don't know if that's possible. Clicking the actual file links fine but when uploaded on the django server it wont work. HTML <html> <form action="file:///H:\My Documents\GUI\page1.html"> <input type="submit" value="Launch Test Plan" /> </form> &nbsp &nbsp <form action="file:///H:\My Documents\GUI\page2.html"> <input type="submit" value="Modify Test Plan" /> </form> </body> </html> Shows the right port address with the main page buttons working -
Import error after installing pip packagaes with sudo
On Ubunutu 16.04 LTS, while trying to insatll packages using pip install I get the error: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python3.5/dist-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python3.5/dist-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python3.5/dist-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python3.5/dist-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python3.5/dist-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/usr/local/lib/python3.5/dist-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/usr/local/lib/python3.5/dist-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/graphviz-0.5.2.dist-info' so I decided to use sudo pip install instead, which worked fine, until I tried importing said package to my Django project, I get the following import error: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f749a55ee18> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 33, in __get__ res … -
PythonAnywhere How to handle multiple "web workers" or processes
Summary of my website: A user fills in some information which after hitting "submit" the information is submitted to the backend via AJAX. Upon the back end receiving the information, it generates a DOCX using the information and serves that DOCX file back to the user. Here is my AJAX Code in my HTML File $.ajax({ type:'POST', url:'/submit/', data:{ data that I submit }, dateType: 'json', success:function() { document.location = "/submit"; } }) My Views Function for /submit/ that uses send_file to return file def submit(request): #Receive Data #Create a File with the Data and save it to the server return send_file(request) def send_file(request): lastName = get_last_name() +'.docx' filename = get_full_path() # Select your file here. wrapper = FileWrapper(open(filename , 'rb')) response = HttpResponse(wrapper, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=' + lastName response['Content-Length'] = os.path.getsize(filename) return response This has worked flawlessly for sometime now. However I started having problems when I increased the amount of "web-workers"/processes from 1 to 4 in my hosting account. What happens is I get an error saying the file that I am trying to send does not exist. So I am assuming that the extra processes that are able to run my web app are creating … -
how to configure two project of django with virtual env, window in apache?
I need to configure more than two django projects in window with apache and every django project has a different virtualenv