Django community: Django Q&A RSS

This page, updated regularly, aggregates Django Q&A from the Django community.

How change caching setting in django_cache_utils0.7 to cache the files in different directory other than C drive?

Posted on April 24, 2014 at 11:49 AM by Stack Overflow RSS

I am using django-cache-utils 0.7 where I am not able to change the cache directory to a drive location other than the default location. Please can anyone tell me how to define custom location and set a size limit on the folder ?

Read this post in context »

Django Imagekit overwrite cachefile_name?

Posted on April 24, 2014 at 11:44 AM by Stack Overflow RSS

I'm trying to overwrite the cachefile_name property from the module django-imagekit. Here is my code: class Thumb150x150(ImageSpec): processors = [ResizeToFill(150, 150)] format = 'JPEG' options = {'quality': 90} @property def cachefile_name(self): # simplified for this example return "bla/blub/test.jpg" It doesn't work at all.When I debug (without my overwrite of cachefile_name), and look at the return value of cachefile_name, the result is a string like "CACHE/blablub/asdlkfjasd09fsaud0fj.jpg". Where is my mistake? Any ideas?

Read this post in context »

django template link to dynamic url

Posted on April 24, 2014 at 11:22 AM by Stack Overflow RSS

I try to make a list from a dictionary, where i also have the name of a view stored (values.1). so with every hit of the for loop i can link to the right page. Problem is, I cant figure out how i should fix the {{ url "view_name }} My template: <table> <tr> <th colspan="2">Timers</th> </tr> {% for key, values in timers.items %} <tr> <td>{{ key }}</td> <td><a href="{{ url values.1 }}">{{ values.0 }}</a></td> </tr> {% endfor %} </table> How can i chance the url so it directs to value.1 ?

Read this post in context »

django-allauth pass value to ACCOUNT_SIGNUP_FORM_CLASS

Posted on April 24, 2014 at 10:45 AM by Stack Overflow RSS

I have a django-allauth signup form that collects addition user profile information after a new user signs in through the Google provider. ACCOUNT_SIGNUP_FORM_CLASS = 'managers.signup.ManagerProfileSignupForm' SOCIALACCOUNT_AUTO_SIGNUP = False I would like to display the logo of the company this user belongs to on the signup form. The problem is that I am not given access to the "get_form_kwargs" function in the view since it's part of django-allauth. How might I pass this logo url to the form? class ManagerProfileSignupForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ManagerProfileSignupForm, self).__init__(*args, **kwargs) ... def signup(self, request, user): # save profile with form data ...

Read this post in context »

Django 1.6 adding custom fields to the User model

Posted on April 24, 2014 at 10:38 AM by Stack Overflow RSS

I've got the following profile/ class UserProfile(models.Model): user = models.OneToOneField(User) university = models.CharField(max_length=200, choices=UNIVERSITY, null=True) profile/ class UserForm(ModelForm): class Meta: model = UserProfile fields = ('username', 'first_name', 'last_name', 'email', 'university') I've run south and the database is up to date but I still get this error django.core.exceptions.FieldError: Unknown field(s) (first_name, username, email, last_name) specified for UserProfile I'm guessing it's something to do with the way the tables are linked. In my UserProfile table I have id, user_id, and university columns with appropriate data in them.

Read this post in context »

This product is used with everyday meal with water

Posted on April 24, 2014 at 10:36 AM by Django Forum RSS

Enough we cook whisking away like a healthy fat eat some are not I grind flaxseed heat on a little bit inky cutie during my yogurt on and it's a healthful back it's just not exactly Spain soil not quite as powerful but it's still a great choice earned question here clinics know we have his energy think it happened that that way and its I think stitches definitely a few pursued I E there’s been some concerns with you know the contamination equal and people getting tech on I'll AVI by pre-washed finish tonight have not got no I have my own but I D sometimes wonder friend off again but if you compare spinach to hey I for Gladys you are worlds apart for many Christian perspective on my client but now we know that I always make fun of my spirited away cue me but it's basically water and fiber not much nutrient he get spinach and Holly cow that dark green collar on it is has how much more nutrition even if you don't like shot well could you maybe 30 1/2 love it and here I Friday make allotter hack delivery powerful planned great suggestion ...

Read this post in context »

Translating SQL request to django

Posted on April 24, 2014 at 10:13 AM by Stack Overflow RSS

I am trying to create a request(in django) that will return an array of posts(only user's posts, which the current user in following). Here are my models Posts: class Post(models.Model): title = models.CharField("Headline", max_length=100) body = models.TextField(max_length=1000) user_id = models.ForeignKey(User) thumbnail = models.FileField(upload_to=get_upload_file_name, blank=True) timestamp = models.DateTimeField(auto_now_add=True) Following/followers: class FollowUser(models.Model): who_id = models.IntegerField() whom_id = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) Users: class UserProfile(models.Model): user = models.OneToOneField(User, unique=True) profile_pic = models.FileField(upload_to=get_upload_file_u_name, default='default.png', blank=True) bio = models.TextField(null=True) website = models.CharField(blank=True, max_length=100) location = models.CharField(blank=True, max_length=100) def __unicode__(self): return "%s's profile" % self.user SQL request that I've created: SELECT * FROM POSTS Where user_id IN (select whom_id from FOLLOWERS Where user_id = 1 ) So, I've tried to translate this sql code to django-like but I wasn't able. The main problem is that i can't request for an array. Need help! Thanks

Read this post in context »

rewriting unfilled field of the model in Django

Posted on April 24, 2014 at 10:08 AM by Stack Overflow RSS

I have a model of object Obj created in django with some fields (A,B,C) While creating some of the objects in data base people did not fill B field. Now I want to filter objects by B, like: for obj in all_Obj: if obj.B = "something": obj.delete() But I am getting this error: users.models.DoesNotExist: Profile matching query does not exist for the line: if c.main_name.user == user[0]: The same error I am getting when writing if not c.main_name.user: So how can I solve this? I can not rewrite this field because I can not address it and I can not filter by this field to delete some entries I don't need Thanks a lot for help.. :)

Read this post in context »

How to match single encoded and double encoded meta characters in django url dispatcher

Posted on April 24, 2014 at 9:38 AM by Stack Overflow RSS

I need to match encoded meta characters in django urls to avoid Open Redirect Vulnerability. e.g. can be matched as: url(r'.\\\\.', RedirectView.as_view(url='/login/', permanent=False),), How to match double encoded characters e.g. Or is there a better way to achieve this ?

Read this post in context »

Django base template files

Posted on April 24, 2014 at 9:36 AM by Stack Overflow RSS

I would like to ask a question about django base templates. How do they exactly work..What do I mean. I have a base file that lets say has a static conten and a block content that changes in templates that extend the base file. base.html <html> <head> <script src="main.js"></script> </head> <body> <div class="side-nav"> <!--static content here--> </div> <div class="content"> {% block "content"%} {%endblock%} </div> </body> </html> I have three templates that extend base.html, e.g t1.html, t2.html and t3.html. All of them have some dom elements that are edited by the main.js file importedn in base.html. My question is the following. Does it load all the page its time i render a template and thus main.js is run again or does it only render the "dynamic" content of the base file? Will the code of main.js run everytime I load a template that extends base.html?

Read this post in context »

Django ImportError: No module named

Posted on April 24, 2014 at 9:03 AM by Stack Overflow RSS

I did a custom command in django ( that calls the csvimport command from this package wihthin a for loop in order to import all my csv files in a folder. Here my code: for indicator_file in os.listdir(indicators_folder)[1:]: if indicator_file.endswith('.csv'): mappings = '1=indicator(IndicatorInfo|id), 2=public_administration(PublicAdministration|slug), 3=has_value, 4=absolute_cons' # OK model ='tdcp_core.PublicAdministrationIndicator' charset = 'latin-1' management.call_command('csvimport', abs_input_csv_path, charset=charset, mappings=mappings, model=model) print "---------> DONE IMPORTING FILE: " + indicator_file And here the error trace that returns after one good execution, or one good csvimport. Traceback (most recent call last): File "C:\Archivos de programa\JetBrains\PyCharm 3.1.1\helpers\pycharm\", line 23, in <module> run_module(manage_file, None, '__main__', True) File "C:\Python27\Lib\", line 176, in run_module fname, loader, pkg_name) File "C:\Python27\Lib\", line 82, in _run_module_code mod_name, mod_fname, mod_loader, pkg_name) File "C:\Python27\Lib\", line 72, in _run_code exec code in run_globals File "C:\Documents and Settings\MiguelFG\PycharmProjects\TdCP_Informes\", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Documents and Settings\MiguelFG\python_envs\tdcp_informes\lib\site-packages\django\core\management\", line 399, in execute_from_command_line utility.execute() File "C:\Documents and Settings\MiguelFG\python_envs\tdcp_informes\lib\site-packages\django\core\management\", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Documents and Settings\MiguelFG\python_envs\tdcp_informes\lib\site-packages\django\core\management\", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "C:\Documents and Settings\MiguelFG\python_envs\tdcp_informes\lib\site-packages\django\core\management\", line 285, in execute output = self.handle(*args, **options) File "C:/Documents and Settings/MiguelFG/PycharmProjects/TdCP_Informes\tdcp_core\management\commands\", line 493, in handle management.call_command('csvimport', abs_input_csv_path, charset=charset, mappings=mappings, model=model) File "C:\Documents and Settings\MiguelFG\python_envs\tdcp_informes\lib\site-packages\django\core\management\", line 145, in call_command klass = ...

Read this post in context »

Why is this Django form bypassing my custom manager when creating a new object?

Posted on April 24, 2014 at 8:36 AM by Stack Overflow RSS

I have a basic Django ModelForm to create a new user: class UserCreationForm(forms.ModelForm): class Meta: model = User # stuff here def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) if commit: return user I also have a custom UserManager for handling the User creation function, which also creates a UserProfile and attaches it to the User: class UserManager(BaseUserManager): def create_user(self, email, password=None): """Create a standard user.""" email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) profile = UserProfile() profile.user = user return user class User(AbstractBaseUser, PermissionsMixin): objects = UserManager() However, whenever the UserCreationForm is called successfully, it creates the User, but doesn't create the UserProfile. My question is, why is the UserCreationForm bypassing my custom UserManager? Is there some special syntax I need to give the form to tell it my model has a custom manager? I am also using django.views.generic.CreateView as the view, so I guess I could change the post method manually to create a User and UserProfile, but I'd like to know why this is failing before coming up with some hacky fix considering it seems like a very basic operation. Thanks

Read this post in context »

Exclude URLs from Django REST Swagger

Posted on April 24, 2014 at 8:28 AM by Stack Overflow RSS

I have a few URLs that I want to exclude from my REST API documentation. I'm using Django REST Swagger and the only documentation I can find ( doesn't really tell me much. There is the "exclude_namespaces" part of SWAGGER_SETTINGS in, but there is no real explanation or example of how to use this. Simply put, I want to exclude any URLs from the docs that start with the following: /api/jobs/status/ /api/jobs/parameters/ How could I go about doing this? Thanks in advance for any help offered :P

Read this post in context »

Sentry AJAX requests get 302 with Nginx and uWSGI

Posted on April 24, 2014 at 8:22 AM by Stack Overflow RSS

I have Sentry setup almost exactly like described here. My Sentry is available on, and everything working fine, except AJAX queries, for example by click on "resolve error" button. AJAX queries uses url without port, and they always get 302 status and they have no effect. Kindly help.

Read this post in context »

Django - Foreign Key not working

Posted on April 24, 2014 at 8:06 AM by Stack Overflow RSS

I'm trying to display some data on a webpage using a foreach loop and django. I do not seem to understand how to use a lookup table that I have created in my Database. These are the columns from the DB: budget_audit_table: -BudgetID -BudgetTypeID <- Foreign Key -ObjectAuditID -CustomerID -DateOfTransaction -BudgetObject -Amount budget_type: -BudgetTypeID -BudgetType As you can probably assume in the, the BudgetTypeID is a foreign key. In the budget_type table I currently have 2 rows: - Expense: ID 1 - Income: ID 2 Now the problem I'm having is I have searched for a few days now trying to understand Django's API more and I'm struggling to understand how do I for each row that is displayed from the budget_audit_table, how do I instead of displaying the BudgetTypeID (eg 1), it displays the BudgetType (eg Expense)? Here is my view & template from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.template import RequestContext, loader from models import BudgetAuditTable from models import BudgetType @login_required def index(request): budgetauditlist = BudgetAuditTable.objects.order_by('-budgetid') template = loader.get_template('budget/budget.html') context = RequestContext(request, { 'budgetauditlist': budgetauditlist, }) return HttpResponse(template.render(context)) Template {% for budgetauditobject in budgetauditlist %} <tr> <td>{{ budgetauditobject.budgetid }}</td> <td>{{ budgetauditobject.budgettypeid }}</td> <td>{{ ...

Read this post in context »

What are some small web app/project which we can develop by having small knowledge of django?

Posted on April 24, 2014 at 8:02 AM by Quora RSS

1 AnswerSee question on Quora

Read this post in context »

Form Wizard: Dynamic workflow

Posted on April 24, 2014 at 7:45 AM by Stack Overflow RSS

I'm using django's built-in Form wizard SessionWizardView to split a form across several pages. When calling the Form wizard, users are being displayed an Select input field which expects an option A or B to be chosen. This choice affects the next steps to be displayed. This means that I basically have two totally different form lists - which of these gets processed by the Form wizard depends on the choice in the first step, e.g: Step 1: Choice A -> use form list A or Step 1: Choice B -> use form list B What is an elegant , django-friendly way to achieve this dynamic workflow?

Read this post in context »

Django coin/points system ideas

Posted on April 24, 2014 at 7:44 AM by Stack Overflow RSS

I am creating a Web Based game in django, in which almost all action require some coins/points , So for every action i need to check if userprofile has specific coins for action or not. I have seen Awards/Rewards packages but it seems like they are awarding/rewarding after some action has been performed. I need a generic solution that checks if user has certain coins for an action or not. for coins i am doing it like this way: class UserProfile(models.Model): .... def deduct_coins(coins): self.coin -= coins def has_coins(coins): if self.coins >= coins: return true return false I am not using django forms for all my actions so before each action ( CRUD ) operations i am doing following steps: Check if user has required coins Perform the action Deduct the coins required 1- How can i make this process generic. 2- Are there any custom signals other than builtin signals, if so how can i use them. 3- Can pre_save signal be used for this scenario.

Read this post in context »

cross domain upload with uploadify

Posted on April 24, 2014 at 7:40 AM by Stack Overflow RSS

I am trying to upload the video file to youtube through uploadify, but getting security error, does uploadify support third party upload? or do i need to do any configuration for that ? any input will help. thanks

Read this post in context »

Unicodedecodeerror with runserver and django

Posted on April 24, 2014 at 7:39 AM by Stack Overflow RSS

After setup all that django requires, and try python runserver command, I caught error. How to fix it? Or at least how take a look on what caused error? Windows 7 python runserver Validating models... 0 errors found April 24, 2014 - 11:13:33 Django version 1.6.3, using settings 'mysite.settings' Starting development server at Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function wrapper at 0x02C46CB0> Traceback (most recent call last): File "C:\Users\Aleksander\.virtualenvs\engineer\lib\site-packages\django\utils\", li fn(*args, **kwargs) File "C:\Users\Aleksander\.virtualenvs\engineer\lib\site-packages\django\core\management\commands 139, in inner_run self.stderr.write("Error: %s" % error_text) UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 14: ordinal not in range(128)

Read this post in context »

django recursively call a thread in web service module

Posted on April 24, 2014 at 7:37 AM by Stack Overflow RSS

I have some global variables in my django web service module and I would like to do some operations on them periodically. In order to do this I am calling an internal function which creates thread recursively, and this function is not a restful api. def thread_test(): print "I am in thread now.." time.sleep(1) threading.Timer(0,thread_test).start() Is it convenient to call such function in django api module? Does it have any drawbacks like performance issues?

Read this post in context »

mezzanine upgrade migration error

Posted on April 24, 2014 at 7:33 AM by Stack Overflow RSS

I'm trying to upgrade a django-1.3 install to 1.6 with mezzanine. But the problem arises when i try to run the migration. It gives me an error and stops the migration Running migrations for generic: - Migrating forwards to 0014_auto__add_field_rating_user. > generic:0008_set_keyword_order - Migration 'generic:0008_set_keyword_order' is marked for no-dry-run. ! Error found during real run of migration! Aborting. ! Since you have a database that does not support running ! schema-altering statements in transactions, we have had ! to leave it in an interim state between migrations. ! You *might* be able to recover with: (migration cannot be dry-run; cannot discover commands) ! The South developers regret this has happened, and would ! like to gently persuade you to consider a slightly ! easier-to-deal-with DBMS (one that supports DDL transactions) ! NOTE: The error which caused the migration to fail is further up. Error in migration: generic:0008_set_keyword_order

Read this post in context »

django-allauth adapter redirects

Posted on April 24, 2014 at 7:09 AM by Stack Overflow RSS

I am leveraging django-allauth to provide Google authentication for my property management application. Here is the registration workflow I'm looking for: A new manager goes to a registration page with a "Signup With Google" button. They click the button and sign into Google. On the call back from Google they are presented with a form for additional info. When they submit this form their user account and manager profile is created and they are redirected to their company's homepage. I have attempted to handle this "redirect to company's homepage" through adapters. The problem I am having is that the "get_login_redirect_url" function is executed after the initial Google sign-in, but before the signup form where I collect their work schedule, so I get a DoesNotExist on the adapter redirect because it was called before the managerprofile was created. What is the proper way to do these redirects? ACCOUNT_SIGNUP_FORM_CLASS = 'managers.signup.ManagerProfileSignupForm' SOCIALACCOUNT_AUTO_SIGNUP = False SOCIALACCOUNT_ADAPTER = 'managers.adapter.ManagerSocialAccountAdapter' ACCOUNT_ADAPTER = 'managers.adapter.ManagerAccountAdapter' class ManagerSocialAccountAdapter(DefaultSocialAccountAdapter): def get_connect_redirect_url(self, request, socialaccount): return reverse('company_details', args=(,)) class ManagerAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): return reverse('company_details', args=(,))

Read this post in context »

remove time from django DateTime in Django

Posted on April 24, 2014 at 7:01 AM by Stack Overflow RSS

So i need to remove from date Time, so i only get date, year and month. "2014-04-17T00:00:00" I looked at different opportunities but it didn't work class Inventory(models.Model): manufacturer = models.CharField(max_length=255) model = models.CharField(max_length=255) description = models.TextField(max_length=255) count = models.IntegerField(max_length= 255, default=1) location = models.ForeignKey('Location', null=True, blank=True) cover = models.FileField(upload_to = 'static/images/', default = 'static/images/no-image.png') created = models.DateTimeField(auto_now_add=True) barcode = models.CharField(max_length=255) assigned = models.ForeignKey(User, blank=True, null=True) checked = models.BooleanField(default=False) modified = models.DateTimeField( tags = TaggableManager(through=None, blank=True) def __unicode__(self): return '%s' % date(self.modified, "n/j/Y") def format_date(obj): return obj.modified.strftime('%d %b %Y %H:%M') format_date.short_description = 'Modified'

Read this post in context »

Unable to send date using Tastypie

Posted on April 24, 2014 at 6:22 AM by Stack Overflow RSS

in my i have field birth_date = models.DateField(_('birth date'), blank=True, null=True) using curl .I am sending date format to tasty pie as "birth_date":'2009-08-10' i am getting bad url 400 error . without birth date . it is accepting data. if add date in this format showing that error? any guess why

Read this post in context »