FAQ Database Discussion Community


Add a boolean field if a row exists in another table?

python,django,django-rest-framework,django-1.7
I have two tables called Post and Reply. The users can create just one Response for each Post. The models look like this: class Post(models.Model): name = models.CharField(max_length = 100) class Reply(models.Model): post = models.ForeignKey(Post, related_name = 'replies') Now, I have a view that returns the posts, like this: class...

Urllib2 and JSON Object Error

python,django,python-3.x,urllib2,django-1.7
I am following a tutorial to add 'Search Function' in my project. However the tutorial is based on Python2x & Django 1.7 while I am using Python 3.4 & Django 1.7. The search code uses bing_search along with urllib2. However urllib2 is not supported in Python 3 and the same...

Can't import a class - import error

python,django,django-1.7
My app looks like this: myproject - my_app1 -- lib --- my_module1 ---- __init__.py ---- file1.py ---- file2.py ---- file3.py -- views.py In lib/my_module1.file1.py class MyClass1(...):..... And this gives me an import error: In views.py I have: from my_module1.file1 import MyClass1 #Not found Why is that?...

In django1.7 , Can one many to many relationship have another many to many relation?

many-to-many,relationship,django-1.7
In Django 1.7 , Can one many to many relationship have another many to many relation ? class KeyValues(models.Model): value=models.IntegerField(max_length=1,blank=True) class Key(models.Model): position=models.IntegerField(max_length=1,default=0,blank=True) keyValues= key=models.ManyToManyField(KeyValues) class FileDetails(models.Model): fileId = models.CharField(max_length = 100,primary_key=True,db_index=True) key=models.ManyToManyField(Key) I wanted to do this type of relation , But I'm getting an error , ERRORS: cloud.Key:...

Django 1.7: serve a pdf -file (UnicodeDecodeError)

python,binaryfiles,python-3.4,django-1.7
I'm trying to serve a PDF file with django 1.7, and this is basically the code that "should" work... it certainly works if I change the content_type to 'text' and download a .tex file with it, but when I try it with a binary file, I get "UnicodeDecodeError at /path/to/file/filename.pdf...

download file in django 1.7

python-3.4,django-1.7
I need to provide a button, once the user click on it It will download a PDF file or Image. I have been tried so many ways out there. non of them works. and I couldn't find any tutorial for this topic....

OpenShift repo not included in path

openshift,django-1.7,paas
I started a Django 1.7 OpenShift instance. When I have python print all of the paths from sys.path I do not see OPENSHIFT_REPO_DIR (/var/lib/openshift/xxxxx/app-root/runtime/repo). When I use https://github.com/jfmatth/openshift-django17 to create a project I do see OPENSHIFT_REPO_DIR in the path. Looking through the example app above I don't see anywhere that...

python: How do i download a file from Google drive using api

python-2.7,google-drive-sdk,django-1.7
I would like to download a file in google drive to my system,using google drive api. How can i implement this ? according to example given at https://developers.google.com/drive/v2/reference/files/get#examples def print_file(service, file_id): """Print a file's metadata. Args: service: Drive API service instance. file_id: ID of the file to print metadata for....

How to deal with the required value which does not have a default value in Django model

django,django-1.7
The version of my Django is 1.7. I have a model named Booking, it has a Boolean field named is_departure, which is used to describe the booking is departure or arrival. class Booking(models.Model): ... is_departure = models.BooleanField() ... When I migrate my app, it will return me a warning that...

Are numerically keyed choices no longer possible in Django 1.7?

python,django,django-1.7
I tried to implement this as a choices variable for a model: >>> choices = ( ... (1, 'Primary'), (2, 'Secondary'), (3, 'Tertiary') ... ) But it failed with this quasi-cryptic error: characters.CharacterArcanumLink.priority: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. Lets see, choices is...

__init__() got an unexpected keyword argument 'mimetype'

django,django-1.7,django-ajax-selects
I am using Django 1.7.4 and django_ajax_selects for AutoComplete. The lookup is failing and i get this error: __init__() got an unexpected keyword argument 'mimetype' The complete stack trace is as below. What could i do to resolve this error? Is it ok that a GET is called instead of...

How to set the default value for existing entries when adding a new column?

django,django-1.7
I have a model in my Django app that requires a new BooleanFieldcolumn to be added. This column should never be null - instead, I'd like all the existing entries to set this field to False. How do I do that? If I just add the new field and set...

django querying multiple tables - passing parameters to the query

python,django,django-1.7
I am using Django 1.7. I am trying to implement a search functionality. When a search term is entered, I need to search all the tables and all the columns for that term in the DB(I have only 7 tables and probably 40 columns in total and the DB is...

AttributeError while using Django Rest Framework with serializers

python,django,serialization,django-rest-framework,django-1.7
I am following a tutorial located here that uses Django Rest Framework, and I keep getting a weird error about a field. I have the following model in my models.py from django.db import models class Task(models.Model): completed = models.BooleanField(default=False) title = models.CharField(max_length=100) description = models.TextField() Then my serializer in serializers.py...

NoReverseMatch for '' in django URLs

python,django,django-1.7,django-1.4
NoReverseMatch at /login/ Reverse for '' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I've located what I think is the error in urls.py urlpatterns = patterns('', url(r'^/?$', 'util.frontpage.frontpage', name='frontpage'), (r'^schedule/', include('schedule.urls')), (r'^user/', include('usermanagement.urls')), (r'^group/', include('groupmanagement.urls')), ) if settings.DEV_SERVER: urlpatterns += staticfiles_urlpatterns() urlpatterns += patterns('',(r'^login/$',...

Django URL does not change after Redirection

python,django,redirect,django-1.7
I'm learning Django 1.7 through an online book "Tango with Django 1.7". This tutorial creates a "Link Directory" which has categories and web links relating to the categories. When I add a page to a category say "django" using following url: http://localhost:8000/rango/category/django/add_page/ I redirect (redirect to category page) after successful...

Change of 'QuerySet' from Django 1.4 to 1.7

python,django,django-queryset,django-1.7,django-1.4
I'm trying to port an app from Django 1.4.15 -> 1.7.3 I've come to a problem where the app have a method in models.py def is_votable(self, user): ''' Decides if the user can vote for him/herself or not ''' if self.rated_by.all().__contains__(user): return False return True the problem I have is...

Django folder structure

django,django-staticfiles,django-1.7
What would be a good structure (best practise) for the folders in a Django application (1.7)? I'm not sure where to put the static data and file Uploads. In all my projects it turns out different, but currently I have something like this (I left out a few obvious folders/files):...

UserProfile in the admin dashboard - doesn't appear

python,django,django-1.7
I want the user to be able to login and logout only, but not edit their profile themselves, only the admin can register and edit the user and their profile. # my_app/models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) field1 = models.CharField(max_length=100, blank=True) field2...

How to create a unique random username for django?

python,django,django-1.7
I want visitors of my page to be able to create entries without registering first. When they register later I want everything they have created within that session to belong to their user account. To achieve that I just want to create blank users with random usernames when entries from...

Adding context variable into change_view not possible because extra_context not a dictionary

django,django-admin,django-1.7
I would like to add a field on the ModelAdmin.change_view() to filter my inline objects. Based on this solution I tried to inject extra_context into it: class ProcessAdmin(admin.ModelAdmin): inlines = [StepInline,] exclude = ('steps',) prepopulated_fields = {'name_slug': ('name',)} def change_view(self, request, extra_context=None): print(extra_context) extra = extra_context or {} extra['filter_form'] =...

Django - Create “hard-coded” groups and permissions

python,django,django-1.7,django-permissions
I need to define some permissions and groups that are used in the models and the views. I know how to do it with permissions (define them in the "Meta" of some models), but it is not clear to me how to do it with groups. Maybe the right thing...

Revert Django 1.7 RemoveField migration

django,django-south,django-1.7,django-migrations
If I have a non-nullable model field, remove it, and create a migration, that migration becomes non-reversible: Consider the following model: class Foo(models.Model): bar = models.TextField() test = models.TextField() # This field is to go away, bye-bye! And migration: # app/migrations/003_remove_foo_test.py class Migration(migrations.Migration): dependencies = [ ('app', '0002_foo_test'), ] operations...

Issues with makemigrations and upgrading to Django 1.7

django-1.7,makemigrations
My team had a project running on Django 1.6 with South and we just upgraded to 1.7. I followed the guide, cleared my old South migrations, ran makemigrations and migrate, and ultimately got my server running so I pushed up the changes to our repository. Now a second developer on...

User Specific Uploads Django 1.7

python,django,django-1.7,ajax-upload
im getting this error "NOT NULL constraint failed: myfiles_document.user_id" what im trying to do is attach files to user ForeignKey so user can only see what they upload im using this app django-file-form here the code for the project model.py class Example2(models.Model): title = models.CharField(max_length=255) class ExampleFile(models.Model): fs = FileSystemStorage(location=settings.MEDIA_ROOT)...

django pass a predicate to filter funtion

django,django-queryset,django-1.7
I have the following code, as you can see only thing that changes is the function call point__distance_gte or point__distance_lte. Is there a way to externalise this function from calling code. def search(): if distance == 50: jobs = list(Job.objects.filter(point__distance_gte=(ref_pnt, D(**distance_from_point)))) else: jobs = list(Job.objects.filter(point__distance_lte=(ref_pnt, D(**distance_from_point))) So something like: def...

troubles with dynamic filtering in generic-display Django

django,django-1.7,django-generic-views
I am trying to display a list of the users. once you select the user you can view the userprofile. the thing is: UserProfile does not work. how to make it works? #views.py class UserList(ListView): model = Userx template_name ='userList.html' class UserProfile(ListView): template_name = 'userprofile.html' def get_context_data(self, **kwargs): self.user= get_object_or_404(Userx,...

'WSGIRequest' object has no attribute 'post' with custom registration form

python,django,forms,django-1.7
I have looked at a lot of posts that had similar issues and the answers did nothing for my code. I am using a custom registration form for a site I'm working on that makes email required. most of the code in it is based off of the one built...

Possible interaction issue between Django 1.7.4 and django-cacheops 2.2.1

python,django,django-1.7,django-cache
I am upgrading a django app from 1.6 to 1.7. The app uses django-cacheops to store the results of a query. After the switch to Django 1.7 the following error is raised on all requests but the first one: Traceback (most recent call last): File "/data/virtualenv/default/lib/python2.7/site-packages/django/core/handlers/base.py", line 204, in get_response...

Django1.7 : 'list' object is not callable

python,django,list,python-2.7,django-1.7
I'm getting 'list' object is not callable. My models.py class KeyValues(models.Model): value=models.IntegerField(max_length=1,blank=True) class Key(models.Model): position=models.IntegerField(max_length=1,default=0,blank=True) keyValues= key=models.ManyToManyField(KeyValues) class FileDetails(models.Model): fileId = models.CharField(max_length = 100,primary_key=True,db_index=True) key=models.ManyToManyField(Key) My code : def Arrangement(fileid,key,user): Key=[] NewKey=[] Key[:0]=key length=len(key) for i in range (0,length):...

Keeping form choice list up-to-date in django

python-2.7,django-forms,django-1.7
I have a form in my admin site where the user is to select a single object from a particular model from a dropdown. thing_choices = [(x.id, x) for x in Things.objects.all()] class ThingSelector(forms.Form): thing = forms.ChoiceField(choices=thing_choices) If I first add a new Thing object, then go to the page...

Django 1.7 request.FILES 'None' not validated (is_valid())

python,django,file,validation,django-1.7
So I extended the User model to add some fields and am having troubles with the image (avatar) POST part. First there is a profile page that displays the user information, along with a link to edit the latter. Once on the 'editprofile' page, the form is loaded and prepopulated...

Django Internationalization gives fuzzy with capital letters

django,internationalization,django-1.7,po
I am setting up internationalization for a Django project (1.7). I am successfully generating .po files, however, I have entries such as: #: my_app/templates/my_app/profile.html:155 #, fuzzy #| msgid "Court" msgid "court" msgstr "" From what I understand , fuzzy will cause the translation not to happen. I would like the...

Is there an easy fix to use IsOwnerOrReadOnly with `user` instead of `owner` attribute?

django,django-rest-framework,django-1.7
I'm trying for the first time to build an api with Django REST framework. Now I want to use IsOwnerOrReadOnly, but all my models have user fields. Is there a way to tell the IsOwnerOrReadOnly permission to use user instead of owner?

How to create table during Django tests with managed = False?

python,django,django-testing,django-1.7,django-migrations
From the oficial documentation: For tests involving models with managed=False, it’s up to you to ensure the correct tables are created as part of the test setup. I don't know how to create the tables as part of the test setup. I found this question and the accepted answer doesn't...