Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to handle user Registration with Django
I'm following a tutorial in which we are using https://django-registration-redux.readthedocs.io for registrations redux settings. Since the tutorial is from 2015 I wanted to check if Djnago had more robust built in features for this, or if going with a 3rd party app such as the one linked to above was still a good choice. -
Unable to connect to ldap using django-python3-ldap
I am developing django website and I want to use ldap authontation with my application. I am using Django 1.11 to authenticate with the django-python3-ldap. I tested the connection to my ldap using ldapsearch and it was succeeded and I got the following result: ally@websrv:/web/demo_project_ally$ ldapsearch -x -W -D 'cn=ldapadmin,dc=myldap,dc=com' -b "dc=myldap,dc=com" "cn=ally ally" -H ldap://myldap.com Enter LDAP Password: # extended LDIF # # LDAPv3 # base <dc=myldap,dc=com> with scope subtree # filter: cn=ally ally # requesting: ALL # # ally ally, my_ou, myldap.com dn: cn=ally ally,ou=my_ou,dc=myldap,dc=com cn: ally ally givenName: ally gidNumber: 500 homeDirectory: /home/users/aally sn: ally loginShell: /bin/sh objectClass: inetOrgPerson objectClass: posixAccount objectClass: top userPassword:: e01ENX1kNVJuSkw0bTV3RzR3PT0= uidNumber: 1000 uid: aally # search result search: 2 result: 0 Success # numResponses: 2 # numEntries: 1 When I try to connect from django I will get this error: System check identified no issues (0 silenced). July 24, 2017 - 20:40:26 Django version 1.11, using settings 'demo_project.settings' Starting development server at http://0:8002/ Quit the server with CONTROL-C. LDAP connect failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - None - bindResponse - None [24/Jul/2017 20:40:37] "POST /accounts/login/ HTTP/1.1" 200 917 Error: LDAP connect failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None … -
Customize the Wagtail editing interface with a form that is loaded after the model
I want to customize the Wagtail editing interface as defined in the docs: http://docs.wagtail.io/en/v1.11.1/advanced_topics/customisation/page_editing_interface.html#customising-generated-forms The problem is that my form has a field with a queryset that gets objects from the model, so I keep running into circular dependencies. How can I define a base_form_class that is loaded after the model? Any way around this? -
Using OAuth to authenticate Office 365/Graph users with Django
We are creating an application for use in our organization, but we only want people in our organization to be able to use the app. We had the idea of using Microsoft's OAuth endpoint in order to authenticate whether a user is part of our org or not. The idea is to bring up a sign in screen where the user can enter their Office 365 username and password, which will then allow them to use our app upon submission of their credentials. Our app is running on Django, and I've only found a solution to this problem using Flask and Microsoft's Graph API connect sample for Python (See code snippet below). This sample uses a similar idea to the one above to log in to the app. Are there any similar methods of authentication for Django? import requests from flask import Flask, redirect, url_for, session, request, render_template from flask_oauthlib.client import OAuth # read private credentials from text file client_id, client_secret, *_ = open('_PRIVATE.txt').read().split('\n') if (client_id.startswith('*') and client_id.endswith('*')) or \ (client_secret.startswith('*') and client_secret.endswith('*')): print('MISSING CONFIGURATION: the _PRIVATE.txt file needs to be edited ' + \ 'to add client ID and secret.') sys.exit(1) app = Flask(__name__) app.debug = True app.secret_key = … -
Django w/ Apache, CSRF Verification Failing
I have a bit of an issue with CSRF verification in my Django app. I have two other {% csrf_token %} tags in my app, in two different HTML templates. These work fine, and always have. When attempting to add a third in another new template though, I receive the '403 Forbidden' page. I've copied the style of the two working 'post' commands exactly, but for some reason this one will not work. Any suggestions? The 'post' form contains a single select/drop-down object, and a submit button. Clicking the button should direct to a view to process the posted data, written again just like the first 2, but it throws the 403 error instead. -
Trying to build a two-player chess game website with Django
I'm trying to use Django to build a website that allows visitors to play each other in chess. I want the game interface to be a chessboard panel within the browser window that players can click to move their pieces, similar to the Chess.com Live Chess interface. Is there any way that I can code the chess game logic and graphical panel interface in Python (using a GUI package such as Tkinter), and then use Django to embed the panel in the middle of a webpage? If so, can anyone explain to me how to do this, or give me a resource that explains it? Or would it be easier to construct the game and GUI panel using Javascript or some other tool? -
Django API Rest Framework
this is - don't slap me in the face - a beginner question. I have some knowledge in Python and Django, but it is not too overwhelming. I have a very appealing business idea in my head and I made it a challange to see if I can get the nessesary skills to make it come to life. Long story short, somewhere along the road I want to be able to build an IOS and Android App (or bring someone in who can do it). I also need a homepage for this (Django is a good enough solution for this - this much I know). As far as I unserstand it, I can use the rest API Framework to connect Apps with the Django Backend. Ist this a good solution? Or would you recommend another way to realise this projekt? Speed would be impartant for the final solution. Also I need good scalability, though, I don't plan to recreate Facbook. -
Django best practiche to know user id logged in outside the view.py
In my django project i need to know the user id logged in my pp. I wrote a client/server application, many user connect with different username/permission on it, i would to know outside the view.py on every single client what is the user id connected. I try to store a cookie after login on client in my view.py like this: u_id = False try: u_id = request.COOKIES['uid'] except Exception: response.set_cookie('uid', value=request.user.id, max_age=None) but after this i don't know how retrive uid from every single client. I try to inspect the django_session table but i don't know how can i link sessionid on client cookie to session_key on table for know what is the user. Some one have an idea about who it's the best practice for know in every place of my app the user-id logged in? Thanks in advance -
Celery do users task
Why do the users task on celery 4 + django? I want to make a flexible user interface based on celery, so that I can add and delete tasks that are periodic and not. -
Using wildcard to do queryset filter in Django
I have three columns (var1, va2 and var3) in my database. On the html page, a user can input values for var1, var2, or var3 or a combination of the three variables (e.g. provide data only for var1 and var3, or var2 and var3). My query search is: Rule.objects.filter(var1=user_var1, var2=user_var2, var3=user_var3, ) If the user enters values for all three variables, this is pretty straight forward. If the user enter values for two or one of the variables, I would like the queryset filter to match only the columns that the users entered values for. For example: users entered data for var2 and var3. The resulting search would be: Rule.objects.filter(var2=user_var2, var3=user_var3, ) But is there a way to keep all three variable in the filter code and so something like: if user_var1 = null, then user_var1=[wildcard or all] Rule.objects.filter(var1=user_var1, var2=user_var2, var3=user_var3, ) -
TypeError: Init Only takes 1 positional Argument
I am using Class Based Views to render my templates. Here is my code so far: Views.py: class CashFlowView(TemplateView): template_name = "visualization/cash_flow.html" def get_context_data(self, **kwargs): context = super(CashFlowView, self).get_context_data(**kwargs) return context def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) return self.render_to_response(context) def render_to_response(self, context, **response_kwargs): response_kwargs.setdefault('content_type', self.content_type) return self.response_class( request=self.request, template=self.get_template_names(), context=context, using=self.template_engine, **response_kwargs ) urls.py: from django.conf.urls import url from django.contrib import admin from .views import CashFlowView urlpatterns = [ url(r'cash-flow', CashFlowView, name='cashflowView') ] As you can see I am using the templateView but I get this a weird init error. Any ideas?: Internal Server Error: /visualization/cash-flow Traceback (most recent call last): File "/Users/andy/Documents/venv_analytics/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/andy/Documents/venv_analytics/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/andy/Documents/venv_analytics/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given -
Django: How to migrate to class-based indexes
Django 1.11 introduced Class-based model indexes. What was previously defined as class A(models.Model): class Meta: index_together = [ ('foo', 'bar'), ] Can now be defined as class A(models.Model): class Meta: index_together = [ models.Index(fields=['foo', 'bar']), ] When I change to the new syntax for a model an run python manage.py makemigrations, it will create migrations like class Migration(migrations.Migration): dependencies = [ ('categories', '0001_initial'), ] operations = [ migrations.AlterIndexTogether( name='a', index_together=set([]), ), migrations.AddIndex( model_name='a', index=models.Index(fields=['foo', 'bar'], name='b_a_f12345_idx'), ), ] This migration will remove and re-create my indexes, which is something I'd like to avoid. What is the recommended way for switching from the old to the new syntax? I could not find anything in the documentation. -
Django: Saving ManyToManyField attribute from form submit
I have a view like so: def view(request, ...): user = request.user company = get_object_or_404(Company, ...) group = get_object_or_404(Group, ...) form = TaskCreateForm() if request.method == 'POST': form = TaskCreateForm(data=request.POST) if form.is_valid(): form.save(commit=False) form.creator = user form.company = company form.group = group # So these above attributes aren't actually inputs in the form, but just data passed to the model from things like the user that's sending off the form and the group they're in for example form.save() Where creator (the user) and the company are related by ForeignKey to this particular model (Task, which the user is filling in the form for). The problem is where I write form.group = group, and I suspect this may be because the Group has a ManyToMany relationship with the Task model. I want the 'group' to be one of the many Group objects that will be related to this Task object. The error occurs upon trying to save the form and is as follows: TypeError at /company/task/625377380359841/ coercing to Unicode: need string or buffer, NoneType found This would be a great help, thanks! Edit: I've also had a look at the save_m2m() method which I thought may be relevant but this did … -
Is it possible to filter models in django templates?
I have added my view and template codes below. MY question, how can i get bird( model 1) and respective bird's details(model2) --------view------ all_birds = Bird.objects.all() detail = Detail.objects.all() template = loader.get_template('bird/bird.html') contex = { 'all_birds': all_birds, 'details': detail, } return HttpResponse(template.render(contex, request)) --------template---------- {% for birds in all_birds %} <div class="container"> <div class="row"> <div id="board" data-columns> <div class="item"> <div class="ani-box"> <a href="{% static 'bird/images/img_10.jpg'%}" class="image-popup fh5co-board-img"> <img src="{% static 'bird/images/img_10.jpg'%}" alt="No Image available"></a> </div> </div> </div> </div> </div> {% endfor %} -
Django ORM: Get latest record for distinct field
I'm having loads of trouble translating some SQL into Django. Imagine we have some cars, each with a unique VIN, and we record the dates that they are in the shop with some other data. (Please ignore the reason one might structure the data this way. It's specifically for this question. :-) ) class ShopVisit(models.Model): vin = models.CharField(...) date_in_shop = models.DateField(...) mileage = models.DecimalField(...) boolfield = models.BooleanField(...) We want a single query to return a Queryset with the most recent record for each vin and update it! special_vins = [...] # Doesn't work ShopVisit.objects.filter(vin__in=special_vins).annotate(max_date=Max('date_in_shop').filter(date_in_shop=F('max_date')).update(boolfield=True) # Distinct doesn't work with update ShopVisit.objects.filter(vin__in=special_vins).order_by('vin', '-date_in_shop).distinct('vin').update(boolfield=True) Yes, I could iterate over a queryset. But that's not very efficient and it takes a long time when I'm dealing with around 2M records. The SQL that could do this is below (I think!): SELECT * FROM cars INNER JOIN ( SELECT MAX(dateInShop) as maxtime, vin FROM cars GROUP BY vin ) AS latest_record ON (cars.dateInShop= maxtime) AND (latest_record.vin = cars.vin) So how can I make this happen with Django? -
Django + Vue.js + SSR
I'm facing interesting problem... I do have a form separated into steps - like wizard. Each step (even the 1st one) is loaded from server, where sits Django. The wizard itself is Vue component. Everything works fine together but now I would like to add a component into HTML, that is returned from server. The thing is Wizard (Vue) can only display HTML loaded from server, it cannot parse incomming HTML for new components and instantiate them. This is the point where I remembered Server Side Rendering. My question is where to start if I wanna render the template that is rendered by Django render again via Vue. Maybe there is nother approach. All I want is to have another rich component in my incomming form not just dumb HTML. Thank you. -
Return error message if username exists with django and bootstrap
I created my first Django app and have begun restyling it. I was using the standard {% load bootstrap3 %} but in the style I am switching to bootstrap4. I am using django's UserCreationForm. I restyled the landing page and the signup form. Here is the html of the form. <form method="post" id="signUpForm" action="{% url 'users:register' %}" class="form"> {% csrf_token %} <!-- Username and Email --> <div class="form-group row"> <div class="col-12 col-sm"> <input type="text" name="username" minlength="2" maxlength="100" class="form-control form-control-lg" id="username" placeholder="Username" required> <!-- <div class="form-control-feedback">Sorry, that username's taken.</div> --> <small class="form-text text-muted">Letters, digits and @/./+/-/_ only.</small> </div> <div class="col-12 col-sm"> <input type="email" name="email" class="form-control form-control-lg" id="email" placeholder="Email" required> <!-- <div class="form-control-feedback">Please enter a valid email.</div> --> <small class="form-text text-muted">youremail@example.com</small> </div> </div> <!-- Password --> <div class="form-group row"> <div class="col-12 col-sm form-group"> <input type="password" name="password" id="password" class="form-control form-control-danger form-control-lg" placeholder="Password" required> <small class="form-text text-muted">At least 8 characters.</small> </div> <div class="col-12 col-sm form-group"> <input type="password" name="confirm_password" id="confirm_password" class="form-control form-control-danger form-control-lg" id="inputHorizontalDanger" placeholder="Password confirmation" required> </div> </div> <!-- Submit Button --> <div class="row"> <div class="col-12 form-group"> <button type="submit" class="btn-landing btn btn-block btn-lg btn-info">Create Free Account</button> </div> </div> </form> I am using https://jqueryvalidation.org/ to dynamically validate the form input. But I need to check … -
Running local Python script from Django webpage
I feel I have searched and exhausted all resources and found no solution. I have successfully developed a few Django sites, but none like this. Essentially, I have a python script that ssh's into a virtual machine and starts a web miner. I simply need a way via the webpage to start this python script (I don't care if it is a button/link/etc.) There is no input or output needed. Just an easier way for my client to start the web miner. The django site itself serves as a reports type site that shows the results from the miner. Here is the python script I need executed from the page: from pexpect import pxssh s = pxssh.pxssh() s.force_password = True s.login('host', 'username', 'password') s.sendline('tmux attach') s.sendline('python filename.py') s.logout I feel like there is probably a simple solution, but I just can't find it. -
Django empty string search shows whole querylist
I have been trying to prevent the front-end search bar from showing all the objects displayed when making empty/blank string as search instead of showing nothing. Tried many ways but didn't work. views.py def search(request): queryset_list = Slot.objects.all().order_by('slot_no') query = request.GET["q"] if query: queryset_list = queryset_list.filter( Q(slot_no__icontains=query) | Q(booking_info__booked_by__applicants_name__icontains=query) ).distinct() paginator = Paginator(queryset_list, 4) page_request_var = "page" page = request.GET.get(page_request_var) try: queryset = paginator.page(page) except PageNotAnInteger: queryset = paginator.page(1) except EmptyPage: queryset = paginator.page(paginator.num_pages) context = { "object_list": queryset, "page_request_var": page_request_var, } return render(request, "search_listings.html", context) html: <form method='GET' action='/listings/'> <div class='col-sm-6 col-sm-offset-3'> <div class="input-group"> <input type='text' class="form-control" name='q' placeholder=' search slots' value='{{ request.GET.q }}' /> <span class="input-group-btn"><input class="btn btn-primary btn-lg" type='submit' value='Search' /></span> </div> </div> </form> urls.py url(r'^listings/', views.search, name='search'), The search results displays properly other than that. -
How to select database in django db collection custom query?
I have two database in my django application. One is default and another is sencondry. When I tried the following code it always return the data from default database. from django.db import connection def my_custom_sql(self): cursor = connection.cursor() cursor.execute("SELECT * FROM accounts_account where id=%s", [self.id]) row = cursor.fetchall() return row I want to execute the query in second databse. -
COR issue with a PreSigned S3 URL for file upload
I try to upload files in an S3 bucket in eu-west-2 region: In the django-view i coded: conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID,settings.AWS_SECRET_ACCESS_KEY,host=settings.AWS_S3_HOST) try: conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID,settings.AWS_SECRET_ACCESS_KEY,host=settings.AWS_S3_HOST) except: print "S3connection Failed" else: print "S3Connection OK" Then i Generate the pre-signed url try: S3url = conn.generate_url_sigv4(secondsPerDay, "PUT", bucket=settings.AWS_STORAGE_BUCKET_NAME, key=path, force_http=True) except: print "generate_url_sigv4 failed" else: print "generate_url_sigv4 OK" print S3url and S3url is: S3url= https://MyBucketName.s3-eu-west-2.amazonaws.com/pathtofile/0.MOV?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=AWSsignature&X-Amz-Date=20170724T120524Z&X-Amz-Credential=MyKey%2F20170724%2Feu-west-2%2Fs3%2Faws4_request Using Curl i can upload a video file with : curl -v -T "0.MOV" --header "Content-Type:binary/octet-stream" "https://MyBucketName.s3-eu-west-2.amazonaws.com/pathtofile/0.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=AWSsignature&X-Amz-Date=20170724T122024Z&X-Amz-Credential=MyKey%2Feu-west-2%2Fs3%2Faws4_request" So for me the generation of pre-signed url in django/python is ok. By the way thanks to How to properly upload an object to AWS S3? contributors The problem comes when i try to use the presigned url through and ajax request. Google Chrome states: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. The response had HTTP status code 403. I try many combinations of settings = $.extend(true, {}, { xhr: function () { var xhrobj = $.ajaxSettings.xhr(); return self._initXhr(xhrobj, previewId, self.getFileStack().length); }, url:S3url, type: 'PUT', cache: false, processData: false, success: fnSuccess, complete: fnComplete, error: fnError, crossDomain: true, headers: { 'Access-Control-Allow-Headers': '*', 'Content-Type': 'binary/octet-stream', }, … -
Create a Model that has two fields that are both user id's [duplicate]
This question already has an answer here: How can I have two foreign keys to the same model in Django? 3 answers I'm trying to make a model called Mission which has both Creator and Lead. I tried adding these lines to Mission: lead = models.ForeignKey(User, on_delete=models.PROTECT) creator = models.ForeignKey(User, on_delete=models.PROTECT) and that threw me an error. How do I contain two users in one model? And to make it more complicated, I want users to be able to "sign up" for a mission and I'm not quite sure how to do that. Is that another table/model connecting them? Thanks! -
cant understand django blocks
I just started learning Django. I came across so called 'blocks'. Basically, u apply blocks to a base html and use it as a matrix instead of retyping code ? I got confused. Also, there are only 2 types of blocks ? used for title and for the body (named content for some reason) ? Another thing, I tried to apply css to the main html but only the ones for the base one is rendered. I am very confused about this subject. I would also like to know when and not to use it. Also, I havent tried, but, css is not rendered in Django without using a static file? Or what's the catch ? Thank you. -
filter latest text entry from models textfield and parse it into the list django
I have a model like this: class TrademarkModel(models.Model): description = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ("-created", ) I wan't to filter latest description entry and parse it into the list, so I can run that list against xml and do some additional counting. I'm doing something like this result = Trademark.objects.values() list_values = [entry for entry in result] return list_values and for the result I've got this: [{'created': datetime.datetime(2017, 7, 24, 11, 58, 14, 30162, tzinfo=<UTC>), u'id': 6, 'description': u'c'}, {'created': datetime.datetime(2017, 7, 24, 11, 57, 22, 674450, tzinfo=<UTC>), u'id': 5, 'description': u'Test'}, {'created': datetime.datetime(2017, 7, 24, 11, 55, 14, 376727, tzinfo=<UTC>), u'id': 4, 'description': u'Test'}, {'created': datetime.datetime(2017, 7, 24, 11, 32, 31, 4703, tzinfo=<UTC>), u'id': 3, 'description': u'Non Building materials'}, {'created': datetime.datetime(2017, 7, 24, 11, 31, 35, 244154, tzinfo=<UTC>), u'id': 2, 'description': u'Testing'}, {'created': datetime.datetime(2017, 7, 24, 7, 20, 29, 920155, tzinfo=<UTC>), u'id': 1, 'description': u'Testing'}] This is not ideal, because I need to do additional parsing of list_values, so I can get latest entry. My question is what is the most elegant way of extracting latest entry from description and parse it into the list? -
Django form error: "Select a valid choice" on RadioSelect()
Trying to figure out what's going wrong here. I have a ModelForm where I need a radio select between three colors. I get the following error: "Select a valid choice. This is not one of the available choices" models.py: COLORS = ( ('1', 'Röd'), ('2', 'Gul'), ('3', 'Blå'),) class Poster(models.Model): title = models.CharField(max_length=100) colors = models.IntegerField(choices=COLORS, default=2) forms.py: class PosterForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PosterForm, self).__init__(*args, **kwargs) class Meta: model = Poster fields = ('title', 'colors') labels = { "title": "Rubrik", "colors": "Färg", } widgets = { 'colors': forms.RadioSelect(attrs={'choices': "[(1, 'Röd'), (2, 'Gul'),(3, 'Blå')]"}), } template.html: <div id="id_colors"> <div class="radio"><label for="id_colors_0"><input class="" id="id_colors_0" name="colors" title="" type="radio" value="1" required /> Röd</label></div> <div class="radio"><label for="id_colors_1"><input checked="checked" class="" id="id_colors_1" name="colors" title="" type="radio" value="2" required /> Gul</label></div> <div class="radio"><label for="id_colors_2"><input class="" id="id_colors_2" name="colors" title="" type="radio" value="3" required /> Blå</label></div> </div> {% if form.colors.errors %} <div class="alert alert-danger"> <strong>{{ form.colors.errors|escape }}</strong> </div> {% endif %} Happy for any help!