Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Working with google calendar api in Django
As a start I wanted to view my events from google calendar in Django, I tried the quickstart example, run successfully, after installing the google-api-python-client and downloading the json file. I followed the Google's example page, the sample didn't seem to work, I wrote something in between but had an error just after the google allow page showed up, Wrong state parameter given then AuthStateForbidden at /complete/google-oauth2/ clearly there was a Bad Request, the folder.credentials wasn't created. I found this and I setup a service account but I didn't know how to write the view to print or insert to my calendar .. -
bad interpreter: No such file or directory
I am receiving this error when I am trying to install Django. I set up the virtual environment and I activated it. I noticed that other users seem to get the ^M that is causing them issues, but I think mine may be a different issue. This is the error: (venv) $ pip install django bash: ~/Documents/Coding Projects/Python/blog/venv/bin/pip: ~/Documents/Coding: bad interpreter: No such file or directory` Thanks for any help! -
How to write a Django message into your views code
I'm reading the documentation on how to display a message to the user with Django messages. It says that in order to add a message in your views to call: from django.contrib import messages messages.add_message(request, messages.INFO, 'Hello world.') I'm not sure where to put the second the second line, this is my view: def sign_up(request): if request.method == "POST": form = IdForm(request.POST) if form.is_valid(): post = form.save() post.save() ID = post.id_text return HttpResponse('Thank you') else: return HttpResponse('That text is invalid') else: form = IdForm() return render(request, 'checkin/base.html', {'form': form}) I want the message to appear and thank the user for signing up and display their input as well. -
Random parameters amount in {% url %} tag in Django templatess
I just want to apologize for my bad English. (I'm from Russia) So, I want to add pagination on my site. Imagine, we have two pages: site.com/ (as main page), on which there is posts list, and site.com/tag/tagname - posts list by tag. Both pages must have a paginator. I want to create individual template for pagination block paginator.html and include this in index.html and tag.html. Page urls must be looks like: site.com/5 and site.com/tag/tagname/5. So, we have a different amount of parameters for {% url %} tag: 1 for main page and 2 for tag page. Just simple example: urls.py: app_name = 'test_app' urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^(?P<page_num>[0-9]+)$', views.index, name = 'index'), url(r'^tag/(?P<tag_name>[-\w]+)$', views.tag, name = 'tag'), url(r'^tag/(?P<tag_name>[-\w]+)/(?P<page_num>[0-9]+)$', views.tag, name = 'tag'), ] views.py def paginate(objects_list, in_page, page_num): paginator = Paginator(objects_list, in_page) page = paginator.page(page_num) return page def index(request, page_num = 1): page = paginate(questions, 5, page_num) return render(request, 'test_app/index.html', { 'questions': page, }) def tag(request, tag_name, page_num = 1): page = paginate(questions, 5, page_num) return render(request, 'test_app/tag.html', { 'questions': page, 'tag_name': tag_name, }) questions is a list of questions. index.html {% for question in questions %} Author: {{ question.author }} <br> Title: {{ question.title … -
Flatten Django one to many relationship
I have 2 tables recording the start and finish times of people watching videos. PROFILE ID | NAME | EMAIL ------------------------------------ 1 | FOO | FOO_BAR@EXAMPLE.COM VIDEO LOG ID | PROFILE_ID | VIDEO_ID | START_DATE | END_DATE | --------------------------------------- 1 | 1 | 1 | 2014-01-01 | 2014-01-01 | 2 | 1 | 2 | 2014-01-02 | 3 | 1 | 3 | 2014-01-02 | I would like to flatten the videos into columns and get a CSV output like this ID | NAME | EMAIL | V 1 START | V 2 START | V 3 START | ----------------------------------------------------------------------------- 1 | FOO | FOO_BAR@EXAMPLE.COM | 2015-01-01 | 2014-01-01 | 2014-01-01 | Currently, I'm using raw SQL like this SELECT P.email, P.id as pk ,B.started as video_started_1 ,C.started as video_started_2 ,D.started as video_started_3 FROM Profile P LEFT JOIN video_log B ON P.id = B.profile_id AND B.video_id = 1 LEFT JOIN video_log C ON P.id = C.profile_id AND C.video_id = 2 LEFT JOIN videlo_log D ON P.id = D.profile_id AND D.video_id = 3 Is there anyway to create a set of models that join on more than just the ID? def Profile(models.Model) video1 = models.OneToOneField( 'videos.video_log', related_name='profile_instance', # ... ? ) … -
Change publicly visible URL and but keep URL same internally
In my Django project, I have app A whose views are all URLs beginning with /A. During development, we have been accessing app A's using the full URL, i.e., localhost:8000/A/foo. For launch, we want to map the URLs for app A to the top level domain. If app A has URL /A/foo and the domain is www.a.com, the user should see www.a.com/foo. I set up the following nginx block to internally redirect the user to the right URL for app A: location / { include /usr/local/etc/nginx/uwsgi_params; rewrite / /A$request_uri break; uwsgi_pass unix:/tmp/mysite.sock; } So if the user enters www.a.com/baz, he is actually going to URL /A/baz internally. Throughout the HTML code, there are GET/POST requests that require a page refresh. When such a request is made, I do not want the URL in the browser window to show www.a.com/A/foo, but rather www.a.com/foo. This would require: (1) UWSGI getting URL /A/foo, and (2) having the browser window show www.a.com/foo. How can I do this? I would prefer not to make any changes on the Django side because we have other apps that follow a similar convention. -
Django model field's validators not trigger in ModelForm
I have a model: class Order(models.Model): amount = models.DecimalField(validators=[MinValueValidator(Decimal('2.00'))]) ... Model form: from django.forms import ModelForm class OrderForm(ModelForm): class Meta: model = Order fields = ['amount'] And view: def order_create(request): form = OrderForm(data=request.POST or None) if request.POST and form.is_valid(): # save new order When I try to create Order object in admin interface with amount = 1 - everything is fine, I get: Ensure this value is greater than or equal to 2.00. But when I try to create Order object with amount = 1 using ModelForm - I get no errors, and item successfully saves. What am I doing wrong? Big thx for help -
Parameter missing in django rest swagger for post request
small peace of code used in View for post request is following def post(request): """ Return S3 Url --- parameters: - name: cc_id description: id of the cc required: true - name: businessFlowId description: businessFlowId of the call required: true """ # start a worker process cc_id = request.data.get('cc_id') businessFlowId = request.data.get('businessFlowId') The Django rest swagger is no longer shows the parameter at the api page. Please help. -
ImportError: cannot import name social_auth_usersocialauth: Accessing Python social auth data in django via shell
I am getting log in data from twitter. In my sqlite database, following are the tables: sqlite> .tables auth_group django_content_type auth_group_permissions django_migrations auth_permission django_session auth_user social_auth_association auth_user_groups social_auth_code auth_user_user_permissions social_auth_nonce django_admin_log social_auth_usersocialauth My data is saved into social_auth_usersocialauth table. Query the table using sqlite3 shell gives me the data I fetched from the website. 1|twitter|xx|1|{"access_token": {"oauth_token_secret": "xx", "oauth_token": "xx", "x_auth_expires": "0", "user_id": "xx", "screen_name": "xx"}, "id": xx} Now I want to display oauth_token_secret and oauth_token in my template. I am trying to run following query from django shell to check whether I can fetch data or not. Since my app name is social.apps.django_app.default so I ran the following code: >>> from social.apps.django_app.default.models import social_auth_usersocialauth But it is giving Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name social_auth_usersocialauth trying another name, twitter, which is my app name, I got the same thing. -
django form won't populate decimal value with instance
I have the following form: class SearchDetailForm(forms.ModelForm): price_min = forms.DecimalField(max_digits=8, decimal_places=2, required=False) price_max = forms.DecimalField(max_digits=8, decimal_places=2, required=False) item = forms.ModelChoiceField(queryset=Item.objects.all(), required=False) max_distance = forms.CharField(required=False) sort = forms.ChoiceField(choices=SORT_CHOICES) class Meta: model = Buy fields = ( 'item', 'max_distance', 'price_min', 'price_max' ) The view that implements this form looks like: def market_view(request): max_distance = request.GET.get('max_distance',None) price_min_str = request.GET.get('price_min',None) price_max_str = request.GET.get('price_max',None) price_min = Decimal(price_min_str) price_max = Decimal(price_max_str) item = request.GET.get('item',None) buy = Buy() buy.price_min = Decimal('10.10') buy.price_max = Decimal('10.10') buy.item = Item.objects.get(pk=item) buy_items = Buy.objects.filter(price__lte=price_max,price__gte=price_min).order_by('item') form = SearchDetailForm(instance=buy) context = { 'items':buy_items, 'form':form, } return render(request, 'index.html', context) I set the form instance to buy so that the last searched values would remain on the page. The item attribute remains, but the price_min and price_max do not. What can I have them do to populate in the form instance? -
In django 1.10, how do I handle my urls now that patterns is deprecated?
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r"^$", home), url(r"^storefront/", storefront), url(r"^sell/", get_entry), . ImportError: cannot import name patterns The above is a snippet of my urls.py, is fixing this just a matter of changing my import statement or will I literally need to rewrite my entire urls.py now that the patterns module has been deprecated? -
Django issues with template rendering
I'm facing some difficulties to render pages with Django shortcuts. My workflow is quite simple: Users go a page where they can view some project data (detail_project) If they want to update the project data, they should click a button that will send a POST request and loads update_project page. This page is loaded with current project data. Users update and submit new data. After submission, they are returned to detail_project page. My view is like this: def update_project(request): if request.method == 'POST': if 'update_project_submit' in request.POST: # updates project with form data and returns to detail project page return detail_project(request, project_name) else: # loads project original data into the form return render(request, 'project/update_project.html', context) def detail_project(request, project_name): if request.method == 'POST': if 'update_project' in request.POST: return update_project(request) else: # does another stuff else: # shows project details return render(request, 'project/detail_project.html', context) This code, however, does not works. After loading my update_page with the current data (step 2) and submitting it, the users are imediatly redirect to detail_page and no update action is done. Is there something I am missing? -
Django email not sending no error message but not receiving email
Ok so I know there are a bunch of other StackOverflow questions regarding this; however, I have looked over them all and I am unable to solve this problem. I have everything configured and when I go to send mail it appears to work but I never receive the email. I am unsure what is going on. settings.py EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-relay.gmail.com' DEFAULT_FROM_EMAIL = 'no-reply@email.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'email@email.com' EMAIL_HOST_PASSWORD = os.environ['EMAIL_HOST_PASS'] views.py def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail( subject, message, from_email, ['support@email.com'], fail_silently=False, ) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, "main/contact/contact.html", {'form': form}) of course these are not my actual email addresses - removed for the sake of security/privacy -
Inverting the ModelSerializer order with Django-Rest-Framework
using Python v2.7, django 1.10, DRF 3.X related to my other pending question at: including extra data in Django intermediate table in Django-Rest-Framework Serializer I'm currently getting this from a set of serializers I've built: { "id": 11, "asset_number": "1234", "serial_number": "1234", "name": "Instrument1", "checksum_string": "0123456789ABCDEF0123", "instr_type": { "id": 70, "make": "Make1", "model": "Model1", "service_email": "model1@company.com", "service_website": "www.model1.com" }, "Validated_Versions": [{ "id": 9, "method": { "id": 9, "name": "Method1", "description": "method one description" }, "version_name": "123", "cmd_line_script": "script", "SOP": "SOP" }, { "id": 10, "method": { "id": 10, "name": "Method2", "description": "method two description" }, "version_name": "123", "cmd_line_script": "script", "SOP": "SOP" }, { "id": 12, "method": { "id": 10, "name": "Method2", "description": "method two description" }, "version_name": "456", "cmd_line_script": "script", "SOP": "SOP" }] } but notice there's a lot of redundancy in this data, I want to have it show the method as a child of Instrument, but only for methods which have a version associated to the instrument being serialized. then I want all the versions that are of that method to be listed as children of the method, but excluding any versions of that method which are not validated on the instrument. This is what I want instead: … -
Django site cache doesn't work with sessions
I have not been able to find a way to make Django site caching work, when also making use of sessions. Is this actually the case? My testing seems to show that a URL will only be cached per session (regenerated for each user) so the resulting effect is basically caching per user (not site-wide, per-url). Is there any way at all to get django to cache a URL for ANY user, unless they are logged in, when using sessions? We do make use of the session in some small areas (multi-step forms) so I'm beginning to think that it's actually correct to not cache across sessions for reasons like this. I have seen some solutions that have /admin on a different uwsgi process with sessions enabled, then disabling sessions for all other URLs. This would be problematic for us (the forms) so I'm thinking I have answered my own question as to why it works this way. Is my logic sound? -
Want to work with soap and wsdl on python django
I want to offer a remote procedure call in my django web project. I have a problem: All tutorial i've found on soap and wsdl for python django are from year 2011 or less. I am wondering why there is nothing up to date. Is it a bad thing to work with soap in django ? -
Django Forms: error displaying
I have the following code: {% if form.errors %} <div class="alert alert-danger" role="alert"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> <span class="sr-only">Error:</span> {{ form.errors }} </div> {% endif %} This produced the following: I would like to remove the bullet points and not include the __ all __ part. Any help would be appreciated, many thanks, Alan. Incase it may be helpful the clean part of the form is as follows: def clean(self): cleaned_data = self.cleaned_data # individual field's clean methods have already been called team1 = cleaned_data.get("team1") team2 = cleaned_data.get("team2") if team1 == team2: raise forms.ValidationError("You picked the same team!") return cleaned_data -
Django custom DateField: to_python() to save two fields
I have the following form field that I'm using for my model (which contains two DateField fields) class DateRangeField(forms.DateField): def to_python(self, value): try: values = value.split(' - ') from_date = super(DateRangeField, self).to_python(values[0]) to_date = super(DateRangeField, self).to_python(values[1]) except: raise ValidationError(_("Invalid input")) return from_date, to_date and in my form, I'm only showing one field class EventDateRangeForm(forms.ModelForm): daterange = DateRangeField(required=True) class Meta: model = myModel fields = [] and my model class myModel(models.Model): start_day = models.DateField(blank=False, null=False) end_day = models.DateField(blank=False, null=False) how would I process the form so that when the form is valid, it will save from_date and to_date to start_day and end_day -
Using a URL as a URL parameter in Django Rest Framework
I have a model whose unique field is an address. The thing is, I am trying to get instances of this model using AJAX. var address = 'http://example.com/blog/2/'; $.ajax({ url: 'http://sitemy.com/api/get_content/'+encodeURIComponent(address), type: 'GET', dataType: 'json', success: function(json) { console.log('Success'); } }); In my urls.py, I have the following code: url(r'^api/get_content/(?P<url>.+)/$', views.get_content), So I am trying to use this URL pattern to capture the get request. However, I am constantly getting a 404 error since the url sent from the request does not match my pattern. What gives? How can I solve this? In case its important, in my views, I am doing the following: def get_content(request, address): try: content = Content.objects.get(address=urllib.unquote(address)) except: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ContentSerializer(content) return Response(serializer.data) Any help would be appreciated. Also, I welcome any general advice regarding the encoding of URLS, as that just boggles my mind for some reason. Thanks. -
Django Crispy Forms Rendering Issue 'cannot convert dictionary update sequence element #0 to a sequence'
Struggling to figure this one out. I've seen several issues where this error code shows up but all seem to have to do with data not being passed into the context for the template to render. I know my data is getting through to the template. Crispy forms must be doing something behind the scenes that is throwing me off? Weird thing is this literally worked 20 minutes ago. I don't know what I could have changed that would have affected this. Here is my view: class ContactListView(View): template = 'support_tracker/contact_list.html' def get(self,request,*args,**kwargs): staff_id = kwargs.pop('staff_id',False) if staff_id: staff = Staff.objects.get(pk=staff_id) else: staff = request.user.staff contact_list = staff.contacts.all() search_term = request.GET.get('search_term',False) sort_by = request.GET.get('sort_by',False) filter_by = request.GET.get('filter_by',False) ##applying search term to determine contact_list ... ## ##sorting of contact_list .... ## ##filtering of contact_list .... ## search_form = SearchForm() sort_form = ContactListSortForm() filter_form = FilterByStageForm() ##pagination to determine contacts ... ## context = { 'staff':staff, 'contacts':contacts, 'form':search_form, 'sort_form':sort_form, 'filter_form':filter_form, 'filter_by':filter_by, 'search_term':search_term, 'sort_by':sort_by, } print context return render(request,self.template,context) My Forms: ##forms.py class SearchForm(forms.Form): search_term = forms.CharField(max_length=30,label='') def __init__(self,*args,**kwargs): super(SearchForm,self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_class = 'form-inline' self.helper.form_method = 'GET' self.helper.field_template = 'bootstrap3/layout/inline_field.html' self.helper.layout = Layout( InlineField('search_term',placeholder='Search'), Submit('','Go',css_class='btn btn-primary'), ) class FilterByStageForm(forms.Form): filter_by = … -
How to embed matplotlib graph in Django webpage?
So, bear with me as I'm VERY new to Django, Python, and web-development in general. What I want to do is display a graph that I've made using matplotlib. I had it working to where the home page automatically redirects to the png of the graph (basically a tab in the browser with the graph displayed). However, now what I want is to see the actual homepage with the graph simply embedded. In other words, I want to see the navigation bar, etc. and then the graph in the body of the site. So far, I've searched and I sort of have an idea of how to accomplish this. What I'm thinking is having a special view that simply returns the graph. Then, somehow accessing this png image from an img src tag in my template that I will use to display my data. Graph Code: from django.shortcuts import render import urllib import json from django.http import HttpResponse from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import datetime as dt import pdb def index(request): stock_price_url = 'https://www.quandl.com/api/v3/datatables/WIKI/PRICES.json?ticker=GOOGL&date.gte=20151101&qopts.columns=date,close&api_key=KEY date = [] price = [] #pdb.set_trace() source_code = urllib.request.urlopen(stock_price_url).read().decode() json_root = json.loads(source_code) json_datatable = json_root["datatable"] json_data = json_datatable["data"] for day … -
How to install PostGIS for Django?
So I'm following the DOCS and just want to make sure I'm understanding correctly. https://docs.djangoproject.com/en/1.10/ref/contrib/gis/install/postgis/ Do I just create a file called migrations.py with: from django.contrib.postgres.operations import CreateExtension from django.db import migrations class Migration(migrations.Migration): operations = [ CreateExtension('postgis'), ... ] and drop it in my project directory? And then run python manage.py makemigrations ? -
Interactive Shell on website in django
I have a Django project up and running. I'd like to provide a user to interactively use JDB through the web app to debug an application. I want that the user can issue a command such as stop in [function name] next And that he would get the back the response and then can proceed. When I use os.system however, like so: def AttachDebugger(pid): # enable port forwarding adb = ADB() adb.set_adb_path('~/Library/Android/sdk/platform-tools/adb') adb.forward_socket('tcp:8001', 'jdwp:' + pid) # attaching os.system('jdb -connect com.sun.jdi.SocketAttach:hostname=localhost,port=8001') then it opens up a JDB session in the background, but it freezes there and doesn't return control to the python code except stopping it via CTRL+C. Is there any way to provide such an interactive session? What I would like to have is similar to the GITHUB-Tutorial-Page here: https://try.github.io/levels/1/challenges/1 where the user can interact with the JDB instance Thanks in advance. -
Django View does not update Template Using Ajax
so I got a Django template which has a form (in which a user can enter Integers) and a Button which sends the value of the form to the server using Ajax. Based on this Information the context should be adjusted (Number of Days). Template: <!-- Form which accepts User Input/Integer --> {% for field in form.visible_fields %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{field|add_class:'form-control'}} {% for error in field.errors %} <span class="help-block">{{error }}</span> {% endfor %} <button type="button" id="submit" type="submit">Submit</button> {{field.id_for_label}} </div> {% endfor %} </br> <!-- Context which should be changed based on entered value by user --> <table> <tr> <th>Date</th> <th>League</th> <th>Time</th> <th>Home Team</th> <th>Away Team</th> </tr> {%for match in matches %} <tr> <td>{{match.date|date:"d/m/y"}}</td> <td>{{match.league.league_name}} <td>{{match.time}}</td> <td><a href={{"../../teams/"|addstr:match.home_team.team_name|cut:" "}}>{{match.home_team.team_name}}</a></td> <td>{{match.away_team.team_name}}</td> <td>{%endfor%} </table> </div> AJAX/JScript (basically copied from a tutorial) $("#submit").click( function(e) { e.preventDefault(); var csrftoken = getCookie('csrftoken'); var days_bet = $('#id_bet_date').val(); //This is the Ajax post.Observe carefully. It is nothing but details of where_to_post,what_to_post $.ajax({ url : window.location.href, // the endpoint,commonly same url type : "POST", // http method data : { csrfmiddlewaretoken : csrftoken, days_bet : days_bet, }, // data sent with the post request }); View: #Context changes based on date_value entered by … -
Django - Two Users Accessing The Same Data
Let's say that I have a Django web application with two users. My web application has a global variable that exist on the server (a Pandas Dataframe created from data from an external SQL database). Let's say that a user makes an update request to that Dataframe and now that Dataframe is being updated. As the Dataframe is being updated, the other user makes a get request for that Dataframe. Is there a way to 'lock' that Dataframe until user 1 is finished with it and then finish the request made by user 2? EDIT: So the order of events should be: User 1 makes an update request, Dataframe is locked, User 2 makes a get request, Dataframe is finished updating, Dataframe is unlocked, User 2 gets his/her request. Lines of code would be appreciated!