Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Group Chat in Django
I am tring to create group chat in Django with Channels. Here below you can see my code. After submit the message nothing happens. Also Log in empty. How to make code work? routing.py: channel_routing = [ route('websocket.connect', ws_connect, path=r'^account/dashboard/projects/(?P<project_code>[0-9a-f-]+)/chat/$'), route("websocket.receive", ws_receive), route("websocket.disconnect", ws_disconnect), ] consumers.py: # Connected to websocket.connect @channel_session def ws_connect(message): query = parse.parse_qs(message['query_string']) if 'username' not in query: return room = message.content['path'].strip("/") Group('chat-%s' % room).add(message.reply_channel) message.channel_session['room'] = room message.channel_session['username'] = query['username'][0] message.reply_channel.send({"accept": True}) # Connected to websocket.receive @channel_session def ws_receive(message): if 'username' not in message.channel_session: return Group('chat-%s' % message.channel_session['room']).send({ 'text': json.dumps({ 'message': message.content['text'], 'username': message.channel_session['username'] }) }) # Connected to websocket.disconnect @channel_session def ws_disconnect(message): Group("chat-%s" % message.channel_session['room']).discard(message.reply_channel) template: {% block content %} <h1>{{ room.code }}</h1> <div id="msgArea"></div> <div> <textarea name="message" id="message" cols="30" rows="10"></textarea> </div> <button id="btnSubmit">Submit</button> {% endblock content %} {% block script %} <script> $(document).ready(function(){ var msgArea = $('#msgArea') var elementMessage = $('#message') var webSocket = new WebSocket('ws://' + window.location.host + '/account/dashboard/projects/(?P<{{ room.project_id }}>[0-9a-f-]+)/chat/'); webSocket.onmessage = function(message) { var data = JSON.parse(message.data) msgArea.append('<p><strong>'+ data.username + '</strong>: ' + data.message + '</p>') } $('#btnSubmit').click(function(e) { webSocket.send(elementMessage.val()) }) }) </script> {% endblock script %} -
NOT NULL constraint failed: core_profile.user_id
I have a model named Profile which is created to extend the User auth model. I have created two forms one is UserForm and ProfileForm. In register.html template I show this two forms and wish to save in the database through the user. But it constantly shows the exception: Integrity Error NOT NULL constraint failed: core_profile.user_id whenever I try to submit the post filling out all the fields and hit submit button. Here are my models: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() And here is my view for posting the forms: from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import SignUpForm, ProfileForm @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': user_form = SignUpForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid(): user = user_form.save() profile_form.save() user.refresh_from_db() # load the profile instance created by the signal user.profile.birth_date = user_form.cleaned_data.get('birth_date') user.save() raw_password = user_form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) … -
Django - Filling a form with a date instance from the Database
I've got a form which will be populated with any data from a saved model object so that the object can be updated. However the date field seems to be pre-populated with a date like... 2016-09-07 00:00:00+00:00 I want this to be in the format 'mm dd YYYY'. In my HTML template I've tried {{ form.date_start|date:'m d Y' }} which doesn't raise an error but just removes the input field altogether. Any ideas on how to specify a date format to pre-populate a date field with? Thanks! -
How to make Authorization mandatory for DRF django?
I'm new to Django world. I've implemented TokenAuthentication for my REST APIs. settings.py 'DEFAULT_AUTHENTICATION_CLASSES': ( 'auth.authentication.TokenAuthentication', ), authentication.py class TokenAuthentication(RestTokenAuthentication): model = RestAPIToken def authenticate_credentials(self, key): try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: if self.model.objects.has_expired(key): raise SessionExpired() raise exceptions.AuthenticationFailed(_('Invalid token.')) # Django auth framework expects # (user, auth) tuple. However, here we don't need user object. # So, keeping it None return None, token models.py class HistoryViewSet(viewsets.ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = History.objects.all() serializer_class = HistorySerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('contract_id',) Now, if I provide Authorization header, it works perfectly fine. However, if I don't provide Auth header at all, still it works fine. I don't have User model. I don't need User model as I don't want to check if it is valid or no. So, skipped User model altogether. I don't understand, without Authorization header why requests are getting successfully exected? -
The best way to do permission set in Django (group, roles, permissions)
Thanks for reading my question. Before to ask, i was reading about my doubt: http://djangobook.com/customizing-authentication-django/ django roles authorization architecture Django Permissions for Different Clients ... And i'm not clear about permissions set in Django :( I learning Django, but i want to try to build a permission set on my app. My system is about a schoool: teachers, students, management people, class room leaders. The system's premise is: an user only must to have a rol. Some questions about it: I thinking to prepopulate role table, with general profiles: student, teacher, management... What is the better way to do it? The typical restriction: a teacher is the unique profile can add, delete, view, edit your student's scores. What is the better way to do it? Should I do it through a custom system? Have u some url, code or source where can i to check it? Excuse me my english. Thanks! -
Delete an object by id with django
Working on school project. I am trying to delete messages by only the people that were logged in and have created it. I want other user to see them but only the creator can delete it. I have code that will delete everything in the database. I researched and found that Mysecret.objects.filter(id=request.session['user_id']).delete() should work but when i do this the page wont delete anything just refreshes the page. I will only post views and model as i know everything else works. I think its just the format that I cant seem to nail down. Views.py from django.shortcuts import render, redirect from . models import Mysecret from ..logReg.models import User # Create your views here. def index(request): context = { "secret": Mysecret.objects.all(), } return render(request, 'secretdojo/index.html', context) def create(request): secreteid= User.objects.get(id=request.session['user_id']) Mysecret.objects.create( secret=request.POST['message'], creator=secreteid) return redirect( 'secretdojo:index') def removesecret(request): Mysecret.objects.filter(id=request.session['user_id']).delete() return redirect( 'secretdojo:index') def topsecret(request): context = { } return redirect( '/') model.py from __future__ import unicode_literals from django.db import models from ..logReg.models import User class Mysecret(models.Model): secret = models.CharField(max_length =500) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) loguser = models.ManyToManyField(User, related_name='loguser') creator = models.ForeignKey(User, related_name='creator') -
Django: Controlling Admin URLs
After not finding an answer, I'm wondering if it is possible to control the Admin url sequence. I have a Post model. When I go to list my Posts in admin, the url is localhost:8000/admin/posts/posts. Is there a way to use the localhost:8000/admin/posts url instead? -
Apache mod_wsgi error log
I have mod_wsgi eror log example es below, but how i can configure logging to combine message with similar timestamp as one event? [Wed Mar 22 17:25:30 2017] [wsgi:error] [pid api:tid 139642724603648] 2017-03-22 17:25:30,856 654 139642724603648 get_helper.py : 754 INFO : GetJobs [Wed Mar 22 17:25:30 2017] [wsgi:error] [pid api:tid 139642724603648] 2017-03-22 17:25:30,856 654 139642724603648 get_helper.py : 384 INFO : doing -
django.core.exceptions.ImproperlyConfigured: Error importing form class pages.custom_sign_up_form: "cannot import name 'BaseSignupForm'"
I am trying to extend SignupForm of django allauth for customizing my signup form. The need is because i want to check if submitted email is accepted for signup or not and it is done by checking if the invite from that email is accepted or not by admin. I have not define my form in forms.py instead i have used another name 'custom_sign_up_form.py'. Below is my full code with import. settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'pages.custom_sign_up_form.CustomSignupForm' custom_sign_up_form.py from allauth.account.adapter import DefaultAccountAdapter, get_adapter from allauth.account.forms import SignupForm from allauth.account import app_settings # from django import forms from invitation.models import Invitation class CustomSignupForm(SignupForm): errors = { 'not_invited': "Sorry! You are not yet invited.", } def __init__(self, *args, **kwargs): super(CustomSignupForm, self).__init__(*args, **kwargs) def clean(self): super(CustomSignupForm, self).clean() email = self.cleaned_data.get('email') email = get_adapter().clean_email(email) if email and app_settings.UNIQUE_EMAIL: email = self.validate_unique_email(email) try: Invitation.objects.get(email=email, request_approved=True) except Invitation.DoesNotExist: # raise forms.ValidationError(errors['Sorry! you are not yet invited']) self.add_error('email','Sorry! You are not yet invited') return email -
Django Choice field - select not set
I have a Django modelform with a ChoiceField. When I try to init the form passing an instance, all the fields are filled correctly but the ChoiceFiled one. Form class: CHOICE_A = 0.070 CHOICE_B = 0.190 CHOICES = ((CHOICE_A, "7%"), (CHOICE_B, "19%")) field = forms.ChoiceField(choices=CHOICES) The instance value in the DB could be 0.070 or 0.190. None of these values seem to be valid though, because when I render the field with: {{ form.field }} It renders the select input with the choices, but the first one is always selected. No matter what value is stored in {{ form.field.value }}. -
Unable to run daphne with binding command
using python manage.py runserver i am able to establish successful websocket connection. but when i run the following command daphne -b 0.0.0.0 -p 8001 app_name.asgi:channel_layer the server is successfully started but the connection fails as shown below. i am unable to find a solution for this. 2017-03-22 10:40:11,940 INFO Starting server at tcp:port=8001:interface=0.0.0.0, channel layer app_name.asgi:channel_layer. 2017-03-22 10:40:11,940 INFO Using busy-loop synchronous mode on channel layer 2017-03-22 10:40:11,940 INFO Listening on endpoint tcp:port=8001:interface=0.0.0.0 127.0.0.1:53259 - - [22/Mar/2017:10:40:33] "WSCONNECTING /ws/2" - - 127.0.0.1:53259 - - [22/Mar/2017:10:40:38] "WSDISCONNECT /ws/2" - - below is the client code. let socket = new WebSocket("ws://" + "localhost:8001" + "/ws/2"); socket.onmessage = function(e) { alert(e.data); }; socket.onopen = function() { console.log("onOpen") }; if (socket.readyState == WebSocket.OPEN) { socket.onopen(); } Error is WebSocket connection to 'ws://localhost:8001/ws/2' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET -
Django REST url does not match patterns
I want to keep URL's prefix with app names in the main urls.py file. This way I will avoid collision of endpoints in other apps under the same project. # project/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/v1/accounts/', include('account.urls')), url(r'^api/v1/users/', include('users.urls')), url(r'^api/v1/transactions/', include('transactions.urls')), url(r'^auth-token-auth', views.obtain_auth_token), ] For instance, I am including accounts.urls with following content: urlpatterns = [ url(r'^', AccountListView.as_view()), url(r'^(?P<pk>[0-9]+)/$', AccountDetailView.as_view()), ] By doing this way /api/v1/accounts/1 pattern does not match AccountDetailView. It always returns the first view AccountListView The most interesting thing is when I change urlpatterns definition in the way provided below. All endpoints works as expected. # project/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/v1/', include('account.urls')), url(r'^api/v1/', include('users.urls')), url(r'^api/v1/', include('transactions.urls')), url(r'^auth-token-auth', views.obtain_auth_token), ] # account/urls.py urlpatterns = [ url(r'^accounts/$', AccountListView.as_view()), url(r'^accounts/(?P<pk>[0-9]+)/$', AccountDetailView.as_view()), ] The question is how to solve this issue by keeping app names api/v1/[app_name] in main urls.py. Maybe you can suggest other patterns (best practice) for URL mapping. -
Is it possible to lose the chunks of data while streaming Ajax
I'm streaming responses from a Django server to a browser(chrome) page, using $.ajax. In testing, I am expecting to get the response in 3 chuncks, but a lot of the time of the time I am only getting one or two text chuncks. On the server I am using StreamingHttpResponse to respond to the request. Is it possible to lose the chunks if the are sent immediately after each other? Here is my ajax call: $.ajax({ url: "createRepos", type: "POST", data: { csrfmiddlewaretoken: "{{ csrf_token }}", //, django requires a csrf token (included in the post data) in every POST request you make. repoList : uniqRepos }, dataType: "json", timeout:0, xhr: function () { var xhr = $.ajaxSettings.xhr(); xhr.onreadystatechange = function () { if(xhr.readyState === XMLHttpRequest.LOADING) { console.log(xhr.responseText); //should be called 3 times //sometimes called only 1 or 2 times, sometimes 3 //... // update the web page with data in // the response text using jQuery } }; return xhr; } }); -
Upload two different files using django with single submit button
How to upload two different file formats and save in different folders using single upload button using django? -
python function when added to cron using django-crontab gives "No JSON object could be decoded" ERROR
When i execute my python function on django shell it executes fine. But when the function is executed via crontab it gives "No JSON object could be decoded" Error. successfully made the api call. response status is 200 Exception occured : No JSON object could be decoded Failed to complete cronjob at ('0,30 * * * *', 'myapp.cron.pulldata', ' >> /usr/local/devops/myapp/crontab.log') Traceback (most recent call last): File "/usr/local/devops/provider_monitoring/env/lib/python2.7/site-packages/django_crontab/crontab.py", line 145, in run_job func(*job_args, **job_kwargs) File "/usr/local/devops/provider_monitoring/provider_monitoring/provider_automation/cron.py", line 49, in pulldata_and_createjira response = response.json() File "/usr/local/devops/provider_monitoring/env/lib/python2.7/site-packages/requests/models.py", line 866, in json return complexjson.loads(self.text, **kwargs) File "/opt/python-2.7.10/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/opt/python-2.7.10/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/opt/python-2.7.10/lib/python2.7/json/decoder.py", line 384, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded I am doing a POST call in my code to splunk rest api. payload = {'search' : 'search index="xyz" | table a , b , c' , 'earliest_time' : '-60m' , 'output_mode' : 'json_rows' } url = "https://localhost:8089/services/search/jobs/export" headers = {'content-type': "application/x-www-form-urlencoded",'authorization': "xyz",'cache-control': "no-cache"} response = requests.adapters.HTTPAdapter(pool_connections=10, pool_maxsize=10, max_retries=5, pool_block=False) response = requests.request("POST", url, data=payload, headers=headers, verify=False) response = response.json() I get error only when i run the … -
Python and Django Insert Strings into a Database
I am using Django and Python for the "framework" of a website. What I am trying to do is create a database that stores user input. The main purpose here is to find out the most common inputs for analytics, etc. I thought about just making a CSV file and inserting into it via Python. But having to open the file and write to it each time seems inefficient. Maybe I'm wrong. Are there any best practices out there that could help achieve this? Thanks -
Continuous deployment of a django application with gitlab
I have a django project of mine, which is hosted on gitlab. And since I would like to take the most out of gitlab's features - I need you advice regarding continuous deployment. The current setup is the following: I have a gitlab runner installed on my VPS which uses shell executor and is registered to my project. When a runner job starts, it runs a couple of manage.py tasks and copies the whole thing to the actual deployment directory after which it restarts nginx and gunicorn. Steps are pretty basic, and since I am not an expert, I would like to know if it is somewhat the right way to (continuously) deploy django applications in the first place and secondly, what are the security implications of this deployment model (especially concerning the use of shell executor) ? I've read some articles about deploying django applications with docker (which I am not familiar with) but for me it seemed more like an overkill rather than a necessity (since I use python virtual environment my project is somewhat encapsulated any way). Although deploying with docker should be more secure ? (at least thats what i heard). What are your thoughts on … -
Assertion error on Python 3.4.2
I got a nasty AssertionError. Can someone check the code with me? It is pointing to line 126; 123 def save(self, *args, **kwargs): 124 min_fee = .2 125 assert self.buy < 100 - min_fee 126 assert self.sell > 100 + min_fee 127 return super().save(*args, **kwargs) More info AssertionError at /admin/..... No exception message supplied Request URL: http://XXXXXXXX:0000/admin/core/relativestrategyprofile/add/ Django Version: 1.8.17 Exception Type: AssertionError Exception Location: /cointrol/core/models.py in save, line 126 Python Executable: /usr/bin/python3 Python Version: 3.4.2 -
'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'
I'm advancing with the web app I asked about earlier. Currently, my models.py is from django.db import models from unittest.util import _MAX_LENGTH class Alimento(models.Model): INTOLERANCIAS = ( ('00', 'Ninguna'), ('GL', 'Gluten'), ('CR', 'Crustáceos'), ('HU', 'Huevos'), ('FS', 'Frutos Secos'), ('AP', 'Apio'), ('MO', 'Mostaza'), ('SE', 'Sésamo'), ('PE', 'Pescado'), ('CA', 'Cacahuetes'), ('SO', 'Sulfitos'), ('SJ', 'Soja'), ('LA', 'Lácteos'), ('AL', 'Altramuz'), ('ML', 'Moluscos'), ('CA', 'Cacao'), ) nombre = models.CharField(max_length=60) intolerancia = models.CharField(max_length=2, choices=INTOLERANCIAS) def __str__(self): return self.nombre class Receta(models.Model): nombre = models.CharField(max_length=100) raciones = models.IntegerField(default=1) preparacion = models.TextField(default='') consejos = models.TextField(blank=True) ingredientes = models.ManyToManyField(Alimento, through='Ingrediente') def __str__(self): return self.nombre def getIntolerancias(self): ing = self.ingredientes intolerancias = [] for i in ing: intolerancias[l+1] = i.alimento.get_intolerancia_display() return intolerancias class Ingrediente(models.Model): receta = models.ForeignKey('recetas.Receta', on_delete=models.CASCADE) alimento = models.ManyToManyField(Alimento) cantidad = models.FloatField(default=0) descripcion = models.CharField(max_length=60, blank=True) def __str__(self): return self.alimento.__str__() the method getIntolerancias is supposed to list the food intolerances related to each of the ingredients of a given recipe (Receta). To do that, I try to get the queryset of ingredients (Ingrediente) with ing = self.ingredientes, but when I try it on shell I get this error message Traceback (most recent call last): File "/usr/lib/python3.5/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File … -
Django - how to query user profile based on User model having OneToOneField
I'm using Django and new to programming. I want to know how can I query the profiles of the user which has OneToOne relation with User model. Here is my code: models.py: class User(models.Model): email = models.EmailField(unique=True, null=True) date_joined = models.DateTimeField(default=datetime.now) username = models.CharField(max_length=22) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=500) contact_person = models.CharField(max_length=255) country = models.CharField(max_length=100) city = models.CharField(max_length=100) If a user signup and after verification fills in his profile. How can I query the database through views.py that for any particular User what is his UserProfile information. For example what is the company_name or country for a user with email example@examplemail.com Just on the side note also is this the best practice I'm doing to capture additional information about user in Django? -
Using Django session to authenticate access to wiki
I've been making an app for a client using Django. Users belong to 'accounts'; these accounts might be companies that are paying the bill or something like that. They have said that they wish users of that app to have access to a wiki (undecided on which software to use yet). Users logged into one service or the other shouldn't have to log in a second time to access the other service. This screams single sign on to me. I've had a look at Keycloak which seems okay but not ideal when wanting to create accounts, and then users within those accounts, like we use in this app. Does anyone have any suggestions as to the best way to share my Django authentication / session with another application like a wiki? Any solution I've thought of so far seems terribly complex. -
AttributeError: 'function' object has no attribute 'views'
Hello i'm learning Django framework for Web applications I'm trying to build basic blog from tutorial and i'm stacked on one problem AttributeError is telling me that 'function' object has no attribute 'views'. i don't know where i have problem in my files so i will include here some code of my files. There is my urls.py from django.conf.urls import url from django.contrib import admin import WarblerTest urlpatterns = { url(r'^admin/', admin.site.urls), (r'^$', WarblerTest.blog.views.index), url( r'^blog/view/(?P<slug>[^\.]+).html', WarblerTest.blog.views.view_post, name='view_blog_post'), url( r'^blog/category/(?P<slug>[^\.]+).html', WarblerTest.blog.views.view_category, name='view_blog_category'), } There is my views.py from django.shortcuts import render from blog.models import Blog, Category from django.shortcuts import render_to_response, get_object_or_404 def index(request): return render_to_response('index.html', { 'categories': Category.objects.all(), 'posts': Blog.objects.all()[:5] }) def view_post(request, slug): return render_to_response('view_post.html', { 'post': get_object_or_404(Blog, slug=slug) }) def view_category(request, slug): category = get_object_or_404(Category, slug=slug) return render_to_response('view_category.html', { 'category': category, 'posts': Blog.objects.filter(category=category)[:5] }) There is my models.py from django.db import models from django.db.models import permalink # Create your models here. class Blog(models.Model): title = models.CharField(max_length = 100,unique = True) slug = models.CharField(max_length = 100,unique = True) body = models.TextField() posted = models.DateField(db_index = True,auto_now_add = True) def __unicode__(self): return '%s' % self.title @permalink def get_absolute_url(self): return ('view-blog-post',None, {'slug' : self.slug}) class Category(models.Model): title = models.CharField(max_length = 100,db_index … -
Querying ManyToMany in Django giving me duplicate results
I have two models class Tag(models.Model): key = models.CharField(max_length=200) class Post(models.Model): name = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) I m trying to filter out posts with a list of tags. Lets say tags heat and warm. I will get a list of tags in my api function(['heat', 'warm']). I want to filter all Post data which have tags whose keys are in the list. I tried many types and didn't get correct output. Is there a way to do this on single query? -
Python, Django. Pillow rotate and crop
I am using cropper.js to add simple photo editor to my Django app. Resizing is good! But I have added a button rotate, and now I can`t crop image correctly. For example, I have such image http://prntscr.com/en4jsi When I send such data to django it crop image OK: {'y': 589.6184782608688, 'x': 518.264492753621, 'height': 1089.0297554347842, 'rotate': 0.0, 'width': 1936.0528985507274} But when I click "rotate": $('#rotate').click(function () { cropper.rotate(90); }) Cropper returns me such image http://prntscr.com/en4ten and coords: {'y': 903.3880434782596, 'x': 14.307971014490937, 'height': 1089.0297554347844, 'rotate': 90.0, 'width': 1936.0528985507278} Python with pillow returns me: The code which I use to crop is: image = Image.open(photo.image) rotated = image.rotate(-coords['rotate']) cropped_image = rotated.crop(( coords['x'], coords['y'], (coords['width'] + coords['x']), (coords['height'] + coords['y']), )) cropped_image.save(photo.image.path) What I make bad? -
Django deployment in centos server
I generally deploy django web applications in Ubuntu. But currently we are using cpanel(not looking for alternatives) which doesnt work in Ubuntu. so want to know if moving to centos for cpanel is worth ? Because my fear is, if we move to centos server, do we have to face some complex issues(with django deployment) that we might take lot of time(we are good at Ubuntu).