Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What do I do git clone ,pip install ,easy install timed out?
enter image description here What do I do git clone connection timed out,pip install timed out ,easy install timed out complaining about an IP address I must have used along time ago when I was connected to a network and saying a port 8888 is timed out for my git enter image description here -
Django two projects, same database
I try to set up two projects, The first is a management project - it involves auth_user, sessions, writing to db. The second project is a "serve content" project, it only read from the db, uses no sessions, users.. It rely on db data created in the first project, but does not change it. The second project urls will be accessed very frequently. That's why I want to seperate the projects, with different subdomaons, and two apache instances, giving the second one more "power" (processes in wsgi deamon conf). So what should I share between the projects? Same settings? SECRET_KEY? Models? I assume I should also remove session app. Can I set django db to be in read only mode? -
Django filters. is_safe doesn't work
In my app teams/templatetags/teams_extras.py I have this filter from django import template register = template.Library() @register.filter(is_safe=True) def quote(text): return "&laquo; {} &raquo;".format(text) So I use it into my view teams/templates/teams/show.html {% extends './base.html' %} {% load static %} {% load teams_extras %} ... <b>Bio :</b> {{ team.biography|quote }} ... But this is the result on my page: &laquo; <p>The Miami Heat are an American professional basketball team based in Miami. The Heat compete in the National Basketball Association as a member of the league's Eastern Conference Southeast Division</p> &raquo; Why ? Thank you -
Django model form {is_valid()}
I have my form and I detect that the program is not entering into the is_valid() because after submitting it redirects me to welcomeUser.html, which is in the else of the if: is_valid(). I don't know what else to try. Thanks in advance models.py from django.db import models class User(models.Model): user_name = models.CharField(max_length=10) user_alias = models.CharField(max_length=10) user_password = models.CharField(max_length=10) user_community = models.CharField(max_length=10) user_email = models.EmailField(max_length=10) user_points = models.IntegerField(blank=True, null=True) user_ratio = models.FloatField(blank=True, null=True) forms.py from django.forms import ModelForm from models import User class UserForm(ModelForm): class Meta: model = User exclude = ['user_points', 'user_ratio'] views.py from django.shortcuts import render from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.core.context_processors import csrf from django.template import RequestContext from models import User from forms import UserForm def signup(request): if request.method == 'POST': form_to_sign_up = UserForm(request.POST) if form_to_sign_up.is_valid(): new_user = form_to_sign_up.save() new_user.save() return HttpResponseRedirect('signupsuccess.html') else: return render_to_response('welcomeUser.html') else: form_to_sign_up = UserForm() return render_to_response('sign_up.html', {'form': form_to_sign_up}, context_instance=RequestContext(request)) def signupsuccess(request): users = User.objects.all() return render_to_response('signupsuccess.html', {'users': users}) def home_user(request): return render(request, 'home_user.html') -
Using dynamic variable in Django Model.objects.filter()
I am facing issues with using dynamic variable after submitting form the in Model.objects.filter(). Added my source code below- user_check = UserForm(request.POST) if user_check.is_valid(): user_id = user_check['user_id'] #Submitted '9a26b3e5-1892-439b-b392-1779a043ca1a' get_user = User.objects.filter(id=user_id) num_of_user = get_user.count() If I use direct assignment i.e. user_id = '9a26b3e5-1892-439b-b392-1779a043ca1a' get_user = User.objects.filter(id=user_id) num_of_user = get_user.count() then I get 1 for num_of_user but id submitted through form submission always result 0. Also, after submitting the form then I was able to view the submitted user id back to my frontend template. Thanks in advance! -
'UserProfile' object has no attribute 'id'
I have an update form, whem i press updated for the form to update the user profile it I get the error "'UserProfile' object has no attribute 'id'" my models is: from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): user = models.OneToOneField(User, related_name="custom_user_profile", primary_key=True) organization = models.CharField(max_length=100, default='', blank=True) address_line_1 = models.CharField(max_length=100, default='', blank=True) address_line_2 = models.CharField(max_length=100, default='', blank=True) city = models.CharField(max_length=100, default='', blank=True) state = models.CharField(max_length=100, default='', blank=True) post_code = models.CharField(max_length=100, default='', blank=True) country = models.CharField(max_length=100, default='', blank=True) def __unicode__(self): return self.user.username @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: profile, new = UserProfile.objects.get_or_create(user=instance) and my views is: from django.shortcuts import render_to_response from django.shortcuts import HttpResponseRedirect from django.template import RequestContext from django.core.context_processors import csrf from django.contrib.auth.decorators import login_required from user_profile.models import UserProfile from django.contrib.auth.models import User from forms import UserProfileForm from django.shortcuts import redirect @login_required def update_profile(request): userProfile = UserProfile.objects.get(user=request.user) form = UserProfileForm(initial={ 'organization':userProfile.organization, 'address_line_1':userProfile.address_line_1, 'address_line_2':userProfile.address_line_2, 'city':userProfile.city, 'state':userProfile.state, 'post_code':userProfile.post_code, 'country':userProfile.country, }) return render_to_response('user_profile/update_profile.html', {'form':form}, RequestContext(request)) @login_required def profile(request, profile_id): if profile_id == "0": if request.user.is_authenticated: userProfile = UserProfile.objects.get(user=request.user) else: userProfile = UserProfile.objects.get(pk=profile_id) return render_to_response('user_profile/profile.html', {'userProfile':userProfile}, RequestContext(request)) @login_required def send_update_profile(request): if request.method == 'POST': form = UserProfileForm(request.POST) if form.is_valid(): userProfile = UserProfile.objects.get(user=request.user) organization … -
django-autocomplete-light, widget attributes, no placeholder visible
I've implemented autocomplete in my form: related_groups = forms.ModelChoiceField( queryset=UserGroup.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='groups-autocomplete', attrs={ 'data-placeholder': 'Autocomplete ...', 'data-minimum-input-length': 2, }, ) ) Generally, autosuggesting works but the placeholder and minimum input lenght don't (groups-autocomplete is my alias to my view). Are these fields properly written here? I found such an example in official tutorial available here: . Am i missing something here? I'm really confused about that. -
Django - Preselect options in MultipleChoiceField
I have a class form that has the forms.MultipleChoiceField in it. I am able to render it and show all the choices to select / highlight, but what I want is the choices that get displayed to be pre-highlighted. so it is up to the user to either deselect the options or leave them as they are when they submit the form. Is there a way to do this ? Thanks -
Show 404 page error on django
def handler404(request): return render(request, '404.html', status=404) error showing 404.html not found. Tips for creating 404 ‘page not found’ and 500 ‘server error’ templates in Django -
Django - loading image in another folder
I make local album program using django. but i can't load another folder(Django static and Django Folder) local image load image path is c:\~~ or select user can i how load another folder image in django? -
collectstatic permission denied error django python
i've a problem running collectstatic on my project in django 1.10. Here is the static root in my setting.py file: STATIC_URL = os.path.join(BASE_DIR, 'static/') STATIC_ROOT = os.path.join(BASE_DIR, '/static/') And the privileges in the three are set to 777, so it shouldn't be a problem for django to access the directory, but still i'm getting: python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Copying '/usr/lib/python2.7/site-packages/django/contrib/admin/static/admin/img/icon-no.svg' Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/usr/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle collected = self.collect() File "/usr/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/usr/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 347, in copy_file self.storage.save(prefixed_path, source_file) File "/usr/lib/python2.7/site-packages/django/core/files/storage.py", line 54, in save return self._save(name, content) File "/usr/lib/python2.7/site-packages/django/core/files/storage.py", line 321, in _save os.makedirs(directory) File "/usr/lib/python2.7/os.py", line 150, in makedirs makedirs(head, mode) File "/usr/lib/python2.7/os.py", line 150, in makedirs makedirs(head, mode) … -
No module named channels when running django web app
Today when I run my webapp written in django, it throws the following exception: python webapp/manage.py runserver Traceback (most recent call last): File "webapp/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/tiendh/news_harvester/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/tiendh/news_harvester/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/Users/tiendh/news_harvester/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/tiendh/news_harvester/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/tiendh/news_harvester/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named channels It runs well before without any problem. I tried to search for a solution but I couldn't find anything. Can you give me a suggestion? Thanks. -
Producing a list by summing results of 'values_list' in Django queryset
Through a Django queryset call, I'm generating a list of integer tuples: [(0,1),(0,2),(0,4),(5,8),.......] I instead need to generate a list which sums the two elements inside the tuple together, i.e. [1,2,4,13,.....] How can I accomplish that within the Django queryset query? The query I've written so far is: photos_score_list = Photo.objects.filter(upload_time__gte=yesterday).annotate(unique_comments=Count('photocomment__submitted_by', distinct=True)).values_list('vote_score','unique_comments') -
Django Apache wsgi uses two python versions
I've installed my Django app on an Ubuntu server with Apache2.4.7 and configured it to use py3.5.2 from a virtual environment. However, from what I can see in the errors, it's starting at 3.5 and defaulting to 3.4. See the error below: SyntaxError at / invalid syntax (forms.py, line 2) Request Method: GET Request URL: http://intranet.example.com/ Django Version: 1.10.1 Exception Type: SyntaxError Exception Value: invalid syntax (forms.py, line 2) Exception Location: /var/www/intranet/formater/views.py in <module>, line 7 Python Executable: /usr/bin/python3 Python Version: 3.4.3 Python Path: ['/var/www/intranet', '/var/www/venv/lib/python3.5/site-packages', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages', '/var/www/intranet', '/var/www/intranet/venv/lib/python3.5/site-packages'] Here's my apache2.conf file: WSGIScriptAlias / /var/www/intranet/intranet/wsgi.py #WSGIPythonPath /var/www/intranet/:/var/www/intranet/venv/lib/python3.5/site-packages WSGIDaemonProcess intranet.example.com python-path=/var/www/intranet:/var/www/venv/lib/python3.5/site-packages WSGIProcessGroup intranet.example.com <Directory /var/www/intranet/intranet> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> What am I doing wrong here? -
Edit view is not showing choice field data in django?
models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) city = models.CharField(default='kottayam', choices=CITY_CHOICES, max_length=150) state = models.CharField(default='kerala', choices=STATE_CHOICES, max_length=150) is_active = models.BooleanField() def __unicode__(self): return str(self.user) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile exclude = ['is_active'] views.py def profile_view(request, username): user = get_object_or_404(User, username=username) profile, created = Profile.objects.get_or_create(user=user) title = request.user.username context = {'profile': profile, 'title': title } return render(request,'profiles/profile_detail.html', context ) form.html <form method='POST' action='' enctype='multipart/form-data' role="form">{% csrf_token %} {{ form|crispy }} <input type='submit' class='btn btn-success' value='Add/Edit Profile' /> </form> Charfield with choices and instances are not visible to edit, could anyone please help? -
Virtual environment python causing Django.core not found error
I am currently experiencing problem with the virtual environment. Using virtual environment wrapper, I used 'workon' to be in that environment. In this enviornment there is a Python 2.7 in Scripts folder and when I run python, it is indeed running this python. When I run django-admin.py it returns the following error: Traceback (most recent call last): File "C:\Users\JOHN\Envs\courseva\Scripts\django-admin.py", line 2, in <module> from django.core import management ImportError: No module named django.core FYI, I installed django and it is within this Envs/courseva folder (Lib/site-packages folder) now. I was curious so I ran python and in the command I tried 'from django.core import management' and it is not throwing an error and I am really confused now. I was concerned with the default Python 2.7 in C: so I even changed the environment path but no use. Please help. -
Taking value from Timefield in a model and Using datetime operations on it.
I am make an appointment booking functionality in an app. For that, I have start and end time of two work shifts. Using values from those two fields, I would like to find total minutes in each shift and then divide it into half hour slots. The problem that I have is this : datetime library expects datetime objects to evaluate a timedelta but all I have are the TimeField. How do I convert TimeField to datetime.time value Below is the model : class ClinicMembershipAttribute(models.Model): DAY_CHOICES = ( ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ('Sunday', 'Sunday') ) clinicmembership = models.ForeignKey(ClinicMembership, null=True, blank=True) day = models.CharField(choices=DAY_CHOICES, null=True, blank=True, max_length=12) shift_one_start = models.TimeField(null=True, blank=True) shift_one_end = models.TimeField(null=True, blank=True) shift_two_start = models.TimeField(null=True, blank=True) shift_two_end = models.TimeField(null=True, blank=True) def get_appointment_status_string(self): first_shift_delta = (datetime.datetime.combine(datetime.date(1,1,1),self.shift_one_start) - datetime.datetime.combine(datetime.date(1,1,1), self.shift_one_end)).time() second_shift_delta = (datetime.datetime.combine(datetime.date(1,1,1),self.shift_two_start) - datetime.datetime.combine(datetime.date(1,1,1), self.shift_two_end)).time() first_shift_seconds = first_shift_delta.seconds() second_shift_seconds = second_shift_delta.seconds() def __str__(self): return self.day + " - '"+str(self.shift_one_start) +" - " + str(self.shift_one_end) + "', '" + str(self.shift_two_start) +" - " + str(self.shift_two_end) + "'" Error is in first_shift_delta and second_shift_delta. -
Parameter order for unittest.TestCase.assertEqual
Is it assertEqual(actual, expected) or assertEqual(expected, actual)? On the one hand I'm seeing lots of code using assertEqual(actual, expected). This includes examples in the unittest docs and examples in the Django docs. However, this test assertEqual('foo', 'bar') is giving me the output - foo + bar Which happens to be the same as for a PHPUnit test with assertEquals( 'foo', 'bar' ); -'foo' +'bar' And PHPUnit has $expected as first parameter, followed by $actual. This diff is also what I'd expect for expected, actual. So is all this Python code I'm seeing doing it wrong? I checked the definition of the unittest method, though that has the extremely helpful first, second parameter names. -
How can i save data without database?
How can i save data from django form template without database and javascript? just use views and template? I have a problem with inserting data on django templates. I just can insert 1x if i insert again the data is renew, cannot adding the data -
Django query data btween date and time
How do I query data between two date and time from django model. I am using below code but it is not working. Here In Db for every second data is populated and from browser every second or minute or hours or current date or week, a Ajax is request sent. However currently I am not filtering the data based upon they date+ time because of this server takes time to respond. Please guide me how do I query data model between date+time tempresult=Realtimekwhrtu1.objects.filter(datetime_published__range=( datetime.datetime.combine('2008-03-27',datetime.time.min), datetime.datetime.combine('2008-03-27',datetime.time.max))) JSON example: { "data": [{ "date": "11/25/2016 08:59:58", "energy": 29940935080, "power": 6815.7056798623, "time": 217781943 }, { "date": "11/25/2016 09:29:59", "energy": 29940981851, "power": 6803.7187250996, "time": 217783743 }, { "date": "11/25/2016 09:59:59", "energy": 29941028913, "power": 6841.5804195804, "time": 217785544 }, { "date": "11/25/2016 10:29:59", "energy": 29941075952, "power": 6845.9247648903, "time": 217787343 }, { "date": "11/25/2016 10:59:58", "energy": 29941123228, "power": 6877.2764478764, "time": 217789143 }] } -
Django Foreign Key duplicate column
I have a prexisting MySQL database that contains a table with a foreign key to another the table. I used inspectdb in Django 1.10 to form the following models from it : class Contested(models.Model): candidate = models.ForeignKey('Candidate',default=None) district = models.CharField(max_length=10) state = models.CharField(max_length=45) num_votes = models.IntegerField() per_votes = models.DecimalField(max_digits=3, decimal_places=2) incumbent = models.IntegerField() year = models.IntegerField() class Meta: managed = False db_table = 'contested' unique_together =(("district","state","year","candidate","num_votes"),) class Candidate(models.Model): first_name = models.CharField(max_length=45, blank=True, null=True) last_name = models.CharField(max_length=45) class Meta: managed = False db_table = 'candidate' However when I attempt to migrate I get django.db.utils.OperationalError: (1060, "Duplicate column name 'candidate_id'") I believe this is because I already have a foreign key relation in my db ( column candidate_id is already in the Contested table), yet Django is attempting to construct the relation itself by adding column candidate_id to the Contested table (although managed is False). Is there a way to for Django to recognize the Foreign key relation already exists? -
Reviewboard 1.6.3 manage.py test run 0 test in 0.000s
I am having a problem running test cases in reviewboard 1.6.3 The structure is goes like this /reviewboard __init__.py settings.py settings_local.py manage.py /reviews __init__.py models.py tests.py I have tried running: python manage.py test but it keeps giving me Ran 0 tests in 0.000s Can someone tell me what am I doing wrong? I just want to run the tests.py Code base is from this repository: https://github.com/reviewboard/reviewboard/tree/release-1.6.x -
'NoneType' object is not callable django cms
I want to store data from template that is not in same directory as views. My form is located in mysite/style.html <-data inserted in this form, I want to pass them in models from another app called "services". /mysite/ is my root directory. <form name = "form" action="{% url 'services.views.add_style' %}" method = "POST" class="form-inline">{% csrf_token %} <input class="form-control" id="style" name="name" placeholder="style" type="style" required> </div> <div class="col-sm-6 form-group"> <input class="form-control" id="color" name="color" placeholder="color" type="color" required> </div> </div> <input class="form-control" id="positions" name="positions" placeholder="positions" type="positions" required> <input class="form-control" id="font_size" name="font_size" placeholder="font_size" type="font_size" required> <input class="form-control" id="background" name="background" placeholder="background" type="background" required> <input class="form-control" id="font" name="font" placeholder="font" type="font" required> <button class="btn btn-default pull-right" type="submit">Send</button> than I have separated app called "services" Here is views.py def add_style(request): if request.method == "POST": style = request.POST.get('style') color = request.POST.get('color') positions = request.POST.get('positions') font_size = request.POST.get('font_size') background = request.POST.get('background') font = request.POST.get('font') Model = style(style=style, color=color, positions=positions, font_size=font_size, background=background, font=font) Model.save() return redirect('/') and models class style(CMSPlugin): style = models.CharField(max_length=30) color=RGBColorField(max_length=30) positions = models.CharField(max_length=30) font_size = models.CharField(max_length=30) background = models.CharField(max_length=100) font = models.CharField(max_length=100) def __str__(self): return self.style Traceback shows error in this line Model = style(style=style, positions=positions, font_size=font_size, background=background, font=font) -
GeoDjango + SpatiaLite - filtering objects in specified radius
models.py -> User and Business model contain this field: location = PointField(geography=True) I'm retrieving via Google Maps Geocode service coordinates from user-input address and then I'm storing it in that field above when saving User and Business object. Now, what I want is to get all nearby Business objects based on user's location: Business.gis.filter(location__distance_lt=(request.user.location, D(km=1))) But it doesn't work, it throws this error: ValueError: SpatiaLite does not support distance queries on geometry fields with a geodetic coordinate system. Distance objects; use a numeric value of your distance in degrees instead. So, does anyone know how to properly solve this? Thanks in advance! -
Django Migration Error in Heroku, but migrate correctly in heroku local
Python 3.5, Django 1.10.3, Sqlite I have deployed a django app in heroku.It ran correctly before. One day I make some change in models.py. I first do python manage.py collectstatic, python manage.py makemigrations, python manage.py migrate, heroku local web -f Procfile.windows, the app run correctly in local. Then I push my code to heroku. I ran: git push heroku master heroku run bash $python manage.py makemigrations $python manage.py migrate heroku ps:scale web=1 But server returned: ProgrammingError at /twitter/blog/ column twitter_article.enable_comments does not exist LINE 1: ...article"."content", "twitter_article"."pub_date", "twitter_a. Here is my key model: from django.db import models from fluent_comments.moderation import moderate_model,comments_are_open, comments_are_moderated from fluent_comments.models import get_comments_for_model, CommentsRelation class Article(models.Model) : title = models.CharField(max_length = 100) category = models.CharField(max_length = 50, blank = True) pub_date = models.DateTimeField(auto_now_add = True) content = models.TextField(blank = True, null = True) pub_date = models.DateTimeField("pub_date") enable_comments = models.BooleanField("Enable comments", default=True) def __str__(self) : return self.title class Meta: ordering = ['-pub_date'] # Optional, give direct access to moderation info via the model: comments = property(get_comments_for_model) comments_are_open = property(comments_are_open) comments_are_moderated = property(comments_are_moderated) # Give the generic app support for moderation by django-fluent-comments: moderate_model(Article, publication_date_field='pub_date', enable_comments_field='enable_comments', ) If I drop my database and build a new database. Server won't …