Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change response format of Django auth login api
I am currently using Django-rest-framework-social-oauth2 and it's token(login) endpoint, which responds with the below data on success. { "access_token": "************", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "************", "scope": "read write" } But I want the change the format and wrap this data in such format: { "status" : true, "data" :{ "access_token": "************", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "************", "scope": "read write" } } I guess I need to extend the view used by the library but don't know how do I accomplish it. -
How do I configure PyCharm to use Django classes? How does Java's concept of classpath relate to Python?
I'm new to Python by way of Java. I'm getting what I would consider a classpath issue trying to use Django classes in a Pycharm project. How do I get my project to recognize the django.contrib.auth.models package? The following is the error message I'm getting: /usr/bin/python /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 127.0.0.1 --port 49963 --file /Users/tcl/_myproject/workspace/myprojectapi/django-nonrel/myproject/integration_tests/tests/bulk_import_validation.py pydev debugger: process 4747 is connecting Connected to pydev debugger (build 172.3317.103) Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1596, in <module> globals = debugger.run(setup['file'], None, None, is_module) File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1023, in run pydev_imports.execfile(file, globals, locals) # execute the script File "/Users/tcl/_myproject/workspace/myprojectapi/django-nonrel/myproject/integration_tests/tests/bulk_import_validation.py", line 1, in <module> from django.contrib.auth.models import User ImportError: No module named django.contrib.auth.models Process finished with exit code 1 -
How can I constantly send data using Django WebSockets?
I would like to constantly send data using Django WebSockets. At this moment I try in the way shown below. routing.py: channel_routing = [ route("websocket.connect", ws_connect), consumers.py: def ws_connect(message): message.reply_channel.send({"accept": True}) while True: message.reply_channel.send({ "text": json.dumps({ 'message': 'My response2' }) }) Unfortunately it doesn't work properly. Obviously without while True it send data but only once. Any ideas how can I solve it? -
Why django is not filtering null attributes?
Using Django 1.11 and PostgreSQL 9.5, I am experiencing the behavior above m = MyModel.objects.all() print(m) # > <QuerySet [<MyModel: MyModel object>]> m[0].details is None # > True m.filter(details__isnull=True) # > <QuerySet []> m.filter(details=None) # > <QuerySet []> The QuerySet clearly have a null field called details, but when I search for it, the answer is an empty query set. Anyone have any idea of what can be happening? -
Saving Django multiple model instances using a population script only saves the instances created in the last iteration
I'm trying to make some practice with Django and write a simple blog application. I want to create my models using a script so I don't have to use the shell or the admin interface. Given the following code: def populate(): current_user = User.objects.get(username='testuser') blogger_data = {'user': current_user,'bio':"this is my test bio", 'likes': 5,} blogger = add_blogger(blogger_data) print("Registered blogger : %s" %blogger.user) for num in range(5): post_data = {'author':current_user, 'title':"test title %s"%num, 'description': "test description%s"%num, 'content': "test content%s"%num,} posted_date = datetime.datetime.today() + datetime.timedelta(days=1) post = add_post(post_data,num,posted_date) comment_data = {'author':current_user, 'post':post,'content':"test content %s"%num, 'upvotes':num, 'downvotes':5-num,} comment = add_comment(comment_data) response_data = {'author':current_user, 'comment':comment, 'content':"test response %s"%num, 'upvotes':5-num, 'downvotes':num,} response = add_response(response_data) print("Saved post : %s, comment: %s, response: %s..." %(post,comment,response)) print("Script succesfully saved data!") The save() method of the corresponding model instance is being called in the corresponding function block and then returned. After running the script only the model instances created in the last iteration of the loop are being saved in the database. What is actually happening? -
How do I change field, when I use ChainedForeignKey?
My models: class Language(models.Model): ... class Group(models.Model): ... language = models.ForeignKey(Language, related_name='groups') item = ChainedForeignKey('Group', chained_field='language', chained_model_field='language', show_all=False, auto_choose=True, blank=True, null=True) ... class Root(models.Model): title = models.CharField(max_length=10) language = models.ForeignKey(Language) group = ChainedForeignKey(Group, chained_field='language', chained_model_field='language', show_all=False, auto_choose=True,) My forms: class RootForm(forms.ModelForm): class Meta: model = Root fields = ('title', 'language', 'group') def __init__(self, *args, **kwargs): super(RootForm, self).__init__(*args, **kwargs) self.fields['group'].queryset = Group.objects.filter(item=None) But in admin site I see all field "group" with all "item" (need only "item=None"). If I change field in class Root(): class Root(models.Model): ... group = models.ForeignKey(Group) ... everything works correctly. -
Django validation errors in semantic-ui with ajax
I can't understand how can I display the validation errors from django in semantic-ui using ajax. I'm trying to change password, but if it fails, I want to display the validation errors. I have this js code: $('.ui.form.password-change') .api({ action: 'password', method: 'post', serializeForm: true, dataType: 'json', onSuccess: function(data) { } }) .form({ fields: { old_password: ['minLength[4]', 'empty'], new_password1: ['minLength[4]', 'empty'], new_password2: ['minLength[4]', 'empty'], } }) ; I have this django code: class CustomPasswordChangeView(LoginRequiredMixin, PasswordChangeView): def form_valid(self, form): response = super(CustomPasswordChangeView, self).form_valid(form) if self.request.is_ajax(): data = { 'saved': 'Your password has been changed!' } return JsonResponse(data) else: return response def form_invalid(self, form): response = super(CustomPasswordChangeView, self).form_invalid(form) if self.request.is_ajax(): data = { 'bad': 'invalid form', } return JsonResponse(data) else: return response All is happening on 'onSuccess' function and I can't figure out how can I display validation errors like 'minLength[4]' error or 'empty' error with custom rules or something like that. My english is bad, don't hesitate to ask if you haven't understand something! Thanks in advance for answers! -
Django REST Framework - Class UserSerializer missing "Meta.model" attribute
I am following the tutorial of Django REST Framework, all is well until part 4 - Authentication & Permissions -> Adding login to the Browsable API, I want to browser the users I have created through url http://localhost:8024/users/. But I get this error message: AssertionError at /users/ Class UserSerializer missing "Meta.model" attribute Request Method: GET Request URL: http://localhost:8024/users/ Django Version: 1.10 Exception Type: AssertionError Exception Value: Class UserSerializer missing "Meta.model" attribute Exception Location: C:\Python27\lib\site-packages\rest_framework\serializers.py in get_fields, line 976 Python Executable: C:\Python27\python.exe Python Version: 2.7.11 Python Path: ['D:\\github\\py2\\dj-rest\\tutorial', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] Server time: Thu, 10 Aug 2017 11:41:38 +0000 But I do have class Meta in my UserSerializer class as showing in "serializers.py" file, please have a look and give me a help. Serializer.py # serializers.py from rest_framework import serializers from snippets.models import Snippet from django.contrib.auth.models import User class SnippetSerializer(serializers.ModelSerializer): # add a new field owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Snippet fields = ('id', 'title', 'code', 'file', 'linenos', 'language', 'style', 'owner') class UserSerializer(serializers.ModelSerializer): """ Because 'snippets' is a reverse relationship on the User model, it will not be included by default when using the ModelSerializer class, so we needed to add an explicit field for … -
Django Foreign Key Null and unqiue togehter , plus lowercase
I have a Category Model that has a Foreign to itself and can have Null values. I know that unique together doesn't work when Foreign key is Null. Also I want to check if they are duplicate, unique together indifferent of case(lower,up, combinations) and that the parent and the child to not have identical names. I found some partial solutions on the site but are not great and don't cover all my situations. Another thing, I do the clean on model, because I will have categories in Admin, so no form or view under my control. Now I have an error on 'name__iexact" and don't understand why because 'name==self.name" works. Also I search for better solutions that what I have now. self.pk=pk ; I check this because in case of update, it will find the current instance that I edit and trow ValidationError, which is not ok. > class Category(models.Model): > name = models.CharField(max_length=255) > parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category') > description = models.TextField() > > def __str__(self): > return self.name > > def clean(self): > cleaned_data = super().clean() > > if not self.parent: > exists = self.__class__.objects.filter(~Q(pk=self.pk), name__iexact=self.name).exists() > if exists: > raise ValidationError(_('Duplicate Category Name with … -
Socket.io in flask: Data from external source
I have a web application and need to continuously display the actions going on in the backend on the browser. I have been trying to use socket.io in Flask. But I need to get the data to be displayed from other Python modules in my project. So, I tried to make a socket connection between Flask and the external module from which I will be getting data to be displayed on the browser(without any delay). @socketio.on('my event') def server(message): s = socket.socket() print "Socket successfully created" port = 12345 s.bind(('', port)) print "socket binded to %s" %(port) s.listen(5) print "socket is listening" while True: c, addr = s.accept() print 'Got connection from', addr print c.recv(1024) emit('my response', {'data': c.recv(1024)}) c.close() print c.recv(1024) is printing data on the console. But the same data is not getting reflected on the browser. It's throwing this error - error: [Errno 98] Address already in use This means it's failing at emit after print c.recv(1024). What could be going wrong? My first doubt is if this kind of connection is allowed. I mean, can we have a socket connection created inside socket.io in Flask? Else, what is the best solution to display the backend actions … -
Remove/hiding username field in django admin edit user form
The frontend user signup form doesn't have username field as I am using email to login.Now I have access to django admin. When I edit an user I get that username field to edit but I do not want that field to be editable or view-able at all. admin.py -- from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import UserProfile class ProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'Profile' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) list_display = ('email', 'first_name', 'last_name', 'is_staff') list_select_related = ('profile', ) exclude = ('username',) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) forms.py -- from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Field from ajax_select.fields import AutoCompleteSelectField, AutoCompleteField from phonenumber_field.formfields import PhoneNumberField from . import models from captcha.fields import ReCaptchaField class SignUpForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) phone_number = PhoneNumberField(label=_("Phone (Please state your country code eg. +44)")) organisation = forms.CharField(max_length=50) email = forms.EmailField() password1 = forms.CharField(max_length=20) password2 = forms.CharField(max_length=20) captcha = ReCaptchaField(attrs={'theme' : 'clean'}) The django version is 1.10 so I … -
timeout and performance issues on redirecting inside django
I am currently having problems with Timeouts and performance on Django redirection. The issue was not visible until I was surfing to my locally hosted application with 2 devices and only one worker enabled on my localhost, timeout set to 30 seconds. I have a views.py function that redirects a page, based on that is given the URL. I do a lookup for the pk in a table and return the url. I also have a counter that keeps track of the amount of forwards. urls.py here: url(r'^i/(?P<pk>[-\w]+)/$', frontendapp_views.item_view, name="item_view"), The page redirects instantly to the "desired_url_forward", however, the connection stays open with the user, while in fact, the user has left my Django environment. This somehow leaves my worker waiting for 30 seconds while I was already forwarded to an external page, not allowing to process any other request with one worker. I could increase the number of workers or shorten the timeout time, but that doesn't feel right as it is not fixing the core issue. This is the only thing I found out on this topic but I am not skilled enough to understand this: https://github.com/requests/requests/issues/520 This is how the views.py looks like: def item_view(request,pk): pk_binairy = … -
running scheduled job in django app deployed on heroku
I have deployed a django app on heroku. So far it works fine. Now I have to schedule a task (its in the form of python script) once a day. The job would take the data from heroku database perform some calculations and post the results back in the database. I have looked at some solutions for this usually they are using rails in heroku. I am confused whether I should do it using the cron jobs extension available in django or using the scheduled jobs option in heroku. Since the application is using using heroku I thought of using that only but I dont get any help how to add python jobs in it. Kindly help. -
Default User test case fails to update username
The goal: I'm writing very simple unit test for profile update view (standard contrib.auth.User). Here is relevant snippet from ProfileView which I'm trying to test: if form.is_valid(): user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.email = form.cleaned_data['email'] user.username = user.email user.save() Here is my test case: class ProfileTestCase(TestCase): def setUp(self): # setup some user def test_profile_update(self): formdata = { 'first_name': 'Bruno', 'last_name': 'Schulz', 'email': 'bruno@schulz.pl' } request = self.factory.post('/accounts/profile', formdata) request.user = self.user response = ProfileView.as_view()(request) self.assertEqual(response.status_code, 200) self.assertEqual(self.user.first_name, formdata['first_name']) self.assertEqual(self.user.last_name, formdata['last_name']) self.assertEqual(self.user.email, formdata['email']) self.assertEqual(self.user.username, formdata['email']) # Fails The problem: For some reason the test fails at username check, i.e. all other data is updated successfully except for username (AssertionError: 'franz1883' != 'bruno@schulz.pl'). I'm 100% sure that view is working fine, I've checked it multiple times by hand. -
how to modeling a table as sql-server needs [schema_name].[table_name]
I have to read an existing SQL-SERVER database with Django FWK and after connecting succesfully to the DB, when I refer to MyModel.objects.all() Django launch a query with the table name quoted, but it fails because SQL-Server needs the prefix schema, getting the error: ('42S02', "[42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'table_name'. (208) (SQLExecDirectW)") How can I configure the model or the settings.DATABASE or the dbrouter to make django connect to the specific schema and don't need to use the schema_name? Option 1: model Meta class property: db_table = 'schema_name.table_name' doesn't work, because the query that builds has the FROM clause as [schema_name.table_name] and what sql needs is [schema_name].[table_name] Option 2: settings.DATABASE 'NAME' already refers to the schema_name, but it's not enough Option 3: no idea how to tell django to connect to the specific schema or to add the prefix schema name to all the queries it builds. -
Djanog two project but run one admin panel
i have two djanog project, first project name is dml and second project name is survey. when i run dml project from url it works fine (http://127.0.0.1:8000/dml/admin). but when i run survey project it does not work (http://127.0.0.1:8000/survey/admin) i have changed admin url in both projects. dml project url for admin: urlpatterns = [ url(r'^dml/admin/', admin.site.urls),] survey project url for admin: urlpatterns = [ url(r'^survey/admin/', admin.site.urls),] i would to like run this projects by different url. Here is my project structure screen short. -
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare
I am trying to run following command $ python app_ac/cron_scripts.py Error File "app_ac/cron_scripts.py", line 15, in <module> from django.contrib.auth.models import User File "/usr/lib/python2.7/site-packages/django/contrib/auth/models.py", line 6, in <module> from django.contrib.contenttypes.models import ContentType File "/usr/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 138, in <module> class ContentType(models.Model): File "/usr/lib/python2.7/site-packages/django/db/models/base.py", line 113, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. cron_scripts.py import os import re import sys import argparse from os.path import expanduser from os.path import join from os.path import basename from os.path import splitext from datetime import datetime import django from django.conf import settings settings.configure() django.setup() from django.contrib.auth.models import User import time def update_cron(): us = User.objects.get(username='onkar') now = datetime.now() us.first_name = now.strftime("%d%m%Y %H:%M") us.save() update_cron() settings.py Application definition INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', #'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'guardian', 'django_tables2', 'crispy_forms', 'adminlte_full', 'wkhtmltopdf', 'docs', 'app_ac', ] #import django #django.setup() #SITE_ID = 1 -
Django CMS Aldryn NewsBlog delete Articles from the frontend
I'm trying to get the standard Aldryn Newsblog Buttons working in my Frontend Page. So every User can Add, Delete and Edit Articles(only the articles they created themselves but thats not the question). This is the Menu with the links: Menu in the Toolbar So i want to add a Button in my template wich triggers the edit, add or delete prompt: Delete prompt I hope someone can help me. Thanks in advance. -
django] adding library in my 'lib' folder
Everyone. I'm a newbie in this field. I develops web application with google app engine using django framework. I have a troubleshot about python lib dir problem... ImportError: no module named... my appengine_config.py file is # [START vendor] from google.appengine.ext import vendor vendor.add('lib') # I believes this line is to add 'lib' folder to PATH. # [END vendor] my 'requirements.txt' file is MySQL-python==1.2.5 #app engine django project default Django==1.11.3 #app engine django project default django-twilio # add i want twilio # add i want and I installed using pip install -t lib -r requirements.txt ROOT ├── lib │ ├── django │ ├── pytz │ ├── wanttousing_lib │ └── ... ├── mysite │ ├── __init__.py │ ├── settings.py │ ├── controllers.py │ ├── models.py │ ├── views.py │ ├── templates │ └── .... ├── test │ ├── like │ │ ├── models_tests.py │ │ └── controllers_tests.py │ └── .... ├── static │ ├── css │ └── js ├── app.yaml ├── manage.py ├── appengine_config.py └── requirements.txt so, I installed in my project... but..compiled error. from wanttousing_lib import example_module importError wanttousing_lib.......... however, if I move my wanttousing_lib to ROOT dir, it works..... ROOT ├── lib │ ├── django │ ├── pytz │ │ … -
Deployment of django using nginx
Im using django 1.11. i have set up everything on server and my website work just fine, the problem is static files. i see django admin panel without any css or js. my settings in settings.py : BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') i run collectstatic and i got them in home/user/myproj/static here is my nginx.conf file : server{ listen 8000; server_name my ip access_log /var/log/nginx/example.log; location /static { root home/user/myproj; } } i also check django-static-file-and-nginx and django-serving-static-files-through-nginx , and tried 1000 times. it still loads without css. can anybody help me ? -
run code if subprocess ends processing
In my django view, i need to send email notification after subprocess is done because the script launched by subprocess is running some commands in background so the email is sent before the script is done, does anyone have an idea about how i could do this ? My view: def getor(request): # process subprocess.call("./step1.sh", shell=True) #send notification current_site = get_current_site(request) user = User.objects.values('username').order_by('id').last() us = user['username'] subject = 'Notification of end of watermark process.' message = render_to_string('notify.html', { 'us':us, 'domain':current_site.domain, }) eml = User.objects.values('email').order_by('id').last() toemail = eml['email'] email = EmailMessage(subject, message, to=[toemail]) email.send() return render(request, 'endexecut.html') -
How to get intersecting geometries with subquery in GeoDjango?
I'm trying to get all records from a table which geometry intersects with a geometry (with a given buffer) from the same table i get with a subquery. My working plain SQL statement is: SELECT id FROM table WHERE ST_INTERSECTS(geom, (SELECT ST_BUFFER(geom, 10) FROM table WHERE id = 1)); How can I achieve this with GeoDjango? -
What's the most elegant way to convert requests' response to DRF response in Django?
Consider the following flow: public client ----> DRF API on Service A ------> DRF API on Service B Some of the DRF API on Service A merely proxying to Service B, so in the particular API on Service A looks like this: class SomeServiceAPI(APIView): def get(request): resp = requests.get('http://service-b.com/api/...') return Response(resp.json()) While this works on normal status, but it has a few issues: It doesn't proxy the actual status code from service b. Unnecessary round-trip of json serialization within Response() The question is, is there a better way to do it? I had a look at Django Rest Framework Proxy project, but I am not entirely sure if it actually suits my use case here. -
Django: Forbidden (CSRF token missing or incorrect.)
My django version is 1.11.4, and I'm on a simple exercise in my book which I need to make a web page that people can submit their comments for a selected restaurant. But it shows the message Forbidden (CSRF token missing or incorrect.). views.py : def comments(request, id): if id != 0: r = Restaurant.objects.get(id = id) else: return HttpResponseRedirect('/restaurantsList/') if request.POST: dateTime = timezone.localtime(timezone.now()) Comment.objects.create( content = request.POST['content'], visitor = request.POST['visitor'], email = request.POST['email'], dateTime = dateTime, restaurant = r ) return render_to_response('comments.html', locals(), RequestContext(request)) comments.html : <!doctype html> <html> <head> <title>Comments</title> <meta charset='utf-8'> </head> <body> <h2>Comments for {{ r.name }}</h2> {% if r.comment_set.all %} <p>We have {{ r.comment_set.all | length }} comments</p> <table> <tr> <th>Visitor</th> <th>Time</th> <th>Comment</th> </tr> {% for c in r.comment_set.all %} <tr> <td>{{ c.visitor }}</td> <td>{{ c.dateTime | date:'F j, Y' }}</td> <td>{{ c.content }}</td> </tr> {% endfor %} </table> {% else %} <p>No comment</p> {% endif %} <br /><br /> <form action='' method='post'> {% csrf_token %} <table> <tr> <td><label for='visitor'>Visitor: </label></td> <td><input id='visitor' type='text' name='visitor'></td> </tr> <tr> <td><label for='email'>E-mail: </label></td> <td><input id='email' type='text' name='email'></td> </tr> <tr> <td><label for='content'>Comment: </label></td> <td> <textarea id='content' rows='10' cols='48' name='content'></textarea></td> </td> </tr> </table> <input type='submit' value='Submit'> </form> </body> I've … -
handle form request with ajax in django
i have problem with ajax when i send a request from my form it doesn't get the value from the form this is my view code def create(request): if request.method == 'POST': msg_text = request.POST.get('the_massage') data = {} form = ChatApp(message=msg_text, user=request.user) form.save() data['message']=form.message data['user']=form.user.username return JsonResponse(data) else: return JsonResponse({'nothing coming thrue'}) it shod get the_massage variable but it give me null value this is my ajax function : $(function () { var created = function () { console.log("create function is here"); var form = $(this); $.ajax({ url: 'create/', type: 'POST', data: {the_massage:$('#msgbox').val()}, dataType: 'json', success: function(json) { console.log(json); console.log('success'); }, error: function(error){ console.log('we have error'); }, }); }; $('#main-form').on("submit" ,function (event) { event.preventDefault(); console.log('submited'); console.log($('#msgbox').val()) } ,created);//created); when i console log the value it just come through in the console please help me