Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - AttributeError: relativedelta object has no attribute translate
I am trying to update a self datetime field of a model using F() object in django. HeatWatchList.objects.filter( user=request.user, next_date_to__lt=datetime.combine(datetime.now().date(), time.min) ).update( next_date_from = F('next_date_from') + relativedelta(months=1), next_date_to = F('next_date_to') + relativedelta(months=1) ) But when doing this i got AttributeError: relativedelta object has no attribute translate. -
Celery task not received by worker when two projects
My colleague has written celery tasks, necessary configuration in settings file and also supervisord config file. Everything is working perfectly fine. The projects is handed over to me and I seeing some issues that I have to fix. There are two projects running on a single machine, both projects are almost same (projA and projB). supervisord.conf file is as: ;for projA [program:celeryd] directory=/path_to_projA/ command=celery -A project worker -l info ... [program:celerybeat] directory=/path_to_projA/ command=celery -A project beat -l info ... ; For projB [program:celerydB] directory=/path_to_projB/ command=celery -A project worker -l info ... [program:celerybeatB] directory=/path_to_projB/ command=celery -A project beat -l info ... The issue is, I am creating tasks through a loop and only one task is received from celeryd of projA, and remaining task are not in received (or could be received by celeryd of projB). But when I stop celery programs for projB everything works well. (please note, the actual name of django-app is project hence celery -A project worker/beat -l info). Please bare, I am new to celery, any help is appreciated. TIA. -
Run SQL post DB creation but pre migrations with pytest
I have a django project that some of its models use a special index. For this reason i create a extension in my db pre-migrations. When i run the tests, pytest creates a test db and runs the migrations but no extension is created. I cannot create the extension inside the migrations. Is there any way to insert a "RunSQL" command on the test db after db creation but before the migrations run? Tech stuff: Django 1.9.5 pytest postgres 9.5 -
How to deploy django project in pythonanywhere
I already have my server running, but I don't know how to add my django project, I'm new to django, if anyone can help me out I'd be very thankful. -
how to use material-ui with django
i want to use react with material-ui in django project . i found node package Webpack to build bundles and found this answer answer but not working sample of jsx file: import React from 'react'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; injectTapEventPlugin(); app.html: <!DOCTYPE html> <html lang="en"> <head> <base target="_blank"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{{ STATIC_URL }}cartoview_geonode_viewer/css/components.css"> <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}cartoview_geonode_viewer/app.css"> <title>{{ instance.title }}</title> <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en,Object.assign"></script> <script src="{{ STATIC_URL }}cartoview_geonode_viewer/resources/ol3-cesium/Cesium.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div id='main'></div> <script src="{{ STATIC_URL }}cartoview_geonode_viewer/react-15.0.0.js"></script> <script src="{{ STATIC_URL }}cartoview_geonode_viewer/react-dom-15.0.0.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script> <script src="https://boundlessgeo.github.io/sdk/dist/js/full.js"></script> <script src="{{ STATIC_URL }}cartoview_geonode_viewer/require.js"></script> <!-- bundle material-ui.js --> <script src="{{ STATIC_URL }}cartoview_geonode_viewer/vendor/build/material-ui.js"></script> <script type="text/babel" src="{{ STATIC_URL }}cartoview_geonode_viewer/app.jsx"></script> </body> </html> errors: -
Template code shows no results
I want to show the values of my database in my detail template. Because of my model: class RiskFactor(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) examination = models.CharField(max_length=100, choices=Examination_Choice, default='notchosenyet') hypertension = models.BooleanField(default=False) diabetes = models.BooleanField(default=False) I want to filter the values of the first examination and so I've design my template like this: <ul> {% for rfac in patient.riskfactor_set.all %} {% if rfac.examination == 'FIRST' %} <li>Hypertension: {{ rfac.hypertension }}<br/> Diabetes: {{ rfac.diabetes }}<br/> </li> {% endif %} {% endfor %} </ul> But I got no values shown in my detail page. Any ideas? -
Django foreign key form save
I am currently working an a 'IMDB' clone for me and my friends to use. The idea is that each of us gets an account and can either submit new movies or vote on already submitted ones. These movies are sorted by rating and users can access the detail view to see the individual reviews. To achieve this I'm using foreign keys in my models.py - one for the movie entries (with information like director, title, etc) and one for the individual votes. The latter one uses foreign keys to fetch the movies title and the user that submitted the review. However when testing the form that submits reviews I encountered the 'NOT NULL constraint failed: list_vote.voter_id_id' error. When browsing through the error page I discovered that the foreignkey values are not submitted to the database params: [None, None, 9.0] query: ('INSERT INTO "list_vote" ("movie_id_id", "voter_id_id", "rating") VALUES (?, ' '?, ?)') self <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f77b8907dc8> Yet, when I browse the error page for the local vars at the moment of the 'post.save()' command the missing variables seem to be there entry: <Entry: Starwars 4> form: <VoteForm bound=True, valid=True, fields=(rating)> movie_id: 'Starwars 4' post: <Vote: Vote object> request: <WSGIRequest: … -
Python Django CRUD with MySQL
I have been working in PHP from the past 2 years or so. I also have worked enough with Python, basically Data scraping projects in Scrapy Framework. I have a project which I want to do in Python, Django or any other Framework. My goal is to have a simple CRUD with MySQL. I have searched a lot but have not found any ready-made solution. Only thing I found is https://github.com/rayed/django_crud but its in SQLlite Short question: How do I create a simple CRUD app using Python (any Framework) with MySQL? Is there any readymade solution available? Like we have in PHP, Codeginter Bonfire (it has module builder) -
Authorization header not passed on to django app by Heroku (TokenAuthentication)
I don't exactly understand much about servers (I'm a second year computer science student) and I would appreciate a simple answer. So, basically, I'm using django's TokenAuthentication to authenticate users for my app and it worked all fine when I was testing it on localhost but it just stopped working when I deployed it onto Heroku. I get { "detail": "Authentication credentials were not provided." } even though I add "Authorization" and "Token xxxxx...xx" in the header of the http request (curl -H "Authorization: Token 102512d001bd4e88e5c611e1e1991b7c4a1f3501" -X GET https://themoviebook.herokuapp.com/users/) class UserList(generics.ListCreateAPIView): # DONE """ https://themoviebook.herokuapp.com/users/ GET request fetches all the users in the db POST request body {"username":<>, "password":<>, "email":<>, "first_name":<>, "last_name":<>} adds user to the db Required Keys for POST: username, password, email, first_name, last_name On used username: {"username":["A user with that username already exists."]} """ model = User queryset = User.objects.all() serializer_class = RegistrationSerializer permission_classes = [ permissions.IsAdminUser, ] Here's a link to views.py https://github.com/mehtamanan/TheMovieBook/blob/master/userprofiles/views.py if that helps. Does anyone know what I'm doing wrong or what direction should I head in to solve it? -
Django ImportError: cannot import name 'x'
I have problems with circularity in my two files. Model import function to run when create object and this function import model to check if code in unique. How use model in function and function in model without problem with circularity? I checked questions simillar to my problem but i still don't know to fix this issue. models.py from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from .middleware.current_user import get_current_user from shortener.utils import create_shortcode from django.conf import settings CODE_MAX_LENGTH = getattr(settings, 'CODE_MAX_LENGTH', 16) class Shortener(models.Model): url = models.URLField() code = models.CharField(unique=True, blank=True, max_length=CODE_MAX_LENGTH) author = models.ForeignKey(User, blank=True, null=True) # Allow anonymous created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) def save(self, *args, **kwargs): if not self.pk: self.author = get_current_user() if self.code in [None, ""]: self.code = create_shortcode() elif self.code.find(' ') != -1: self.code = self.code.replace(' ', '_') if self.url not in ["http", "https"]: self.url = "http://{0}".format(self.url) super(Shortener, self).save(*args, **kwargs) def __str__(self): return self.url def __unicode__(self): return self.url def get_short_url(self): return reverse("redirect", kwargs={'code': self.code}) Utils.py import random import string from django.conf import settings from shortener.models import Shortener SIZE = getattr(settings, 'CODE_GENERATOR_MAX_SIZE', 12) def code_generator(size=SIZE): return ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(size)) def create_shortcode(): … -
tastypie queryset values is not being displayed
I have this tastypie resource: class TagResource_min(ModelResource): class Meta: queryset=Question.objects.values('text', 'id') When I do this I have the error: error_message": "'dict' object has no attribute 'pk'", The 'dict' it is referring to must be the queryset obtained by Question.objects.values('text', 'id'). When I log into shell and ask for Question.objects.values('text', 'id') I have the following: <QuerySet [{'text': 'Why does capillary action take place?', 'id': 1}, {'text': "If a human brain was connected to a fish's body, how would the humans thoughts change?", 'id': 2},... What am I doing wrong by using objects.values()? How do I display a new queryset using objects.values()? -
How to allow only specific users to connect to a WebsocketConsumer in Django channels?
I use django channels. I define a JsonWebsocketConsumer: class Consumer(JsonWebsocketConsumer): http_user = True def connect(self, message, **kwargs): if not message.user.is_superuser: self.disconnect(message, **kwargs) But this doesn't work. Any user can connect and send data that receive(self, text=None, bytes=None, **kwargs) method will handle. How can I allow only specific users to connect? -
Django race condition test with before_after
I have finished the Django polls tutorial I wanted to continue on it by making a test to check for a voting race condition as mentioned here. I found a python package called before_after that can be used to make tests involving race conditions. However I don't understand the parameters for the before and after methods. I've looked over some examples and thought Choice.get_votes is what I needed for my first parameter, however that causes me to get ImportError: No module named 'Choice'. Does anyone know what I need to change in my test to get it to work? Here's the test I made: tests.py: import datetime from django.utils import timezone from django.test import TestCase from .models import Question, Choice import before_after def create_question(question_text, days): time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) class ChoiceTest(TestCase): def test_race_condition_avoided(self): self.assertEqual(self.creating_race_condition(), 2, "Votes do not equal amount expected.") def test_race_condition_occurred(self): self.assertNotEqual(self.creating_race_condition(), 1, "Votes do equal amount expected from a race condition.") def creating_race_condition(self): q = create_question('Did the race condition happen?', 0) self.choice = q.choice_set.create(choice_text="Let's find out.", votes=0) with before_after.after('Choice.get_votes', self.increment_vote): self.increment_vote() return c.votes def increment_vote(self): self.choice.votes += 1 self.choice.save() def get_votes(self): return self.choice.votes models.py: import datetime from django.utils import timezone from django.db import … -
Django and c9.io - connection refused?
First of all, Merry Christmas to those that celebrate it. I'm an absolute newbie to Django, currently working on my first project, and I'm having trouble running my code. More specifically, when I start the server using python manage.py runserver localhost:8000, it appears to connect, giving me: System check identified no issues (0 silenced). December 25, 2016 - 00:30:23 Django version 1.9.4, using settings 'deanslist.settings' Starting development server at http://localhost:8000/ Quit the server with CONTROL-C. And nothing else. However, in my browser window, going to localhost:8000 gives me an ERR_CONNECTION_REFUSED error. This has happened on every other port I've tried as well. I can't for the life of me figure out what's going wrong. Anyone else have any ideas? For the record, my manage.py looks like this: import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "deanslist.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) And the script I used to set up my virtual environment looks like this: LogFile=./setup_log ErrFile=./setup_err # Detect the platform OS="`uname`" case $OS in 'Linux') OS='Linux' ;; 'Darwin') OS='Mac' ;; 'AIX') ;; *) ;; esac function install_mac_dependencies() { brew update brew upgrade brew prune brew install python3 if [ $(xcode-select -p) == 2 ] then xcode-select --install fi … -
Django URL to View Mapping Issue
I am attempting to utilize this ModelViewSet using the Django REST Framework. I want to add some additional functionality to a UserViewSet that I created, but I can't seem to get the URL to map to the View method properly. What am I doing wrong in the URL or View? I expect a sample URL to look something like this 127.0.0.1/users/create/?username=sean&password=jacob123. but I am ultimately doing this 127.0.0.1/users/create/sean/jacob123/ Error Received when using 127.0.0.1/users/create/sean/jacob123/ TypeError at /users/create/sean/jacob123/ create() got an unexpected keyword argument 'username' Request Method: GET Request URL: http://127.0.0.1:8080/users/create/sean/jacob123/ Django Version: 1.10.4 Exception Type: TypeError Exception Value: create() got an unexpected keyword argument 'username' Exception Location: C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handlers\base.py in _get_response, line 185 Python Executable: C:\Program Files (x86)\Python35-32\python.exe Python Version: 3.5.1 Python Path: ['C:\\Users\\Sean\\OneDrive\\Projects\\myapi', 'C:\\Program Files (x86)\\Python35-32\\python35.zip', 'C:\\Program Files (x86)\\Python35-32\\DLLs', 'C:\\Program Files (x86)\\Python35-32\\lib', 'C:\\Program Files (x86)\\Python35-32', 'C:\\Users\\Sean\\AppData\\Roaming\\Python\\Python35\\site-packages', 'C:\\Program Files (x86)\\Python35-32\\lib\\site-packages'] Server time: Sat, 24 Dec 2016 22:32:19 -0500 I have limited knowledge of the Views, so perhaps I should be just looking to create a functional view instead of a class based view. VIEW class UserViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = User.objects.all() serializer_class = UserSerializer def create(self, request): user = … -
when update Image fields, then initial data does not work
try: info_user = my_image initial_data = { 'web_site': info_user.web_site, 'biography': info_user.biography, } info = UserInfoForm(request.POST or None, instance=info_user, initial=initial_data) except: info = UserInfoForm(request.POST or None) if info.is_valid(): new_info = info.save(commit=False) new_info.user = request.user new_info.save() return redirect('/index/') above the code, if there is initial datas then I showed the datas in page then we can make changes if we want, and the initial data works very fine try: info_user = my_image initial_data = { 'web_site': info_user.web_site, 'biography': info_user.biography, } user_form = UserInfoForm(request.POST or None, request.FILES or None, instance=info_user) except: user_form = UserInfoForm(request.POST or None, request.FILES or None) if user_form.is_valid(): form = user_form.save(commit=False) form.user = request.user form.save() return redirect('/'+str(request.user.username)+'/') but above the code, if I save any images in model then all type textfields are gone in model I have 1 image field 2 text field, but text fields and image field stays in different page but it does not make trouble, because textfields and image field is null true blank true, in text field's page if I save then everything is saved even if image field has image then images are not gone, but in images field's page if I save image then all text fields are gone, I am crazy … -
Django get_or_create throwing integrity errors
I'm so confused as to why the get_or_create() method should throw error here, I have this in my serializer: def create(self, validated_data): user, _ = User.objects.get_or_create(id=validated_data['message']['from_user']['id'], defaults=validated_data['message']['from_user']) chat, created = Chat.objects.get_or_create(id=validated_data['message']['chat']['id'], defaults=validated_data['message']['chat']) message, _ = Message.objects.get_or_create(message_id=validated_data['message']['message_id'], defaults={'message_id': validated_data['message']['message_id'], 'from_user': user, 'date': validated_data['message']['date'], 'chat': chat, 'text': validated_data['message']['text']}) update, _ = Update.objects.get_or_create(update_id=validated_data['update_id'], defaults={'update_id': validated_data['update_id'], 'message': message}) return update It says that: {u'from': {'id': [u'User with this id already exists.']}, u'chat': {'id': [u'Chat with this id already exists.']}} I have checked other threads, but the solution they all gave is what I already have in my code so I'm really confused -
How to create a single
I've successfully learned some basics of Celery, but I've found no simple way to create single file executable (with no need to run celerybeat as a seperate process to run periodic tasks). It is possible to write an app and start its worker process (http://docs.celeryproject.org/en/3.1/userguide/application.html): from datetime import timedelta from celery import Celery app = Celery() @app.task def test(): print("he-he") app.conf.update( BROKER_URL="redis://localhost:6379", CELERY_RESULT_BACKEND="redis://localhost:6379", CELERY_ACCEPT_CONTENT=["application/json"], CELERY_TASK_SERIALIZER="json", CELERY_RESULT_SERIALIZER="json", CELERYBEAT_SCHEDULE={ 'runs-every-30-seconds': { 'task': '__main__.test', 'schedule': timedelta(seconds=30), }, } ) if __name__ == '__main__': app.worker_main() But how can I start the beat process from the same module to start runnning periodic tasks (in order not to run celerybeat daemon as a separate executable)? It's important, because I'd like to use pyinstaller, so no dedicated Python interpreter will be available on client machines. Thanks in advance! And let me wish you a Merry Christmas and a Happy New Year! -
Django ImageField widget that accepts upload or external link as source
Is there a Django widget for ImageFields that provides the option to either upload an image or provide a url? I'm thinking like Summernote does (if you click the image icon) in its examples I've browsed through many apps and they are all focused on just uploading and thumbnailing. -
Using HttpResponseRedirect() in a Django view where context has to be passed
In this Django app of mine, I use a ListView class to list user-uploaded photos. One can upvote or downvote these photos. An unignorable section of my users use legacy devices that can't support JS. For such users, upvote or downvote isn't AJAX-enabled. Instead, the entire page refreshes. I ensure the page refresh still lands such users on the same photo they voted. I do this via the <a name="section{{ forloop_counter }}"> tag in HTML. I show 20 photos per page, i.e. 20 sections. Upon voting, I pass the photo_id to def get(self, request, *args, **kwargs) method of ListView class. I calculate which section_num the photo_id appears in. Then I simply do return HttpResponseRedirect(section_num). This lands me at the correct position, e.g. http://example.com/?page=1#section8. My question is: instead of using a ListView class, assume I'm writing my own custom view to list out the photos and such. How do I implement the aforementioned HttpResponseRedirect(section_num) functionality in this case? An illustrative example would be great. Thanks in advance! Here's my custom view: def photos_list(request, *args, **kwargs): form = PhotosListForm() ob_list = retrieve_latest_photos(request.user.id) paginator = Paginator(ob_list, 20) page = request.GET.get('page', '1') try: page = paginator.page(page) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page … -
Django channels run three workers, is it normal?
I have a very simple setup of django project with channels using documentation https://channels.readthedocs.io/en/stable/getting-started.html In settings: CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", "ROUTING": "core.routing.channel_routing", }, } In rounting.py: from channels.routing import route from apps.prices.consumers import get_prices channel_routing = [ route('get_prices', get_prices), ] And when i run: python manage.py runserver it prints: 2016-12-24 23:49:05,202 - INFO - worker - Listening on channels get_prices, http.request, websocket.connect, websocket.receive 2016-12-24 23:49:05,202 - INFO - worker - Listening on channels get_prices, http.request, websocket.connect, websocket.receive 2016-12-24 23:49:05,203 - INFO - worker - Listening on channels get_prices, http.request, websocket.connect, websocket.receive 2016-12-24 23:49:05,207 - INFO - server - Using busy-loop synchronous mode on channel layer And three workers seems that something went wrong, or it is normal? But everything else works fine. Big thx for advices -
Static files are not loaded. Deploying Django app to VPS with Ngnix and Gunicorn
It's my first time I am trying to deploy django project to Digital Ocean droplet(instance) and set up with Gunicorn and Nginx. I'v got problem with static files because there are not loaded. It seems I messed things up because in tutorials static is usually located in (in my case) glboy/ and localy in my project it was located in glboy/app/. So I now there is folder /root/glboy/static and everything is copied there by python manage.py collectstatic . I can't understand what is wrong. I tried various things and after every edit restarted after every change sudo service nginx restart but nothing helped. What is likely to be wrong? In sudo nano /etc/nginx/sites-enabled/closer: location /static/ { root /home/root/glboy/; expires 30d; } In sudo nano /etc/nginx/sites-available/default: location /static/ { root /home/root/glboy/; expires 30d; } In settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
Angularjs not working in Chrome but working in Firefox
I have been developing on firefox & the code works fine but when I tried to test on Chrome it just displays the {{err_msg}} which means angular is not working. I am using Django 1.10 server with Rest Framework for managing get requests from the Angularjs 1.5.9 code. I tested on Firfox, Midori & Chrome. It only works on Firefox! my app: 'use strict'; var givemecouponApp = angular.module('givemecouponApp', []); givemecouponApp.controller('CouponsCtrl', ['$scope', '$http', 'givemecouponService', function CouponsCtrl($scope, $http, givemecouponService) { $scope.finderloader=true; $scope.err_msg = 'no error'; var myDataPromise = givemecouponService.getData(); myDataPromise.then(function(result) { if(result.data == "Not a valid course!" || result.data == "No course passed!"){ $scope.err_msg = result.data; }else{ $scope.coupons = result.data; } }, function ( result ) { if(result.status == 429){ $scope.err_msg = "Too many requests!"; } // TODO: handle the error somehow }).finally(function() { // called no matter success or failure $scope.finderloader = false; }); }]); //service for getting coupon codes givemecouponApp.factory('givemecouponService', function($http) { var getData = function() { // Angular $http() and then() both return promises themselves return $http({method:"GET", url:slug_json_url}).then(function(result){ // What we return here is the data that will be accessible // to us after the promise resolves return result; }); }; return { getData: getData }; }); {% load … -
How to write/read the online file's data to/from python without downloading the file?
I am trying to write a program in Python 3.5 that will be the main interaction between Teachers and Students. The Teachers will be able to Upload test marks and attendance from their PCs and Students will be able to check out their scores and whole report on their home.i.e It is a Student Portal Type App. The Whole code is written and is working. Now the final and most difficult part is that I have to take the data online. I want my Python app to: Automatically Update the Online File if the teacher makes some update to it. Show the Student's their report without Downloading the file. I do have a dropbox account and I want to keep the data file there. CAN ANY ONE HELP ME PLEASE ?? -
FATAL: password authentication failed for user
I use this tutorial with Python 3.5, Django 1.9, Linux Mint and PostgreSQL 9.3. But when I try "manage.py migrate" I have an error: django.db.utils.OperationalError: FATAL: password authentication failed for user "myprojectuser" My database settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'xxxxx', 'HOST': 'localhost', 'PORT': '', }}