Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does context={'request': self.request} need in serializer?
Today I dig into django-rest-auth package a bit. And I have no idea what context={'request': self.request} for in get_response and post function. They say context parameter is for including extra context to serializer. But below the codes, it seems not necessary to put context parameter. Is there something I have missed? context: http://www.django-rest-framework.org/api-guide/serializers/ django-rest-auth : https://github.com/Tivix/django-rest-auth/blob/master/rest_auth/views.py def get_response(self): serializer_class = self.get_response_serializer() if getattr(settings, 'REST_USE_JWT', False): data = { 'user': self.user, 'token': self.token } serializer = serializer_class(instance=data, context={'request': self.request}) else: serializer = serializer_class(instance=self.token, context={'request': self.request}) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request, *args, **kwargs): self.request = request self.serializer = self.get_serializer(data=self.request.data, context={'request': request}) self.serializer.is_valid(raise_exception=True) self.login() return self.get_response() -
Do I remove STATIC & MEDIA roots when using AWS S3 storage with my Django project?
I'm following this tutorial to integrate AWS S3 storage to my django project. It involves adding a ~/project/app/aws/conf.py file which includes: MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' does this mean I should remove the MEDIA_ROOT and STATIC_URL from ~/project/app/settings.py? (and also MEDIA_URL and STATIC_ROOT?) -
Modifying Django internal tables
I am working on a Django application which requires some DDL modifications for internal tables generated by Django. For example on running migration django creates a table called django_session with the following create table command. I got this command after running migration and then taking DB dump. -- -- Table structure for table `django_session` -- DROP TABLE IF EXISTS `django_session`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `django_session` ( `session_key` varchar(40) NOT NULL, `session_data` longtext NOT NULL, `expire_date` datetime(6) NOT NULL, PRIMARY KEY (`session_key`), KEY `django_session_expire_date_a5c62663` (`expire_date`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; I am using MySQL as my database. The team setting up the DB has constraints and recommendations when setting up the DB. One of them is to build primary key constraint only on column id, and add unique constraint to session_key. There are modifications to other tables as well. Is there a way to change table structure for internal tables in Django? -
Python Django Cookie Path Issue
I am using python3.4 and Django 1.9.6, Cookies are save with different path, but when i want to fetch only global path cookie is get on different url. -
Django custom admin action - How to write a admin action that calculate a field value depending on other model field values?
I have this scenario: In which I need to calculate a field value from values of other models fields. And that calculation should be done by custom admin action. -
Dynamically populate a choice field and get the non-chosen fields in the post data
I have a form where I'm trying to compare two objects (Cards) that are randomly selected from the database. In my form, I tried to dynamically populate a choicefield with the two cards, and in the view I'm trying to create an object (CardComparison(winning_card,losing_card)) with the choice of the user. I've overwritten the __init__ of the form to dynamically populate the card choices, and it's working fine. The problem is that when the user selects a card, it only passes the selected card, and I'm not able to figure out which card is NOT chosen in the view. I'm new to Django, and I've realized the more I struggle with this, a dynamic choice field may not be what I actually want to use, so a suggestion for a better method would also be greatly appreciated. forms.py: def get_new_comparison(): left_card = #get a random card (code hidden for cleanliness) right_card = #get a second random card left_card_choice = (left_card, left_card.name) right_card_choice = (right_card, right_card.name) return [left_card_choice, right_card_choice] class CompareCardsForm(forms.Form): def __init__(self, *args, **kwargs): post_flag = False if kwargs.get('post_flag'): post_flag = kwargs.pop('post_flag') super(CompareCardsForm, self).__init__(*args, **kwargs) if post_flag and len(args) > 0: card_name = args[0].get('cards_to_compare') card_obj = Card.objects.get(name=card_name) card_choice = [(card_obj,card_name)] self.fields['cards_to_compare'] … -
Django how to display multiple fields on the same row using ModelForm class
I'd like to display two fields on the same line when I use ModelForm class as follows, company name : my company yearend : mm / dd But, but I don't how to customize field arrangement like this. #models.py class Companies(models.Model): co_name = models.CharField(max_length=120) yearend_mm = models.IntegerField(null=True, blank=True) yearend_dd = models.IntegerField(null=True, blank=True) #forms.py class CompaniesCreateForm(forms.ModelForm): class Meta: model = Companies forms.html '''''' <form method='POST'> {% csrf_token %} <table> {{ form|crispy }} </table> <button type='submit'>Save</button> </form> ...... -
Heroku Django 503 Error
Is Heroku telling me that I'm cheap? What does this mean? I keep getting an H10 code 503 error message. I read the guides but it doesn't explain why the dyno keeps crashing. -
Moving multiple models from one django app to another
I'm building a project using django v2.0.2 that consists of 3 apps with 24 models. One of the apps has 14 models. Having so many models in one app is becoming complicated, and I'd like to create a new app and move few models to this app. I found an answer explaining how this can be done using south. I've been using django core migrations and since south is deprecated, I don't want to switch to south at this point. The models I want to move are quite complex - they have ForeignKey fields, ManyToMany fields, etc. I need a workflow showing how I can move these models using django core migrations. -
how to use bokeh add_periodic_callback function in Django
I am trying to implement bokeh live chart in django. I got some reference in one website. They used add_periodic_callbackfunction in curdoc() to refresh the chart. This is working fine by running bokeh serve filename.py. I tried this in django by using this code in my view.py def bokeh(request): import numpy as np from bokeh.layouts import column from bokeh.models import Button from bokeh.palettes import RdYlBu3 from bokeh.plotting import figure, curdoc import pandas as pd # create a plot and style its properties p = figure(x_axis_type="datetime", title="EUR USD", plot_width=1000) p.grid.grid_line_alpha = 0 p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' p.ygrid.band_fill_color = "olive" p.ygrid.band_fill_alpha = 0.1 # add a text renderer to out plot (no data yet) r = p.line(x = [], y = [], legend='close', color='navy') i = 0 ds = r.data_source # create a callback that will add a number in a random location def callback(): global i a = fxdata()[0] ## this script will return EURUSD forex data as list ds.data['x'].append(np.datetime64(str(a[1]))) ds.data['y'].append(np.float(a[2])) ds.trigger('data', ds.data, ds.data) i = i + 1 # add a button widget and configure with the call back button = Button(label="Press Me") # button.on_click(callback) # put the button and plot in a layout and add to the … -
How to test my views function using Django unit testing?
I have a Django app called sample. I need to check a function inside sample app's views.py file. When I try to import the function , I get an error saying sample.views is not a package. I am trying to import the function like this : from sample.views import samplefunc What am I doing wrong ? Thanks in advance -
github. Is importing enough?
If I wanted to incorporate a password strength meter from this page https://github.com/aj-may/django-password-strength, do I need to copy the 'django_password_strength' folder and paste it into my project or will doing the 'pip install django-password-strength' and then 'from django_password_strength.widgets import PasswordStrengthInput, PasswordConfirmationInput' take care of it? Sorry I'm a noob. The instructions don't make this clear, and I've never done something like this from github. -
How can i improve performances when using django queryset?
I'm trying to make a news feed. Each time the page is called, server must send multiple items. One item contain a post, number of likes, number of comments, number of comment children, comments data, comment children data etc. My problem is, each time my page is called, it takes more than 5 secondes to be loaded. I've already implemented a caching system. But it's still slow. posts = Posts.objects.filter(page="feed").order_by('-likes')[:'10'].cache() posts = PostsSerializer(post,many=True) hasPosted = Posts.objects.filter(page="feed",author="me").cache() hasPosted = PostsSerializer(hasPosted,many=True) for post in post.data: commentsNum = Comments.objects.filter(parent=posts["id"]).cache(ops=['count']) post["comments"] = len(commentsNum) comments = Comments.objects.filter(parent=posts["id"]).order_by('-likes')[:'10'].cache() liked = Likes.objects.filter(post_id=posts["id"],author="me").cache() comments = CommentsSerializer(comments,many=True) commentsObj[posts["id"]] = {} for comment in comments.data: children = CommentChildren.objects.filter(parent=comment["id"]).order_by('date')[:'10'].cache() numChildren = CommentChildren.objects.filter(parent=comment["id"]).cache(ops=['count']) posts["comments"] = posts["comments"] + len(numChildren) children = CommentChildrenSerializer(children,many=True) liked = Likes.objects.filter(post_id=comment["id"],author="me").cache() for child in children.data: if child["parent"] == comment["id"]: liked = Liked.objects.filter(post_id=child["id"],author="me").cache() -
About frameworks using web dev
Programming Beginner here. I've been thinking about what to do for my first web application. However, sometimes I look at Python frameworks and get confused. For example, though people often say Django is for medium or large projects while Flask is for smaller ones, I'm not even sure what exactly a small, medium, or large web application entails. Also, how do you decide what kind of framework is suitable or unsuitable for a project? And what happens when you try to use a framework meant for small applications on a large application? Finally, is what you can make dependent on the framework you use? Please answer in a way even a beginner can understand -
Production.py issue with deployment of cookiecutter-django and gunicorn to digital ocean
I built a Django project using the latest version of cookiecutter-django, which seems to be working fine on my local computer as well as when I run it through python manage.py runserver using the various settings files. I'm trying to test my Gunicorn server on Digital Ocean (running Ubuntu 16.04) but for some reason can't get the server to run properly when production.py is the one being used. When I do the following command on bash: gunicorn --bind 0.0.0.0:8000 --env DJANGO_SETTINGS_MODULE=config.settings.test --preload config.wsgi everything works fine and I get these: [2018-02-18 23:31:14 -0500] [31662] [INFO] Starting gunicorn 19.7.1 [2018-02-18 23:31:14 -0500] [31662] [INFO] Listening at: http://0.0.0.0:8000 (31662) [2018-02-18 23:31:14 -0500] [31662] [INFO] Using worker: sync [2018-02-18 23:31:14 -0500] [31666] [INFO] Booting worker with pid: 31666 But when I don't specify the settings file and default to production.py with gunicorn --bind 0.0.0.0:8000 --preload config.wsgi, where the environment variable DJANGO_SETTINGS_MODULE is set to config.settings.production, I only get these: DEBUG 2018-02-18 23:31:55,786 base 31681 140442914699008 Configuring Raven for host: <raven.conf.remote.RemoteConfig object at 0x7fbb5cc0b668> INFO 2018-02-18 23:31:55,786 base 31681 140442914699008 Raven is not configured (logging is disabled). Please see the documentation for more information. And it pretty much just gets stuck there. What might … -
trying to delete inactive users in django
I am writing a site that sends confirmation emails on signup. Until the user clicks the link, the is_active field is set to false. How can I automatically delete any users who do not click the activation link within a certain period of time? Is this even a viable option or is there a better way to work around users who never confirmed their accounts? Thanks for any help! -
Django somehow accesses the static files even after i had deleted the whole static folder
I am new to Django, I had placed the static files in the project level static folder and even in multiple applications inside the app/static/app directory. Everything was working fine until I decided to delete few of the static files. The project is surprisingly accessing the deleted static files i.e images and stylesheets. I even had deleted both the static and the staticfiles folders and it still would access the static files that I had placed in these folders. Following is a code snippet from my setting.py file. STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ('accounts', os.path.join(BASE_DIR, 'accounts', 'static')), ('transport_resources', os.path.join(BASE_DIR, 'transport_resources', 'static')),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Whatever I do with those static files, it still manages to access the old and even deleted files. I am assuming that it keeps a cache of the files that we had used previously if this is the case, how can we clear that cache. Thanks! -
How correctly reorganize Django settings?
I am trying to reorganize my settings.py file with django-split-settings app. I use next structure but it raise error. It seems to me that I miss something. Can someone say me whats wrong I make? I have next error: ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. P.S. Database settings are correct. With next settings I can run project with python manage.py runserver command without any problem. Error happens when user try to go to any link of the project. structure: project_name/settings/ <- folder where Django by default create settings.py file __init__.py components __init__.py common.py secret_key.py database.py environments __init__.py development.py production.py __init__.py: # -*- coding: utf-8 -*- from split_settings.tools import include from os import environ ENVIRONMENT = 'development' or 'production' base_settings = [ 'components/common.py', 'components/secret_key.py', 'environments/%s.py' % ENVIRONMENT, ] include(*base_settings) common.py: # -*- coding: utf-8 -*- import os from django.core.urlresolvers import reverse_lazy BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = ['127.0.0.1'] DEFAULT_CHARSET = 'utf-8' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.forms', 'django_select2', # "django-select2" application 'modeltranslation', # "django-modeltranslation" application 'reversion', # django-reversion application 'custom_app_1', # "custom_app_1" application 'custom_app_2', # "custom_app_2" application 'custom_app_3', # "custom_app_3" application 'el_pagination', # django-el-pagination application 'custom_app_4', # 'custom_app_4' application … -
django models multiple table inheretence: can I remove the OnetoOnefield link with the parent class for only one field in the childModel
So in the example code below I'm trying to remove the OneToOnefield link between 'type2' and the Child class to avoid confusion and make things neater. I tired chucking the 'parent_link' kwargs in the desired field however that didn't work. class Parent(models.Model): type = models.CharField() type2 = models.CharField(parent_link=False)## class Child(Parent): different_type = models.CharField() different_type2 = models.CharField() -
Different session cookie for each authentication backend
I have an application with multiple authentication backends and I am wondering if it is possible to have different cookie for each backend to reference sessions of each backend separately. The application is made of a central django rest framework API that is linked to 2 frontend apps. The 2 apps are on the same domain but have their own base url (ex: app 1 : https://basedomain/app1/... ; app2 : https://basedomain/app2/...) Each app have it's own authentication backend. The authentication backends are linked to the same User model. -
Using HTTPResponse to return prettified dictionary
I'm trying to return a HTTPResponse object that is prettified JSON. I know that the indent parameter for json only works when you're printing. And printing converts an argument to a string. So shouldn't the indent parameter work if I just str() on my JSON before returning it? def conversationview(request, convo_identification): data = InputInfo.objects.all() conversation_identification = convo_identification #conversation_id = {'conversation_id': []} header = {'conversation_id': '', 'messages': []} entry = {} output = {} for i in data: if str(i.conversation_id) == conversation_identification: header['conversation_id'] = i.conversation_id entry = {} entry['sender'] = i.name entry['message_body'] = i.message_body entry['date_created'] = str(i.created) header.get('messages').append(entry) #parsed = json.loads(header) convert_to_json = json.dumps(header, sort_keys=True, indent=4) output = str(convert_to_json) return HttpResponse(output) -
Django many-to-many relationship gives "IntegrityError: could not create unique index"
I don't know much about Django. I'm taking over a project that was started by another developer. I have two models, in two apps: crawler/Publisher search/Collection In the database, we've been collecting some data about publishers, such as: name address website phone number Collection has a relationship to Users. The users can create their own collections, and add publisher data to those collections. If they want to gather publishers who focus on medicine, they can create a collection called "medicine." I added this line to crawler/Publisher: # publishers -> collections search_collection = models.ManyToManyField('search.SearchCollection', through='search.SearchPublisherCollection') Then I run: python manage.py make migrations python manage.py migrate django.db.utils.IntegrityError: could not create unique index "crawler_publisher_website_145c5f8f_uniq" DETAIL: Key (website)=(https://brandenbooks.com) is duplicated. It's true that we have some duplicate data, but why does Django care? I don't care. How do I make this error go away? And why is Django creating an index on the website field? -
Read data from local text file using CBV
so I have a python program which looks for words in a string that user typed in. I have the words save in a text file. I want to implement the same program in Django. I will have page that will allow user to input the string in a textbox then once the submit button is clicked, it will load the words that matches in my text file. I want to know what is the best approach to do this in Django using CBV? I've seen some post related to reading data from a file but most of them are in FBV. Any suggestions will be highly appreciated. -
Deleting selected rows in DataTable and Django
I've made a selectable rows checkbox using DataTables. I have created a good UpdateView for this so far, so editing items are good. How can I do something like a "Delete selected items" button using that? Here's what I've done so far.. Datatables .js script: $(function () { $('#table-part').DataTable({ dom: 'Bfrtip', responsive: true, buttons: { buttons: [ { extend: 'selectAll', className: 'bg-red waves-effect' }, { extend: 'selectNone', className: 'bg-red waves-effect' }, { extend: 'copy', className: 'bg-red waves-effect' }, { extend: 'csv', className: 'bg-red waves-effect' }, { extend: 'excel', className: 'bg-green waves-effect' }, { extend: 'print', className: 'bg-red waves-effect' }, ], }, 'columnDefs': [{ 'targets': 0, 'orderable': false, 'className': 'select-checkbox', 'checkboxes': { 'selectRow': true } }], 'select': { 'style': 'multi', }, 'order': [ [1, 'asc'] ] }); }); Here's what it looks like: I'm confused as to how can I use the class-based DeleteView in Django. I need something that gets all the id based on what rows I have selected, also, I need to have something like a conditional check that if I didn't select any rows to delete, the delete function won't continue, or it would be disabled, or something like that. Thank you very much in advance! -
How can I delete a repeated dictionary in list?
for dynamic values sometimes the value will be keep repeating, say if a variable table = [{'man':'tim','age':'2','h':'5','w':'40'},{'man':'jim','age':'4','h':'3','w':'20'},{'man':'jon','age':'24','h':'5','w':'80'}, {'man':'tim','age':'2','h':'5','w':'40'},{'man':'tto','age':'7','h':'4','w':'49'}] here {'man':'tim','age':'2','h':'5','w':'40'} dictionary set repeat twice these are dynamic value, How can I stop repeating this, so list will not contain any repeated dictionary before rendering it to templates?