Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Downloading file from Google Driva and sending the file as HttpResponse to clientside via Google Drive python client
I have Django 1.10 project in which I have a module for working with Google Drive data. Currently my goal is to download a file from Google Drive to the local PC of the user. As of now, I have the following code: def a_files_google_download(request): #... service = build("drive", "v2", http=http) download_url = file.get('downloadUrl') resp, content = service._http.request(download_url) fo = open("foo.exe", "wb") fo.write(content) I am stuck at this point and don't know how to pass the file as HttpResponse. Clearly, I don't know the file type in advance. It can be .mp3, .exe, .pdf...And the code should work irrespective of the file type. Also, I don't want to send the file as a zip-file. Is it possible ? Help me please with this ! -
Adding tastypie rest functionality to an already functional application django
I have a fully function web app written in django 1.10. A new request came stating that the application should expose a limited amount of functionality to an external app. Their choice was tastypie. I visited http://django-tastypie.readthedocs.io/en/latest/cookbook.html#using-your-resource-in-regular-views and it is in fact possible but that will require me to rewrite the web app in the functions required. My views are as in normal django app tho all of them (except the home page which renders the homepage), accept and return JSON which is then displayed on the screen via angular.js (UX guy choice). I am not sure how but this is my current view for e.g.: @login_required def on_going(request): ''' Show ongoing tasks of the user ''' tasks=Tasks.objects.filter(ongoing=True,user=request.user).values('id','started_on') tasks_listed=list(tasks) data=json.dumps(tasts_listed,default=defaultJSONSerializer) return httpResponse(data,content_type='application/json') I get the resource via the url: localhost:7900/tasks/on-going Now basically, I want the same resource to come via an API call such as the following: localhost:7900/api/1/tasks/on-going/?api-key=sdfdsafad I have 25 such functionalities to expose and I am curious to know if there is an easier way to expose them to the calling external function using its API keys? -
django 'taggit' error--can't set attribute- "self.to=to"
hello i am getting error while migrating my model. i have just installed 'taggit' module in my project with pip and when i make migrations, it is showing me error, "self.to=to", can't set attribute. if anyone could please help me out from this. models.py- from django.db import models from django.contrib.auth.models import User from taggit.managers import TaggableManager class Post(models.Model): STATUS_CHOICES= ( ('draft','Draft'), ('published','Published'),) slug=models.SlugField(max_length=250,unique_for_date='publish') author=models.ForeignKey(User,related_name='blog_posts') body=models.TextField() status=models.CharField(max_length=50,choices=STATUS_CHOICES, default='draft') tags = TaggableManager() -
django can't relabel empty label in ModelChoiceField
I can't seem to relabel the empty label in a form's ModelChoiceField. I have tried. (note I am using django crispy forms for the form layout - shouldn't interfere with this) Forms.py class PaymentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['payment_day'].empty_label = 'test something' self.helper = FormHelper(self) self.helper.label_class = 'sr-only' self.helper.form_tag = False self.helper.layout = Layout( ...... PrependedText('payment-day', '<i class="fa fa-calendar"></i>', placeholder="What"), ) class Meta: model = DirectDebit fields = [ ...... 'payment_day', ] models.py class DirectDebit(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) ...... DAYS_OF_MONTH_CHOICES = [(i, i) for i in range(32)] payment_day = models.IntegerField(choices=DAYS_OF_MONTH_CHOICES) time_stamp = models.DateField(auto_now=True) -
Django: consume web API through manage.py shell
In my seemingly never ending project to consume JSON from a web API that is behind OAuth2, I think I am finally at a point to integrate it into Django. My first attempt was to create a PostgreSQL foreign data wrapper, which didn't really get anywhere. You can find my various questions regarding it here: Consume Dynamics CRM Web API directly into PostgreSQL database in Django web app Building Python3 auth proxy server between PostgreSQL and Dynamics 365 Web API PostgreSQL 9.2 using www_fdw to public web API results in "Failed to connect to...: permission denied" Combine proxy.py and custom auth.py file to have authorized connection to data source I have abandoned that idea for just using Django, Django REST Framework (DRF), and consuming the JSON that way. I was able to get a pure Python project to connect to the API, store in JSON, and print to console. Now I am at the point of integrating it into Django/DRF, but am having difficulty... there is a light at the end of the tunnel, but I am probably aiming well above my actual skill level. Anyway, I just want to be able to run this from manage.py shell for the … -
django model - fetching user data accross multiple tables
I am writing a django (1.10) website and using allauth for authorisations. I don't want to extend the user model in django - because allauth adds a further layer of complexity to what is already a seemingly convoluted process. I want to create a model (Custom UserManager?) that will have the following methods: get_all_subscriptions_for_user(user=specified_user) get_unexpired_subscriptions_for_user(user=specified_user) Note: unexpired subscriptions are defined by subscriptions whose end_date > today's date. This is a snippet of my models.py below from django.db import models from django.contrib.auth.models import User #... class Subscription(models.Model): token = models.CharKey() start_date = models.DateTime() end_date = models.DateTime() # other attributes class UserSubscription(models.Model): user = models.ForeignKey(User) subscription = models.ForeignKey(Subscription) # In view def foo(request): user = User.objects.get(username=request.user) # how can I implement the following methods: # get_all_subscriptions_for_user(user=specified_user) # get_unexpired_subscriptions_for_user(user=specified_user) Ideally, I would like to have a custom user manager, which can fetch this data in one trip to the database - but I'm not sure if I can have a custom user manager without having a custom user model. [[Aside]] I'm trying to avoid using a custom model, because it wreaks havoc on the other applications (in my project) which have User as a FK. makemigrations and migrate always barf with a message … -
Using Django Channels to send info to all connected clients
I'm creating a system where the Twitter Live Streaming API gets a live stream of tweet data through given keywords. Whenever a tweet comes in, I want to send that new data over WebSockets (using Django Channels) to all connected clients. Here's my current procedure: Twitter live streaming code calls initiateHandshake() function in consumers.py whenever it gets new data Django channels sends the text "handshake" to all clients Client recieves handshake message and sends a message back The websocket.recieve function picks up this message, and, based on filter information that is stored in the client's connection session, sends back the needed data (this is why the handshake is needed - because each client has its own filter that is in its connection session) Right now, the problem is that the "handshake" message in initiateHandshake() isn't sending. Why is this, and how can I fix it? Thank you so much! My code is below. WebSockets is functioning correctly (If the client sends a message, I can use reply_channel to reply to it - that all works) routing.py from channels.routing import route from tweetrunner.consumers import * channel_routing = [ route("websocket.connect", ws_connect), route("websocket.receive", ws_message), route("websocket.disconnect", ws_disconnect), ] consumers.py # In consumers.py from channels … -
Django 1.11.3: Has anyone worked with JavaScriptCatalog?
Does it work? I do according to the documentation settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', _('English')), ('ru', _('Russian')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) urls.py urlpatterns += i18n_patterns( url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), ) shell django-admin makemessages -l ru I'm added translation into locale\ru\LC_MESSAGES\django.po shell django-admin makemessages -d djangojs -l ru django-admin compilemessages But the response from the http://127.0.0.1:8000/ru/jsi18n/ does not contains translate from locale\ru\LC_MESSAGES\django.po Am I doing something wrong? Or is it a bug in the JavaScriptCatalog? -
Post id value from html to Django onclick
i need to change tag name based on list element id without reloading all page or if you has better idea share it with me :D i use django framework with Wagtail CMS i have : blog_index.html {% block content %} {% load static %} {% load wagtailcore_tags wagtailimages_tags %} <ul class="nav nav-pills "> <li id="Latest" role="presentation" class="active"><a href="#">Latest</a></li> <li id="News" role="presentation"><a href="#">News</a></li> <li id="Aricles"role="presentation"><a href="#">Aricles</a></li> <li id="Reviews" role="presentation"><a href="#">Reviews</a></li> </ul> <div class="container" style="padding-top:9px;min-height:396px;width:100%"> <div class="row" style="background-color:#f7d320;"> {% for post in blogpages %} #..... my blog based on models.py class BlogIndex(Page): def get_context(self, request): tag = i want this onclick # Update template context context = super(BlogIndex, self).get_context(request) if onclick : blogpages = BlogPage.objects.filter(tags__name=tag) blogpages = BlogPage.objects.live().order_by('-first_published_at') context['blogpages'] = blogpages return context class BlogPageTag(TaggedItemBase): content_object = ParentalKey('BlogPage', related_name='tagged_items') def main_image(self): content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), FieldPanel('tags'),], heading="Blog information"), FieldPanel('date'), FieldPanel('intro'), FieldPanel('body'), ] -
Django: Trouble redirecting to previous page after cancel editing
I'm working on a blog project where it shows all the posts of a blog on home page. I have an edit function for each blog entry and contains two options: publish and cancel. In views.py it looks like this: def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) In html it looks like this: {% extends 'blog/base.html' %} {% block content %} <h1>Edit post</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default" >Publish</button> <a class="btn btn-default" href="{% url 'post_detail' pk=? %}">Cancel</a> </form> {% endblock %} I could'n figure out what's the pk in html. I have tried pk and post.pk but either works. Anyone can help. Thanks -
Creating database tables for Django dynamic models that use inheritance
So I've recently learned that simply creating dynamic models does not create database tables and in order to do that, I need to take a database-driven approach and use tools such as mutant or south. Considering south is deprecated, my life is a bit harder now! I am using inheritance for my models, and from what I found here, I have not found any solutions that allow inheritance in dynamic models. Does anyone know how to have both inheritance and database tables for my dynamic models? -
Is it possible to skip delegating a celery task if the params and the task name is already queued in the server?
Say that I have this task: def do_stuff_for_some_time(some_id): e = Model.objects.get(id=some_id) e.domanystuff() and I'm using it like so do_stuff_for_some_time.apply_async(args=[some_id], queue='some_queue') The problem I'm facing is that there are a lot of repeat tasks with the same arg param and it's boggling down the queue. Is it possible to apply async only if the same args and the same task is not in the queue? -
Django rest view include one to many related objects in the response
I have two models as following: class Task(models.Model): what_task = models.CharField(max_length=100, ) how_often = models.CharField(max_length=50, ) how_important = models.CharField(max_length=50, ) ) #This helps to print in admin interface def __str__(self): return u"%s" % (self.what_task) class Step(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, ) what_step = models.CharField(max_length=50, blank=True, ) #This helps to print in admin interface def __str__(self): return u"%s" % (self.what_step) I have written serializers for them: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' depth = 1 class StepSerializer(serializers.ModelSerializer): class Meta: model = Step fields = '__all__' And one of my views: @api_view(['GET', 'POST']) def task_list(request): """ List all tasks, or create a new task. """ if request.method == 'GET': tasks = Task.objects.all() serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TaskSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) This gives me data like following: [ { id: 1, what_task: "Sample task one", how_often: "Daily", how_important: "Extremely important", } ] However I want to include related Steps while retrieving tasks like bellow: [ { id: 1, what_task: "Sample task one", how_often: "Daily", how_important: "Extremely important", steps:[] } ] Also, when the user creates a Task he can also create Steps at … -
Django auto submit form?
I want to know if I can submit a form in django without user interaction so that it acts just like when a user posts a form. Here is my situation: User submits data to payment gateway. Payment gateway responds with data which has to be validated. User redirected to payment gateway and more data has to be posted to gateway. One option for me is to render another form for the user after step 2 which can then be used to post the data and redirect for step 3. However the user has to click a button again. I couldn't find anything relevant to my situation about submitting forms with django. Is there a way I can do this without the user interacting again for ease of use? -
Django - get or create dynamically objects with dictionary
Is it possible to use get_or_create to dynamically create/get objects passing a dictionary in which some fields wont be present like in the example? What would be the best way to do something like this? class Car(models.Model): id = models.CharField(max_length=255) name = models.CharField(max_length=255, null=True) brand = models.CharField(max_length=255) drivers = models.ManyToManyField(Driver, related_name='cars') class Driver(models.Model): name = models.CharField(max_length=255) ################ driver = Driver.objects.create(id='foo') for row in cars: # Dictionary might be {'id': foo, 'brand': ford} so without a name field dictionary = { key:value for key,value in row if value is not None } # Passing the dictionary with keys/fields values/values car_object, created = Car.objects.get_or_create(driver, **dictionary) -
Incorrect url pattern match
I'm creating a classifieds website in Django. A single view function handles global listings, city-wise listings, barter-only global listings and barter-only city-wise listings. This view is called ads. The url patterns are written in the following order (note that each has a unique name although it's tied to the same ads view): urlpatterns = patterns('', url(r'^buy_and_sell/$', ads,name='classified_listing'), url(r'^buy_and_sell/barter/$', ads,name='barter_classified_listing'), url(r'^buy_and_sell/barter/(?P<city>[\w.@+-]+)/$', ads,name='city_barter_classified_listing'), url(r'^buy_and_sell/(?P<city>[\w.@+-]+)/$', ads,name='city_classified_listing'), ) The problem is that when I hit the url named classified_listing in the list above, the function ads gets called twice. I.e. here's what I see in my terminal: [14/Jul/2017 14:31:08] "GET /buy_and_sell/ HTTP/1.1" 200 53758 [14/Jul/2017 14:31:08] "GET /buy_and_sell/None/ HTTP/1.1" 200 32882 This means double the processing. I thought urls.py returns the first url pattern matched. What am I doing wrong and what's the best way to fix this? All other calls work as expected btw (i.e. only once). Note: Ask for more information in case I've missed something. -
Django rest view must be callable error
I am building a Django rest project and I have an app created called tasks. My app level urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^api/', include('tasks.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^docs/', include('rest_framework_docs.urls')), ] my app tasks whose urls.py: from django.conf.urls import url from tasks.views import task_list, task_detail urlpatterns = [ url(r'^tasks/$', task_list, name='task_list'), url(r'^tasks/(?P<pk>[0-9]+)$', task_detail, name='task_detail'), ] views are defined like following: from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from tasks.models import Task from tasks.serializers import TaskSerializer # Create your views here. @api_view(['GET', 'POST']) def task_list(request): """ List all tasks, or create a new task. """ if request.method == 'GET': tasks = Task.objects.all() serializer = TaskSerializer(tasks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = TaskSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'PUT', 'DELETE']) def task_detail(request, pk): """ Get, udpate, or delete a specific task """ try: task = Task.objects.get(pk=pk) except Task.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = TaskSerializer(task) return Response(serializer.data) elif request.method == 'PUT': serializer = TaskSerializer(task, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response( serilizer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': task.delete() return Response(status=status.HTTP_204_NO_CONTENT) This gives me TypeError: view must … -
how do i access the values in a session dynamically using django?
(Django , Python) I have created a list of book objects and it is being passed as context in my views.py along with the current session. On my template, i was to check if the books in that list are stored in the session, and if they are i want to access some info relating to that book within that session. how do i access the books in the session dynamically? is there a way? i know i can access them by using "request.session.name" (where "name" is the same of the space in the session it is stored) There are several book titles saved in the session, the way they are saved are as follows (in a function under views.py) request.session["random book title"] = "random dollar price" i want to access that "random dollar price" dynamically in a template. this is the block of code in the template {% for book in book_list %} {% if book.title in request.session %} {{ request.session.??? }} {% endif %} {% endfor %} Thank you in advance! -
Is it possible to run a unit test on a celery periodic task?
I'm trying to run a unit test on a celery task that I have set to run daily. I have tried importing the function and calling it in my test but this doesn't work. The task is: @shared_task def create_a_notification_if_a_product_is_in_or_out_of_season(): """ Send a notification if a product is now in or out of season """ julian_date = date.today().timetuple().tm_yday + 1 active_products = Product.objects.filter(status='ACTIVE') for products in active_products: in_season_prd = ProductDescription.objects.filter(product=products, early_start_julian=julian_date) for prd in in_season_prd: notification = Notification() notification.type = notification_choices.PRODUCT_IN_SEASON notification.description = str(prd.product.name) + " will be in season from tomorrow." notification.save() and here is an example of one of my tests: def test_when_product_is_about_to_come_in_to_seasonality(self): """ Make a notification when a product is due to come in to seasonality tomorrow """ p = Product.objects.first() p.status = "ACTIVE" today = date.today().timetuple().tm_yday p.early_start_julian = today + 1 create_a_notification_if_a_product_is_in_or_out_of_season() updated_notifications = Notification.objects.all().count() self.assertNotEqual(self.current_notifications, updated_notifications) Any help would be appreciated! Thanks -
Excluding subdomains from url using a Django view
I am trying to use subdomains on a Django + Wagtail site. For the starting page, I am using a view and for almost everything else, Wagtail Page are being used. Also, I want to implement subdomains within the site, but when trying to access sub domain index page, instead of the page I set as a index page for this subdomain, I got the index view being served. I tried using django-subdomains app but with not success. Is there a way to create a url pattern to serve a view only if its not on a subdomain? My patterns looks like url(r'^$', views.HomePage.as_view(), name='home'), url(r'^(?!admin/|cms/|ckeditor/)', include(wagtail_urls)), Using Django 1.10.6 and Wagtail 1.9 Any ideas? I tried something in the lines of: url(r'(?!P<subdomain>[a-z]+)$', views.HomePage.as_view(), name='home'), -
Django Drop down user select filtering
I am creating a search page for users and am utilizing drop down menus for each attribute of my object. What I would like to do is filter the drop downs based on user input. This isn't a cascading/chain-select problem. The user can start by selecting any column to search based on what they know about the object. So if they choose a value for y, only the x & z values corresponding with y will appear in the respective drop downs and the same for if they knew a value of x or z. I am having difficulty knowing where I should be putting the ajax query logic since I am relatively new to Django and what is possible since I am dynamically adding values to my list from a database. I can currently get all the unique items into drop down menus and return results based on user input, but the drop down options are not filtered based on the previous user input. I currently do not use Django Forms in my code to create the drop down menus. models.py For constraint reasons I only have one model and cannot break them up to include Foreign Keys, which … -
Django submit button is not responding
I am trying to construct a simple webpage that takes in multiple user inputs, then displays them on another page when the user hits submit. Unfortunately my submit button is not responding-when I click on it nothing happens. Below is the HTML code for the search results: enter code here <html> <head> <title>Search results</title> </head> <body> {% if hashtags.type()==None and user.type()==None and before_date.type()==None and since_date.type()==None %} <p>You searched for tweets.</p> {% elif hashtags.type()==None and before_date.type()==None and since_date.type()==None %} <p>You searched for tweets from user <strong> {{ user }}</strong>.</p> {% elif hashtags.type()==None and user.type()==None and before_date.type()==None %} <p>You searched for tweets dated no earlier than <strong>{{ since_date }}</strong>.</p> {% elif hashtags.type()==None and user.type()==None and since_date.type()==None %} <p>You searched for tweets dated no later than <strong> {{before_date}}</strong>.</p> {% elif hashtags.type()==None and before_date.type()==None %} <p>You searched for tweets from user <strong> {{user}}</strong> dated no earlier than <strong>{{since_date}}</strong>.</p> {% elif user.type()==None and since_date.type()==None %} <p>You searched for tweets with hashtags <strong> {{hashtags}} </strong>dated no later than <strong> {{before_date}} </strong>.</p> {% elif since_date.type()==None and before_date.type()==None %} <p<You searched for tweets with hashtags <strong> {{hashtags}} </strong> from user <strong>{{user}}</strong>.</p> {% elif hashtags.type()==None and user.type()==None %} <p>You searched for tweets dated between<strong> {{since_date}} </strong> and <strong>{{before_date}}</strong>.</p> {% … -
Django Haystack raw_search query syntax
Using Django Haystack for searching an index. Like below: SearchQuerySet().exclude(django_id__in=self.user_existing_news_items).filter(keywords=feed.keywords).values_list("source_id", flat=True)[:total] The user_existing_news_items gets big for heavy user. Which hits limitation of max_clause_count configuration for Elasticsearch. Wanted to use raw query using must_not as filter those user_existing_news_items. Tried differently to accomplish that with Haystack, could not figure that out. result = SearchQuerySet().raw_search("keywords:mobile NOT django_id:95991") works fine for single djnago id. But the following does not negate specified django ids result = SearchQuerySet().raw_search("keywords:mobile NOT django_id:[95991, 70413]") The goal is to transfer following Elasticsearch request to Haystack Search querySet raw_search: curl -XPOST http://localhost:9200/_search -d '{"query":{"bool":{"must":[{"term":{"keywords":"mobile"}}],"must_not":[{"ids":{"values":[95991, 70413]}}]}}}' Any hints on the syntax for raw search for above mentioned in query will be helpful. -
django- Exception Value: No module named urls
i am new to stackoverflow.sorry for improper write. Qn)i created urls and views folder, like templates but it is not working. i am getting above error. i tried hard. help me out. requirements.txt: Django==1.6.5 pymongo==2.8 . ├── DjangoProject │ ├── DjangoProject │ │ ├── app │ │ │ ├── __init__.py │ │ │ ├── __init__.pyc │ │ │ ├── models.py │ │ │ ├── models.pyc │ │ │ ├── templates │ │ │ ├── tests.py │ │ │ ├── urls │ │ │ │ └── test.py │ │ │ └── views │ │ │ └── test.py │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── settings.py │ │ ├── settings.pyc │ │ ├── urls.py │ │ ├── wsgi.py │ │ └── wsgi.pyc │ └── manage.py └── requirements.txt settings.py file : INSTALLED_APPS = ( 'DjangoProject.app', ........ ) ROOT_URLCONF = 'DjangoProject.app.urls' DjangoProject/urls.py : urlpatterns = patterns('', url(r'^$', include('DjangoProject.app.urls')), url(r'^admin/', include(admin.site.urls)), ) app/urls/test.py : from django.conf.urls import patterns, url urlpatterns = patterns('DjangoProject.app.views.test', url(r'^/create/$','first_view',name='first_view'), ) app/views/test.py : from django.shortcuts import render, render_to_response from django.http import HttpResponse from django.template import loader from django.template import RequestContext def first_view(request): return HttpResponse("Hi") -
Django View Unit Tests when the View Accesses an Elasticsearch Index
I have a Django view where a user fills out and submits a form. The data is taken from this form and a document is created in an Elasticsearch index. My question, is how can I test this view without impacting my Elasticsearch index? It is a development index, but I would prefer not to muddle it with unit test data. One option would be to create the record in the unit test and then delete it during tear down - but, if possible, I would really like to avoid touching the index at all. Are there any other options?