Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a code run while a view is open in Django
I am wondering how I could get tasks running, but They will not be doing nothing until I allow by doing some action in another device that is recognized by django, but meanwhile I will need to have these tasks running while I have a view open and the actions of these tasks will make some changes in the view, for example playing a sound, changing css's proprieties. I have looked for some informations about how I could do that, I found the Celery, but It only sets up tasks to be carried out in a certain time. If you guys could explain how this can be possible and provide some resources so I can learn I'd be very grateful. -
Dealing with participant variables and players
I am currently programming an experiment on oTree, constructing for the first app of my two stages experiment on the "quiz" pre-installed app. I would like to rank the results of the participants in the subsession and calculate for each of them the percentile in which they are placed. I did so creating first a dictionary and then, after using the function sorted(), I got a list of tuples, structured like this: sorted_d = [(<Player 3>, 2, 0.33), (<Player 1>, 4, 0.66),...]. I would need now to assign to each participant the corresponding percentile in which they are placed, which is the last element in each tuple. I did so by creating the following method in the class: def player_perc(self): for i in range(0, Constants.players_overall): if self.subsession.sorted_d[i][0] == self.in_all_rounds()[0]: self.participant.vars['percentile'] = self.subsession.sorted_d[i][2] self.show = self.participant.vars['percentile'] However in the database, in "show", I cannot find anything. (Clearly I called the method later in views.py). I am quite sure that the equivalence relationship should be correct, but apparently something is not worked. Is there a way to debug this, while the session is running? Because the only thing I found at the moment is the otree shell, which however cannot be called … -
Error Killed: 9 after command "git add ."
I have a problem when I do "git add ." I received an error message "Killed: 9". If I try again "git add ." I received an another error: fatal: Unable to create './crmeasy/.git/index.lock': File exists. Another git process seems to be running in this repository, e.g. an editor opened by 'git commit'. Please make sure all processes are terminated then try again. If it still fails, a git process may have crashed in this repository earlier: remove the file manually to continue. If I delete ./.git/index.lock file and try again I receive the same cycle of errors. I try to commit new empty Django project virtualenv dir. How could I solve the issue? -
Django channels work on local but not on server, Error during WebSocket handshake
Website is loading fine but the channels are not working. In console I get: WebSocket connection to 'ws://fortests.ovh/8' failed: Error during WebSocket handshake: Unexpected response code: 404 Server: Ubuntu 16.04 on Digital Ocean nginx version: nginx/1.10.0 (Ubuntu) Redis server v=3.2.8 my settings.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, 'ROUTING': 'slist.routing.channel_routing', } } wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "slist.settings") application = get_wsgi_application() consumers.py import json from channels import Group from channels.auth import channel_session_user_from_http, channel_session_user from .models import Item # Connected to websocket.connect @channel_session_user_from_http def ws_add(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the users group Group("users").add(message.reply_channel) routing.py from channels.routing import route from tobuy.consumers import ws_add, ws_receive, ws_disconnect channel_routing = [ route("websocket.connect", ws_add), route("websocket.receive", ws_receive), route("websocket.disconnect", ws_disconnect), ] js var socket = new WebSocket('ws://' + window.location.host + '/' + {{ active_list.id }}); nginx settings server { listen 80; server_name server_name fortests.ovh; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/kuba1/slistproject/slistvenv/src; } location / { include proxy_params; proxy_pass http://unix:/home/kuba1/slistproject/slistvenv/src/slisock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } -
Python_Django - Adding Attending Event option - How to?
There are 3 models in my web application. Event (self-made), User (imported from django.contrib.auth.models) and EventAttendance (self-made). EventAttendance is a table which connects Event and User table (through foreign keys person_key and event_key). I would like to create a button which will connect the user (the one who is logged in) and the Event. It should insert a line into the table EventAttendance. I was trying to make it work but unfortunatelly it is not doing anything. Right now i am able to put data into EventAttendance table just through the ADMIN tab. Could somebody please check my code and give me some advices? MODELS class Event(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) place = models.CharField(max_length=100) start = models.DateTimeField() price = models.IntegerField() text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class EventAttendance(models.Model): person_key = models.ForeignKey(User, on_delete=models.CASCADE) event_key = models.ForeignKey('Event', on_delete=models.CASCADE) attended = models.BooleanField() def __str__(self): return "%s - %s" % (self.event_key, self.person_key) FORMS` class EventForm(forms.ModelForm): class Meta: model = Event fields = ('title', 'text','place','start','price',) class EventAttendanceForm(forms.ModelForm): class Meta: model = EventAttendance widgets = { 'event_key': forms.HiddenInput(), } fields = ['person_key', 'event_key', 'attended',] class UserCreateForm(UserCreationForm): email = … -
How to make a query on a django model passed as a function parameter
Having my models defined class Model1(models.Model): description = models.TextField() some_attribute_1 = models.IntegerField class Model2(models.Model): description = models.TextField() some_attribute_2 = models.CharField(max_length=10) I want to build a function : def my_function(model, desc): return model.objects.filter(description = desc) And use it as str1 = my_function(Model1, "some description") str2 = my_function(Model2, "some description") -
Apache server conflicting with Django runserver command (httpd.conf)
About a year back I was playing around with my Apache server on my Mac and edited the httpd.conf file. Recently I installed Django and wanted to begin with a project, but when I use the python manage.py runserver and refresh the page, I don't get the typical Django page (It works, then with more details on Django and debugging etc.) but instead the Site "It works!" without further information. So I did "sudo apachectl stop", and this didn't resolve anything either. I suspect it is because of a change I made to the http.conf file, but unfortunately I don't know what parameter to change/comment out etc. How can I overcome this issue? -
Create a dynamic Django form based on a model to load another model
I'm new to Python and Django, and have managed to get myself very lost and confused, so any help would be much appreciated. I come from a database background, so my thinking is very model based. (Sorry my code is a mess now and completely off track so I haven't posted it). Scenario: I want to create a form that lets people assign a quantity of items to a certain user. I want to use the Django auth User model as a drop down for selecting the user. And then have a set list of items as the label, with a user entry field to enter the quantity of each item assigned to that user. At the bottom of the form, I want people to be able to add a new item and quantity if needed. My thinking is I have the Django User model for selecting the user, a Item model with a pre determined list of items, and UserItemTally model for writing the results to (with each record having user, item and quantity) and a UserEnteredItems model for recording any additional items entered in the form. AS I said, I have become very confused with trying to put … -
Call a soap WS from django using a simple search form
In a Django project,in my html page i have a simple form <form method="get" action="/search/"> Search Book: <input type="text" name="q" id="id_q" value="{{ query }}"/> <input type="submit" value="Search" /> and then in views.py i have <form method="get" action="/search/"> Search Book: <input type="text" name="q" id="id_q" value="{{ query }}"/> <input type="submit" value="Search" /> my web service method is below : def get_isbn(title): return client.service.show_book(title) How can i call the method get_isbn and insert it in views.py? Any ideas?Thanks -
Django CMS - ImportError: No module named markdown
This one I hope is quite a simple issue - but may be made a little more complicated by the fact that I am using the Divio Django cms service. I'm using Python 2.7.11 and Django 1.11.1 for all the egg heads out there that care about these things. Essentially my app is failing to find the Markdown package: import markdown or from markdown import markdown or from markdown import * or even (this is getting fancy) try: from markdown import markdown except ImportError: class MarkdownNotFound(Exception): def __str__(self): return "Uuuugh, why isn't this simple thing working" raise MarkdownNotFound All will give the general error: ImportError: No module named markdown (Obviously, all with slightly different wording). Uuuugh, why isn't this simple thing working? I've pip installed markdown until the cows come home...so it's there. Just can't be found by my Django project. import datetime works without issue. Is there something I am missing which is quite simple or, if not, are there any alternatives to the markdown module in Django that actually work from import? This is the full traceback: Traceback (most recent call last): File "manage.py", line 7, in <module> startup.manage(path=os.path.dirname(os.path.abspath(__file__))) File "/virtualenv/lib/python2.7/site-packages/aldryn_django/startup.py", line 11, in manage utility.execute() File "/virtualenv/lib/python2.7/site-packages/django/core/management/__init__.py", … -
Prevent object creation when unique_together is set in Django
models.py class Registrierung(models.Model): kategorie = models.ForeignKey(Kategorie) sportler = models.ForeignKey(Sportler) date_added = models.DateTimeField(auto_now_add=True) class Meta: unique_together = (('kategorie', 'sportler'),) views.py def registrieren_user(request, kategorie_id): kategorie = get_object_or_404(Kategorie, pk=kategorie_id) user = get_object_or_404(User, pk=request.user.id) reg = Registrierung(kategorie=kategorie, sportler=user.account.sportler) reg.is_valid(): reg.save() return HttpResponseRedirect(reverse('events:events')) Hi, I am trying to prevent duplicates in my database. If I make a duplicate entry of Registrierung in the admin-panel, I receive an error message that I can't create an object because of the unique_together relation. How can I get this functionality in my view? Every execution of registrieren_user is saved, though it should not be possible. -
User with permission to modify only one field of the model in the Django Admin
I have a user named ExpertUser who should only be able to modify an attribute of the called model (money) of the users in the Django Admin. I have tried adding permissions in the model using the Meta but when entering with that permission I can not modify anything since I do not have access to any user. My model is this: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) money = models.FloatField(default=1000) def __str__(self): return self.user.username class Meta: permissions = (("can_view_money", "Can view money"),) -
How to filter users depending on a models.charfield choices in django
so i currently have this as my profile model for each user. class Profile(models.Model): user = models.OneToOneField(User) location = models.CharField(max_length=120, choices=LOCATIONS,null=True, blank=True) picture = models.ImageField(upload_to=upload_location, null=True, blank=True) how to i filer users depending on the choices given in the location field? So for example if the current user has London selected, in the template they will only see results of users/profiles with the same location. Do i have to create an if statement or a for loop in the views.py? or do i use a q lookup? if anyone could give me some pointers or show me in the right direction that would be amazing! thank you for any help in advance -
Is there a way to document the composition of an object required in a POST request using Django Rest Swagger?
Let's say I have an endpoint for creating Player that requires a Team object: models.py class Team(Model): name = CharField() class Player(Model): name = CharField() team = ForeignKey(Team) And I have a ModelViewSet as follows: views.py class PlayerViewSet(ModelViewSet): model = Player serializer = PlayerSerializer serializers.py class TeamSerializer(ModelSerializer): class Meta: model = Team fields = "__all__" class PlayerSerializer(ModelSerializer): class Meta: model = Player fields = "__all__" When I look at my Django Rest Swagger, the "Example value" for data I need to POST to create a player looks like: { "name": "string", "team": {} } What I want is for the {} to be expanded, to show that I would need to provide a {"name": "string"} object to create the Team object. I've tried adding team = TeamSerializer(help_text="{'name': 'string'}") to the PlayerSerializer but that only adds the data to the Model tab on Django Rest Swagger. Is there a way to add this documentation automatically to the Example tab and Model showing the required POST data? -
Understanding the Client's Responsibilities in OAuth 2.0
I've been trying to learn the inner workings of OAuth 2.0 in my own RESTful app, and I can't seem to find any good explanation of how my Javascript client handles the process. At this point, I have the client (an Angular 2 SPA) ask the user for their username and password (running Django Rest Framework along with Django Oauth Toolkit). The client makes an AJAX post to the server (specifically to /o/token), and using the resource owner password credentials flow is authenticated and receives the response with the token. Now, assuming I'm doing everything correctly up to this point, I'm unsure how to properly handle the token from that point forward. At this point, I'm having my Angular app save the token in a variable and attach the authorization header (with the token) to the calls made to the API. This works as far as granting the correct permissions, but im having a hard time understanding how to maintain persistence of the header (so if the user navigates to a different page, the token is still callable). Initially I stored it in a cookie, but I have concerns with security. So, first, am I understanding all this correctly? What … -
MySQL select_for_update() and triggers .. how blocking works?
I have a row with an integer value, there're many concurrent requests on that row, I want that every read operation to be followed by an update operation (increment), and keep the data consistent, only one request can read->update at the same time. I've made some research and figured out the select_for_update(), and I also thought of making a trigger on SELECT to increment the value AFTER it's selected, the question is .. Will that work as I'm assuming? Is the trigger working in parallel or is it consistent this way? -
Apache Cordova file-transfer to django backend
I am trying to send over a picture with the apache cordova file-transfer plugin to an django based backend. When I submit a picture via the file-transfer plugin in the backend, it doesn't recognize any of the parameters. function uploadPhoto(imageURI) { var options = new FileUploadOptions(); options.fileKey = "file"; options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1); options.mimeType = "image/jpeg"; var params = {}; params.value1 = "test"; params.value2 = "param"; options.params = params; var ft = new FileTransfer(); ft.upload(imageURI, encodeURI("http://127.0.0.1:8000/declare/"), win, fail, options); } reqeust.FILES, request.POST, request.GET everything are empty dictionary. When I submit the url to a hookbin it seems to recognize everything though. What could be the problem why django keeps the request.FILES etc empty? @csrf_exempt def declare(request): me = User.objects.get(username='test') response = JsonResponse({'success': "ok"}) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "*" return response -
how to configure vi/vim for django development?
I have used many text editors and IDE's but I find Vim/Vi more suitable for myself. For betterment I have used plugins like YouCompleteMe and made my .vimrc file but I need to configure vim to be completely supporting my django web development. Please do answer with any enhancements or plugins I can use to make it more better. Below is my .vimrc Note: I'm still learning if I'm wrong somewhere please do pardon me 1 set nocompatible 2 filetype off 3 set rtp+=~/.vim/bundle/Vundle.vim 4 call vundle#begin() 5 6 " Let Vundle manage itself" 7 8 Plugin 'VundleVim/Vundle.vim' 9 10 "Plugins" 11 Plugin 'Valloric/YouCompleteMe' 12 13 call vundle#end() 14 filetype plugin indent on 15 16 "Color Scheme" 17 colorscheme badwolf 18 "colorscheme goodwolf" 19 20 21 "Pathogen Vim" 22 execute pathogen#infect() 23 24 "Enabling syntax higlighting" 25 syntax enable 26 27 "show line numbers" 28 set number 29 30 "set tabs to have 4 spaces" 31 set ts=4 32 33 "Auto Indent" 34 set autoindent 35 36 "expand tabs into spaces" 37 set expandtab 38 39 "when using >> or << commands, shift lines by 4 spaces" 40 set shiftwidth=4 41 42 "set visual line under the cursor's current line." … -
How to set a deadline for POST requests based on related object?
I have two related model like this: Form: name fields date_deadline FormEntry: form = ForeignKey(Form) data I want to prevent adding new entry after submission deadline. I write a validation in serializer like this: class FormEntrySerializer(serializers.ModelSerializer): def validate(self, data): from datetime import datetime form = data.get('form') if form.date_deadline and\ datetime.date(datetime.today()) > form.date_deadline: message = 'Entries can\'t be added after submission deadline.' raise serializers.ValidationError(message) return data class Meta: model = FormEntry fields = ( 'id', 'form', 'data', ) It works but I can't update an form entry too after submission deadline. I want to make this validation only for POST requests (means new insertions). Also I'm not sure this is the best way to do it. Maybe I must use permissions. How I do it? -
Optimal way to count total of list comprehension result in django
I have a list comprehension in my view I use since I have to filter based on model calculated fields. tobe_payed_terms = [obj for obj in leaseterms if obj.current_balance < 0] I use it to display all the fields in my report. Currently I have to add a dashboard where I just want to display count of total units of this list comprehension. What is most performance wise optimal way of doing so? (I might have few cases like this in my dashboard) -
Django-Chart Circular request error
I'm trying to render a page using django-chartit by using models and examples provided by the Django-Chartit docs. My model looks like this. class MonthlySchedule(models.Model): ''' Monthly schedule for django-chartit statistics''' months = ( (u'jan',_('January')), (u'feb',_('February')), (u'mar',_('March')), (u'apr',_('April')), (u'may',_('May')), (u'jun',_('June')), (u'jul',_('July')), (u'aug',_('August')), (u'sep',_('September')), (u'oct',_('October')), (u'nov',_('November')), (u'dec',_('December')) ) programme = models.ForeignKey(Redaktion, related_name='red_monthly', null=True, on_delete=models.CASCADE) year = models.CharField(_('Year'), max_length=4, blank=False, default=year) month = models.CharField(_('Month'), choices=months, max_length=3) current_size = models.DecimalField(_('Current size(TB)'), max_digits=4, decimal_places=1, blank=True, null=True) target_size = models.DecimalField(_('Target size(TB)'), max_digits=4, decimal_places=1, blank=True, null=True) def __str__(self): return '' class Meta: verbose_name = (_("quota")) verbose_name_plural = (_("quotas")) and my views look like this... @staff_member_required def ChartitSchedule(request, red=None): '''Monthly disk Quotas''' ds = DataPool( series=[{ 'options': { 'source': MonthlySchedule.objects.filter(programme__pk=red) }, 'terms': [ 'month', {'Current Size': 'current_size'}, 'target_size' ] }] ) cht = Chart( datasource=ds, series_options=[{ 'options': { 'type': 'line', 'stacking': False }, 'terms': { 'month': [ 'target_size', 'Current Size' ] } }], chart_options={ 'title': { 'text': 'Disk Quotas' }, 'xAxis': { 'title': { 'text': 'Month' } } }) return render(request, 'sysadmin/chartit.html', {'this_chart': True, 'these_quotas':cht}) and my template looks like this.... {% extends 'base2.html' %} {% block title %}Programme Quotas{% endblock %} {% load static %} {% block add_to_header %} {% load chartit %} {{ these_quotas|load_charts:"container" }} … -
django-guardian refuses to acknowledge permissions when form is used
I'm using django-guardian to assign per-object permissions between register.GeneralUser and butler.Business models. If I create a business and a user in shell, and then use assign_perm to assign a permission, django correctly reports that user.has_perm("permission", business) is True. This is also the behavior when a user and a business are create via django's admin-system. However, for user's and their corresponding businesses created through a django-registration form, guardian will always report permissions as False, even though they do exist in the db table! Meaning: guardian is assigning the permissions, but is always reporting them as False. I've tried countless of ways to solve this, but to no avail. This is leading me to think that my fairly standard form is somehow flawed, and it's confusing guardian for some reason. Here's my register/forms.py: from registration.forms import UserCreationForm from butler.models import Business from register.models import GeneralUser from django import forms class GeneralUserForm(UserCreationForm): business_name = forms.CharField(required=True) class Meta: model = GeneralUser fields = ['username', 'email', 'password1', 'password2', 'business_name'] def save(self, commit=True): user = super(GeneralUserForm, self).save(commit=True) print(user) user.set_password(self.cleaned_data["password1"]) business = Business(name=self.cleaned_data['business_name'], owner=user) print(business) user.save() business.save() return user Here's a link to my GeneralUser model. If I now query the user and business created through this … -
Django serialization - does is_valid() hit database?
I am using Django 1.10, and now have to optimize the speed of my app. I was just playing with the code trying to find the bottlenecks, and came across a strange code behavior. I have the following view: @api_view(['POST']) def test(request): for record in request.data: serializer = TestTableSerializer(data = record) if serializer.is_valid(): a = 1 ...a model: class TestTable(models.Model): client_id = models.IntegerField() value = models.CharField(max_length = 1) class Meta: managed = False db_table = 'test_table' ...and a serializer: class TestTableSerializer(serializers.ModelSerializer): class Meta: model = TestTable fields = '__all__' The strange thing is that when I run test view from, say, restlet client, it takes 3.6 (!!!) seconds for 2000 rows to execute the view. However, when I remove if serializer.is_valid(): statement, the query is executed instantly. Is it normal for 2000 rows to validate in 3 seconds ? Or there's something under the hood that is wrong in my code elsewhere ? P.S. I would expect to validate AND INSERT 2000 rows instantly: @api_view(['POST']) def test(request): for record in request.data: serializer = TestTableSerializer(data = record) if serializer.is_valid(): serializer.save() -
Django cannot detect my translation under app/locale
My project name is fellow_go and I'm working with an app called pickup. In setting.py, LANGUAGE_CODE is set to 'zh-hans', and django.middleware.locale.LocaleMiddleware is installed. I have a *.po file containing translations at pickup/locale/zh-Hans/LC_MESSAGES/django.po, and django-admin compilemessages has been run several times, which creates a django.mo under the same directory. Despite these efforts, the localization doesn't work. To figure out what's wrong, I wrote a test view: def get_lang(request): from django.utils import translation lang = translation.get_language() return HttpResponse(lang) the result is zh-hans. Also, as you can see from the screenshot, some of the strings are translated actually. I suspect these translated string come from the Django-provided base translation in django/conf/locale. In case it's relevant, here is the result of a hexdump test. sunqingyaos-MacBook-Air:~ sunqingyao$ hexdump /Users/sunqingyao/PycharmProjects/fellow_go/pickup/locale/zh-Hans/LC_MESSAGES/django.po 0000000 23 20 53 4f 4d 45 20 44 45 53 43 52 49 50 54 49 0000010 56 45 20 54 49 54 4c 45 2e 0a 23 20 43 6f 70 79 0000020 72 69 67 68 74 20 28 43 29 20 59 45 41 52 20 54 0000030 48 45 20 50 41 43 4b 41 47 45 27 53 20 43 4f 50 ...... So, why can't Django discover and … -
django CKEditor not showing image upload
In a django application, target is to edit e-mail template in a WYSIWYG editor. Using CKEditor works fine, but images can only be included via URL, not via upload. A similar question is asked here: Django-CKEditor Image Upload What is not covered there is the case where a Form Field is used, not a Model Field. Also the accepted solution is not really explained. Current code: from django import forms from crispy_forms.helper import FormHelper class EmailConfirmationTemplateForm(forms.Form): def __init__(self, *args, **kwargs): self.email_template = kwargs.pop('email_template') kwargs.setdefault('initial', {})['email_template'] = self.email_template super(EmailConfirmationTemplateForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.fields['email_template'] = forms.CharField(widget=CKEditorWidget()) Template code: ... <form> {% csrf_token %} {% crispy form %} </form> Settings: INSTALLED_APPS = [ ... 'ckeditor', 'ckeditor_uploader', ... ] CKEDITOR_UPLOAD_PATH = 'cke-uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' Question is: How to have the possibility to upload images in this WYSIWYG editor? Version Info: django 1.8.16, django-ckeditor 5.2.2