Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How may I ascertain that my content types are indeed stale and can be safely deleted?
Problem Details Deleting a model Author from my appname/models.py resulted in the following warning from Django: The following content types are stale and need to be deleted: appname | author Any objects related to these content types by a foreign key will also be deleted. Are you sure you want to delete these content types? If you're unsure, answer 'no'. Type 'yes' to continue, or 'no' to cancel: Really worried about data loss here, am hitting 'no' at the moment. Another model, Book, was previously ForeignKey-ed to the Author model. In a migration prior to the one above, I'd removed the ForeignKey association between Book and Author by changing the ForeignKey field on Book to some other model. Question Is it possible to check what I might be deleting before I actually do so? I don't want to lose any Book objects. Extra Info I've found the following related Django tickets: #18682 and #24546, but it seems like those features haven't been implemented in Django 1.8.7, which I'm using. I'm probably being worried over nothing, but I've learned that sometimes it's safer to be worried and cautious than not. Thank you for reading. -
Deploying Rapidpro to AWS
I am an absolute beginner in cloud computing to bear with me. I want to deploy a Django application to AWS for testting purposes. The documentation is given here : https://rapidpro.github.io/rapidpro/docs/development/ Can this be deployed on a AWS free-tier for small testing purposes? Can some provide a step-wise guide/tutorial? Any help will be appreciated. Thank you -
Django Integration tests for urls
I have a django app I wanted to write tests for. For now Im writing integration tests for the urls. For my signin test , my url looks like: url(r'^signin/$', login_forbidden(signin), name='signin') and my test looks like: from django.test import TestCase class SigninTest(TestCase): def test_signin(self): resp = self.client.get('/signin/') self.assertEqual(resp.status_code, 200) However I have no idea to test a a longer url, for instance I have one entry in urls like: url( r'^ad_accounts/(?P<ad_account_id>[^/]+)/$', AdAccountDetailView.as_view(), name='campaigns' ), If I repeat the above test I have for the signin page (replacing resp = self.client.get('/ad_accounts/')) returns a failure ====================================================================== FAIL: test_signin (engineoftravel.tests.SigninTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "path/to/project/tests.py", line 7, in test_signin self.assertEqual(resp.status_code, 200) AssertionError: 302 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.103s FAILED (failures=1) -
Django - Filtering inside of get_context_data
Using class-based views in Django, I'm having a problem filering inside of a DetailView. What i would like to get is a list of all movies in a specific genre ie: Movie.objects.all().filter(genre=genre_id). class GenreView(generic.DetailView): model = Genre template_name = 'movies/genre.html' context_object_name = 'this_genre' def get_context_data(self, **kwargs): context = super(GenreView, self).get_context_data(**kwargs) context.update({ 'all_movies': Movie.objects.all().filter(genre=pk), 'all_genres': Genre.objects.all() }) return context I get this error: Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler s\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler s\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi c\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi c\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi c\detail.py", line 118, in get context = self.get_context_data(object=self.object) File "C:\Users\admin\trailers\movies\views.py", line 43, in get_context_data 'all_movies': Movie.objects.all().filter(genre=pk), NameError: name 'pk' is not defined When I tried replacing Movie.objects.all().filter(genre=pk) with Movie.objects.all().filter(genre=kwargs['pk']) I got: Traceback (most recent call last): File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler s\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handler s\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\views\generi c\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) … -
Django: correct URL appears in developer tools but link doesn't use that src
I've created a link in a Django template which appears to lead to the correct URL in the elements pane of the developer tools. But the actual link in the page only goes to localhost. I thought I understood how the Django url template tag worked, but I must be missing something. URL pattern: url(r'^dollhouse/(?P<dollhouse>[0-9]+)$', views.dollhouse, name='dollhouse') Template: {% for workingdollhouse in dollhouses %} <a href src="{% url 'dollhouse' dollhouse=workingdollhouse.id %}">{{workingdollhouse.dollhouse_name}}</a> {% endfor %} Text of element appearing in developer console (hovering over the '"/dollhouse/1"' reveals the intended address of localhost/dollhouse/1): '<a href src="/dollhouse/1">dollhouse1</a>' Actual link just goes to localhost. -
HiddenInput ForeignKey Django
I can't seem to figure out why its not letting me display my ForeignKey fields that I'm passing to the forms on my templates. I researched all over but couldn't figure out an answer with explanation that works. Anyone have any ideas what I'm doing wrong? forms.py class MeetingForm(forms.ModelForm): meeting_date = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Date.objects.all()) person = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Person.objects.all()) class Meta: model = MeetingAttendance fields = ['meeting_date', 'person', 'attended',] Models.py class MeetingAttendance(models.Model): meeting_date = models.ForeignKey('Date', on_delete=models.CASCADE) person = models.ForeignKey('Person', on_delete=models.CASCADE) attended = models.BooleanField() def __str__(self): return "%s - %s" % (self.person, self.meeting_date) Views.py def date_detail(request, slug): people = Person.objects.all() detail = Date.objects.get(slug=slug) MeetingFormSet = formset_factory(MeetingForm, extra=len(people)-2, max_num=len(people)) if request.method == "POST": form = MeetingFormSet(request.POST) if form.is_valid(): formset = form.save(commit=True) formset.save() return redirect('date_detail', slug=slug) else: initial_data = [{'person': person, 'meeting_date': detail} for person in people] form = MeetingFormSet(initial=initial_data) context = { 'form': form, 'people': people, } return render(request, 'date_detail.html', context) Template <div class="directory panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Meeting Details</h3> </div><!-- end paneil-heading --> <div class="panel-body"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} </div> -
Why not use static methods for CBV's?
Pycharm was suggesting that I make my CBV methods static, and I thought "why not". But there's got to be a reason that this isn't done, otherwise a lot of people smarter than myself must've thought to do this before. Now I'm trying to understand why it isn't done. I read the tutorial in the documentation again, and the only place self is used is to refer to the objects methods, which themselves could be static. So I still don't see any reason that they shouldn't be all made static. http://www.django-rest-framework.org/tutorial/3-class-based-views/ I tried making them static in my project, and it seemed to work without any issue. So would someone please explain to me why these methods are not made static as a common practice? FBV's are static, so CBV's should very well be using staticmethods as well, right? -
Django-Haystack returns no results in search html
I am using Django-Haystack with elasticsearch backend. When I do a query I get no results on HTML. so, I tried the debugging steps suggested in the Haystack docs by typing the following into a Django shell, and I can see that all the text I want has been indexed. class BasicSearchView(SearchView): template_name = 'search.html' queryset = SearchQuerySet().models(EnMovielist)[:10] form_class = SearchForm url.py url(r'^search/', BasicSearchView.as_view(), name='search_view'), serarch.html {% for result in page.object_list %} {% if result.object.name %} <table class="table table-striped table-hover" cellspacing="0" id='result_table'> <thead> <tr> <th>a</th> <th>b</th> </tr> </thead> <tbody> <tr class="active"> <td><a href="{% url 'actress_detailview' result.object.name %}"><img src="http://52.221.245.150/media/enActress/{{result.object.image_paths}}" class="img-circle" class="img-responsive" alt="{{result.object.name}}"></td> <td>{{ result.object.name }}</td> </tr> </tbody> </table> What else can I try? -
Error : The program 'django-admin' is currently not installed
But it is installed, coz when I run python -m django --version it shows 1.10.1. But when I try to start some project django-admin startproject mysite or check the version with django-admin --version , it shows The program 'django-admin' is currently not installed. You can install it by typing: sudo apt-get install python-django` I'm using ubuntu 14.04. I'm new to django, I was just trying to follow some tutorial to learn it and faced this issue. -
docker-compose on windows directory sync
Running the django tutorial for docker compose, but the command to init the django project is not working as expected. $ docker-compose run web django-admin.py startproject composeexample . [31mERROR[0m: Interactive mode is not yet supported on Windows. Please pass the -d flag when using `docker-compose run`. In windows "interactive" mode is not supported so I modified the command to run in "detached" mode. $ docker-compose run -d web django-admin.py startproject composeexample . Creating network "djangotest_default" with the default driver ... Successfully built 0fb90648c1d8 [33mWARNING[0m: Image for service web was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`. djangotest_web_run_1 This seems to create the boxes.. but my current directory shows no new files (from the django-admin command). $ ls docker-compose.yml Dockerfile requirements.txt How do I get the container output to sync with the current working directory as expected? -
Django - Filtering inside of get_context_data
Using class-based views in Django, I'm having a problem filering inside of a DetailView. What i would like to get is a list of all movies in a specific genre ie: Movie.objects.all().filter(genre=genre_id). class GenreView(generic.DetailView): model = Genre template_name = 'movies/genre.html' context_object_name = 'this_genre' def get_context_data(self, **kwargs): context = super(GenreView, self).get_context_data(**kwargs) context.update({ 'all_movies': Movie.objects.all().filter(genre=kwargs['pk']), 'all_genres': Genre.objects.all() }) return context I get an error saying: AttributeError: module 'movies.views' has no attribute 'genre' even though genre is an attribute of Movie: Movie class: class Movie(models.Model): title = models.CharField(max_length=511) release = models.DateField(null=True, blank=True) director = models.ManyToManyField(Person, related_name="directed_movies") actors = models.ManyToManyField(Person, related_name="acted_movies") genre = models.ManyToManyField(Genre) I can't seem tofigure out a way around it, any help would be appreciated! -
how to prepare a a general computer( usually people use ) as django production server?
it is my first question, may not be clearly asked. but mainly I just wanna make my linux mint based pc a production server for run my django project as a production version. What can I do? -
Django pagination error, int has no len
@csrf_exempt def board_searched(request): searchStr = request.GET['searchStr'] pageForView = request.GET['pageForView'] contact_list = Board.objects.filter(title__contains=searchStr).count() paginator = Paginator(contact_list, 10) # Show 25 contacts per page contacts = paginator.page(1) return render(request, 'board/board_searched.html', {'contacts': contacts}) This views.py code, that processing search in board. And I give the link http://127.0.0.1:8000/board/search/result/?searchStr=asd&pageForView=1 In this case, It occurred 'object of type 'int' has no len()' And, It occurred at contacts = paginator.page(1) What is the problem..? -
django-threadedcomments: 'RequestContext' object has no attribute 'META'
I try to use django-threadedcomments But when I add into template {% load threadedcomments_tags %} I get error on this lines {% render_comment_list for publication %} {% render_comment_form for publication %} 'RequestContext' object has no attribute 'META' But if I use django_comments with {% load comments %} it's work -
Django cache causing WSGIRequest.META to disappear
In my code, I need to extract some information from the WSGIrequest, especially from the META header (doc here), but my code checks for dupe before executing the request process. from django.core.cache import cache dupe = cache.get(key) if not dupe: cache.set(key, 1, 30) # where key is previously set. It uses some unique id to be part of it so there's no worry for repeated cache key else: return request_process(wsgirequest) request_process mainly extracts info from COOKIES and META. Since it's not really the issue here, I'm not going to post the code. Now, I printed the request before and after the cache operation, and the META mysteriously disappeared after the operation. I searched online and found nothing. The cache operation has nothing to do with the request itself. I don't understand why the META just went away and why just META. Of course moving the request_process in front of the cache operation solves the issue, but I mainly want to know the reason behind it. -
Nginx Not Serving Static Files (Django + Gunicorn)
nginx.conf server { listen 80; server_name serveraddress.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ec2-user/projectname; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/ec2-user/projectname/projectname.sock; } } settings.py STATIC_URL = '/static/' STATICFILES_DIR = '/home/ec2-user/projectname/static/' STATIC_ROOT = '/home/ec2-user/projectname/static/' If I run the server using the Django development server with manage.py runserver or with gunicorn, all the static files work perfectly, but using nginx on port 80, none of the static files work; which leads me to believe that it's an issue involving nginx. And yes, I've ran python manage.py collectstatic and 'django.contrib.staticfiles' is installed. I'm using RHEL 7 (Centos 7). Nginx error.log 2016/09/22 20:44:33 [error] 322#0: *371 open() "/home/ec2-user/projectname/static/css/home.css" failed (13: Permission denied), client :##.###.##.##, server: ##.###.###.###, request: "GET /static/css/home.css HTTP/1.1", host: "##.###.###.###", referrer: "http://##.###.###.###/" -
Loading dumped data with --natural-foreign throws error int() argument must be a string or a number, not 'list'
When dumping data using ./manage.py dumpdata app --indent 2 --natural-foreign -o app/fixtures/dev.json I am getting an error when I try to load this same file using ./manage.py loaddata dev saying TypeError: Problem installing fixture '/path/to/project/app/fixtures/dev.json': int() argument must be a string or a number, not 'list' I figured this is due to the --natural-foreign argument, which dumps the foreignkeys like "created_by": [ "admin" ] If I manually edit the fixture file and replace this by "created_by": 1 it's working fine. I know it was working before, but we haven't touched the fixtures for a while, and now that I'm trying to bring this back up to date, I'm getting this error. Is there a way to tell the loaddata command to interpret the foreignkeys correctly ? -
How can e-commerce sites remember my cart list even after I close browser and revisit?
I want to know how e-commerce sites(e.g Amazon) remember my shopping cart list even though I didn't login at all before. It still showing my cart list even I close all browser and revisit it. Do they make session not to expire even after closing its browser? I'd like to implement this in Django and need your advices. Thanks :) -
sentry-youtrack plugin: PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed
I'm trying to integrate youtrack into sentry using this plugin. The problem is the page seems to hang when we click More --> Create YouTrack Issue. Looking at the syslog, I saw this: Traceback (most recent call last): File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/utils/decorators.py", line 29, in _wrapper return bound_func(*args, **kwargs) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/utils/decorators.py", line 99, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/utils/decorators.py", line 25, in bound_func return func(self, *args2, **kwargs2) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/web/frontend/base.py", line 172, in dispatch return self.handle(request, *args, **kwargs) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/web/frontend/group_plugin_action.py", line 25, in handle response = plugin.get_view_response(request, group) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/plugin.py", line 113, in get_view_response return super(YouTrackPlugin, self).get_view_response(request, group) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/plugins/base/v1.py", line 296, in get_view_response response = self.view(request, group) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/plugin.py", line 131, in view return view(request, group, **kwargs) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/plugins/bases/issue.py", line 169, in view form = self.get_new_issue_form(request, group, event) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/plugin.py", line 77, in get_new_issue_form project_fields=self.get_project_fields(group.project), File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/plugin.py", line 57, in get_project_fields return cached_fields(self.get_option('ignore_fields', project)) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../sentry_youtrack/utils.py", line 16, in wrapper cache.set(key, result, timeout) File "/usr/local/sentry/local/lib/python2.7/site-packages/sentry/../django/core/cache/backends/memcached.py", line 82, in set self._cache.set(key, value, self._get_memcache_timeout(timeout)) File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line 740, in set return self._set("set", key, val, time, min_compress_len, noreply) File "/usr/local/sentry/local/lib/python2.7/site-packages/memcache.py", line … -
Sort data in template from list
I am getting the following output from my ListView: [<Book: Sample Title>, <Chapter: Chapter 1>, <Chapter: Chapter 2>, <Author: John Doe>] I want to be able to display this data in a table, but sort it based on Book, Chapter, and Author. Is there a way to group these separately using Django templates? views.py: class SearchListView(ListView): def get_queryset(self, *args, **kwargs): query = self.request.GET.get('q', None) books = Book.objects.filter(name__icontains=query) chapters = Chapter.objects.filter(title__icontains=query) authors = Author.objects.filter(name__icontains=query) all_results = list(chain(books, chapters, authors)) return all_results -
Accessing a named view from a template in django
Suppose I have two Apps AppA and AppB |_AppB | |_urls.py # url(r'^create/', views.user_profile, name="name_user_profile"), | |_AppA |_urls.py |_templates |_file.html Now in file.html I have something like this {% block content %} Success !!! goto <a href={% url name_user_profile % }> Manage Profile </a> {% endblock %} However name_user_profile cant be recognised ? Is there anything i have to do to get it recognised ? -
Kombu error after upgrade
I upgraded to Ubuntu 16, which introduced a bug in Kombu caused by some minor changes in Python's standard library. This was fixed by upgrading Kombu, but now when I try to run syncdb or migration in my Django 1.5 install, I get the error: File "~/myproject/.env/local/lib/python2.7/site-packages/kombu/transport/django/migrations/__init__.py", line 18, in <module> raise ImproperlyConfigured(SOUTH_ERROR_MESSAGE) ImproperlyConfigured: For South support, customize the SOUTH_MIGRATION_MODULES setting to point to the correct migrations module: SOUTH_MIGRATION_MODULES = { 'kombu_transport_django': 'kombu.transport.django.south_migrations', } I tried making the change, as the error suggests, but I still get the identical error. How do I run Kombu>=3.0.30 with Django 1.5? I can't upgrade to Django 1.5 yet, due to a huge number of dependencies and legacy code that do not yet support higher versions. -
django-tables2 : Error during template rendering
I am writing a simplest possible example of django-table2 it fails with Error during template rendering In template /myproject/app/templates/test_table.html, error at line 2 Any clue what's wrong here. just following document. context 1 {% load render_table from django_tables2 %} 2 {% render_table table %} 3 model.py class TestTable1(models.Model): col1 = models.CharField(max_length=1, primary_key=True) col2 = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'test_table1' class TestTable1Tbl(tables.Table): class Meta: model = TestTable1 attrs = {"class":"paleblue"} views.py def test_table_org(request): table = TestTable1.objects.all() tmpl = loader.get_template("test_table.html") cont = Context({'TestTable1':table}) return HttpResponse(tmpl.render(cont)) template $ more test_table.html {% load render_table from django_tables2 %} {% render_table table %} -
Login / register using phone or email for django, allauth integration
I want to modify my django user model to allow phone or email registration / login. Using USERNAME_FIELD = 'identifier' If the user registers with phone number, the identifier will be its phone number, or email, vice versa. (If anyone think I should just assign some number as the identifier, let me know.) Here is my accounts.models: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from phonenumber_field.modelfields import PhoneNumberField class UserManager(BaseUserManager): def create_user(self, email, phone, password, **kwargs): """ Creates and saves a Account with the given email or phone and password. """ now = timezone.now() identifier = '' if not email: if not phone: raise ValueError('Users must have a valid email or phone address.') else: identifier = phone if not phone: if not email: raise ValueError('Users must have a valid email or phone address.') else: email = self.normalize_email(email) identifier = email user = self.model(email=email, phone=phone, identifier=identifier, joined=now, **kwargs ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **kwargs): user = self.model( email=email, is_staff=True, is_superuser=True, **kwargs ) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(null=True, blank=True, unique=True) phone = PhoneNumberField(null=True, blank=True, unique=True) joined = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=200, null=True, blank=True) last_name = models.CharField(max_length=200, null=True, blank=True) is_staff = … -
Change admin static location in django
Because of some limitation in the server I'm using I can't have the word 'admin' at all in any of my urls. I've managed to change the admin site url to something different. But Django's admin static files are served from STATIC_URL/admin/path/to/file. Is there any way to change the word 'admin' to something else in these cases?