Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"SignatureDoesNotMatch" error when trying to connect AWS S3 storage to Django
I've gone through this tutorial to implement AWS S3 storage to my django project. I've completed everything up until the very final step where it says to run python manage.py collectstatic. When I perform python manage.py collectstatic it says: You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? I say yes and then it returns: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/james/postr/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/james/postr/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/james/postr/env/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/james/postr/env/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/james/postr/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/home/james/postr/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/home/james/postr/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 354, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/james/postr/env/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 260, in delete_file if self.storage.exists(prefixed_path): File "/home/james/postr/env/lib/python3.5/site-packages/storages/backends/s3boto3.py", line 475, in exists if self.entries: File "/home/james/postr/env/lib/python3.5/site-packages/storages/backends/s3boto3.py", line 290, in entries for entry in self.bucket.objects.filter(Prefix=self.location) File "/home/james/postr/env/lib/python3.5/site-packages/storages/backends/s3boto3.py", line 288, in <dictcomp> self._entries = { File "/home/james/postr/env/lib/python3.5/site-packages/boto3/resources/collection.py", line 83, in __iter__ for page in self.pages(): File "/home/james/postr/env/lib/python3.5/site-packages/boto3/resources/collection.py", line 166, in pages for … -
Error when I creating django application in visual studio
When I create a django application in VS and I press the project name (in the solution expoler) -> python -> django create supreser (=> 1.7) there is such an error - Traceback (most recent call last): File "путь к проекту\manage.py", line 15, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The interactive Python process has exited. The interactive Python process has exited. and when I start the project - ModuleNotFoundError: No module named 'django' points to the string - from django.core.management import execute_from_command_line Although both python and django, the latest version is installed. Why is that? -
Advanced Django: validators within the model? UUID Field?
I'm tasked to develop a system that tracks how many times a certain task has been completed and which it was. The user who gives the tasks should be able to choose dynamically how many times that task should be completed. I think if you read the 'pseudo'-models you will understand: class Taskoverview(models.model): user = models.Foreignkey(User, related_name = 'taskoverviews') company = models.Foreignkey(Company, related_name = 'taskoverviews') limit = models.PositiveSmallIntegerField(default=5) done = models.PositiveSmallIntegerField(default=0) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) class Task(models.model): taskoverview = models.Foreignkey(Taskoverview, related_name = 'tasks') category = models.CharField(max_length = 120) worth = models.PositiveSmallIntegerField(default=1) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) In this example the limit declares how many tasks should be done and the done counter counts how many tasks have been done. I want to know: How can I do it, so that each 'worth' of task is allways one? Meaning that a task can't be made where worth is two? How can I ensure that a task can't be assigned to a taskoverview, if it would increase it's 'done'-counter to more that the 'limit'? How can I ensure the UUID is allways 32 digits long? Is there any method to set the first two digits of the UUID manually? Meaning can … -
Connecting Django to Hive
My requirement is to display few of Hive table data (aggregated value) in front-end once the user clicks on certain links. After searching the net felt Django framework would suit the need and tried to build the app, with just the standalone python script am able to access hive data and print in IDLE shell, however I am not sure how to fetch and display the same data using Django, searching till now has resulted in methods to connect to oracle (here), MongoDB (here) and MySQL (here), code to connect to hive as below, wanted the result of this to be printed in front-end: from impala.dbapi import connect import pandas as pd #PROD conn = connect(host='xxxxxx', port=yyyyy, auth_mechanism='PLAIN', user="rrrrrr", password="tttttt") #Enter your query here query = "select * from table1 limit 5" print('connected') cur = conn.cursor() try: cur.execute(query) names = [ x[0] for x in cur.description] rows = cur.fetchmany(1000) for row in rows: print (row) -
Do we also create content char field in models. I want to know the standard practice
New to Django and web development in general. For a blog post I understand we create model fields for author, publish date, title, category etc.My question is do we also create content char field or some other field in models for the content. I want to know the standard practice. I don't want the content to be purely restricted to the text I also want it to include images, embedded videos etc. is it possible to achieve this within the admin panel? -
call_command makemigrations does not work on EBS
I have a scenario, where I need to create a table dynamically, To create the table dynamically I have written code to create a model.py file with the table content that I want to create. Once this file get created then I want to perform the makemigrations command from the code itself like from django.core.management import call_command call_command('makemigrations') call_command('migrate') it is working fine in my local as well in AWS EC2 instance, but it is not working into the Elastic Beanstalk (eb). and when I'm trying to run the makemigrations command manually from the eb ssh then it gives me the following error. PermissionError: [Errno 13] Permission denied: '/opt/python/bundle/47/app/quotations/migrations/0036_dynamic_table.py' Anyone have any idea how can I handle this situation. One Other thing is that as I'm creating new dynamic models So how can I push that code to the git, as on new deployment EBS will replace the existing code to new code, so in this way I will lose the files that I created in EBS using these commands Thanks -
from django.shortcuts import reverse ImportError: cannot import name 'reverse'
I am getting this error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f78dfe090d0> Traceback (most recent call last): File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/webapps/onehyr/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/webapps/onehyr/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/webapps/onehyr/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/webapps/onehyr/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/webapps/onehyr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/webapps/onehyr/ladislist/blog/models.py", line 5, in <module> from django.shortcuts import reverse ImportError: cannot import name 'reverse' Here are my imports in model.py from django.contrib.auth.models import User from django.db import models from django.shortcuts import reverse from django.utils import timezone, html from django.utils.safestring import mark_safe Django version is 2.0.1 It was all working perfectly until I installed django-grappelli. Now even after uninstalling it, I still face the same issue. Like … -
User Model Serializer required Validation Error
I want to create a registration app for my project. Here is my serializer: from rest_framework import serializers from rest_framework.validators import UniqueValidator from django.contrib.auth.models import User from rest_framework import serializers from django.contrib.auth import get_user_model # If used custom user model UserModel = get_user_model() class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) user.set_password(validated_data['password']) return user class Meta: model = User fields = ('id', 'username', 'password','email','first_name','last_name') write_only_fields = ('password',) read_only_fields = ('id',) As you see, I use UserModel which is one of the default models of rest_framework. I want to make first_name field required for my registration serializer. Waiting for your help. -
include does not work in a template on live instance in django 1.11
I work with django 1.11 and I have a problem with include at base.html. When I work on localhost - everything is OK. The problem starts when the code goes live, on the server. The problem is here: {% include "pages/menu.html" %} -
How to perform .delete() queryset in Django in a ListView?
Here is what I've done so far: 1.) I've made a javascript function that gets all the id's of the items (using checkbox select) in the database like so (this is DataTables): function () { // count check used for checking selected items. var count = table.rows( { selected: true } ).count(); // Count check. // Count must be greater than 0 to delete an item. // if count <= 0, delete functionality won't continue. if (count > 0) { var data = table.rows( { selected: true } ).data(); var list = []; for (var i=0; i < data.length ;i++){ // alert(data[i][2]); list.push(data[i][2]); } var sData = list.join(); // alert(sData) document.getElementById('delete_items_list').value = sData; } } It outputs something like 1,2,5,7 depending on what rows I have selected. 2.) Passed the values inside a <input type="hidden">. Now, I've read a post that says you can delete data in Django database using a checkbox, but I'm not sure how exactly can I use this. I'm guessing I should put it in the ListView that I made, but how can I do that when I click the "Delete selected items" button, I can follow this answer? I'm trying to achieve what Django Admin … -
Django - Dictionary errors when saving multiple selection boxes in one form
I need to save multiple selections in one form, but I keep getting a MultiValueDictKeyError. This is how the form looks: This is my models.py class ChoiceManager(models.Manager): def rates (self, Assignment_id, rating, year): assignment = assignment.objects.get(assignment=Assignment_id) yo = year rate = rating rated = Choice.create( assignment = assignment, fy = year, rating = rating ) class Choice(models.Model): rating = models.ForeignKey(Rating, related_name="picks") year = models.ForeignKey(FiscalYear, related_name="choices") assignment = models.ForeignKey(Assignment, related_name="choice") objects = ChoiceManager() This is my views.py def task_rating(request, Assignment_id): rates = Choice.objects.rates(Assignment_id,request.POST['rating'], request.POST['year']) return redirect ((reverse('Project:assignment_page', kwargs={'Assignment_id': Assignment_id}))) HTML <div> <ul> <form action="{% url 'Project:task_rating' Assignment_id=tasks.id %}" method'POST'> {% for year in years %} <li class=cap_select> <div id=fyc>{{year.fy_year}}</div> <select name="rating"> <option>Choose From List</option> {% for cap in caps %} <option value="{{cap.rating}}">{{cap.rating}}</option> {% endfor %} </select> <input type="hidden" name="year" value={{year.fy_year}}> </li> {% endfor %} <br> <input id=save_cap type="submit" value="Save"> </form> </ul> </div> How can I save the rating for each year? -
Serializing wagtail image chooser
I didn't find information about that. And I'am not sure if it possible to do. So i have following Page models and their relationships: class TeamRooster(Page): team_logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) @register_snippet class GroupstageTournamentModel(ClusterableModel): team_1 = models.ForeignKey( TeamRooster, null=True, verbose_name='Erste Team', on_delete=models.SET_NULL, related_name="+", ) class GroupstageScreencastRelationship(Orderable, models.Model): page = ParentalKey('ScreencastPage', related_name='groupstage_screencast_relationship') match = models.ForeignKey('GroupstageTournamentModel', related_name='match_screen_relationship') panels = [ SnippetChooserPanel('match') ] class ScreencastPage(Page): content_panels = Page.content_panels + [ InlinePanel( 'groupstage_screencast_relationship', label="Choose Teams" ] def matches(self): matches = [ n.match for n in self.groupstage_screencast_relationship.all() ] return matches def serve(self, request): if request.is_ajax(): result = [ { 'team_2_logo': match.team_2.team_logo } for match in self.matches() ] json_output = json.dumps(result) return HttpResponse(json_output) else: return super(ScreencastPage, self).serve(request) Is it possible to get a picture from the TeamRooster model with an ajax request? If I try to do this as shown in the code above, then I get an error: TypeError: Object of type 'Image' is not JSON serializable -
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()