I understand I am able to filter queryset of Foreignkey or Many2ManyFields, however, how do I do that for a simple CharField that is a Select Widget (Select Tag).
For example:
PRODUCT_STATUS = (
("unapproved", "Unapproved"),
("approved", "Listed"),
#("Backorder","Backorder"),
#("oos","Out of Stock"),
#("preorder","Preorder"),
("userdisabled", "User Disabled"),
("disapproved", "Disapproved by admin"),
)
and the Field:
o_status = models.CharField(max_length=100, choices=PRODUCT_STATUS, verbose_name="Product Status", default="approved")
Suppose I wish to limit it to just "approved" and "userdisabled" instead showing the full array (which is what I want to show in the admin), how do I do it?
Thanks!
Hi,
How can I fix number of concurrent sessions allowed at app level?
Basically I want a limit to how many concurrent requests to this url to keep the server from getting congested.
I guess some middleware hack?
Thanks.
my form is
class MapForm(forms.ModelForm):
class Meta:
model = Map
fields = ('mapName', 'kmlStr')
and the view is :
map_form = MapForm(request.POST or None)
if map_form.is_valid():
map = map_form.save(commit=False)
map.mapName=map_form.mapName#is thie code right ?
how to get the mapName 's value , us 'map_form.mapName' ?
thanks
Suppose this is my URL route:
(r'^test/?$','hello.life.views.test'),
How do I make it so that people can do .json, .xml, and it would pass a variable to my views.test, so that I know to make json or xml?
Hi,
I have an application to count the number of access to an object for each website in a same database.
class SimpleHit(models.Model):
"""
Hit is the hit counter of a given object
"""
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
site = models.ForeignKey(Site)
hits_total = models.PositiveIntegerField(default=0, blank=True)
[...]
class SimpleHitManager(models.Manager):
def get_query_set(self):
print self.model._meta.fields
qset = super(SimpleHitManager, self).get_query_set()
qset = qset.filter(hits__site=settings.SITE_ID)
return qset
class SimpleHitBase(models.Model):
hits = generic.GenericRelation(SimpleHit)
objects = SimpleHitManager()
_hits = None
def _db_get_hits(self, only=None):
if self._hits == None:
try:
self._hits = self.hits.get(site=settings.SITE_ID)
except SimpleHit.DoesNotExist:
self._hits = SimpleHit()
return self._hits
@property
def hits_total(self):
return self._db_get_hits().hits_total
[...]
class Meta:
abstract = True
And I have a model like:
class Model(SimpleHitBase):
name = models.CharField(max_length=255)
url = models.CharField(max_length=255)
rss = models.CharField(max_length=255)
creation = AutoNowAddDateTimeField()
update = AutoNowDateTimeField()
So, my problem is this one: when I call Model.objects.all(), I would like to have one request for the SQL (not two). In this case: one for Model in order to have information and one for the hits in order to have the counter (hits_total). This is because I cannot call directly hits.hits_total (due to SITE_ID?). I have tried select_related, but it seems to do not work...
Question:
- How can I add column automatically like (SELECT hits.hits_total, model.* FROM [...]) to the queryset?
- Or use a functional select_related with my models?
I want this model could be plugable on all other existing model.
Thank you,
Best regards.
MYMESSAGE = "<div>Hello</div><p></p>Hello"
send_mail("testing",MYMESSAGE,"[email protected]",['[email protected]'],fail_silently=False)
However, this message doesn't get the HTML mime type when it is sent. In my outlook, I see the code...
Suppose I have my models set up already.
class books(models.Model):
title = models.CharField...
ISBN = models.Integer...
What if I want to add this column to my table?
user = models.ForeignKey(User, unique=True)
How would I write the raw SQL in my database so that this column works?
For formatting a date using date filter you must use the following format :
{{ my_date|date:"Y-m-d" }}
If you use strftime from the standard datetime, you have to use the following :
my_date.strftime("%Y-%m-%d")
So my question is ... isn't it ugly (I guess it is because of the % that is used also for tags, and therefore is escaped or something) ?
But that's not the main question ... I would like to use the same DATE_FORMAT parametrized in settings.py all over the project, but it therefore seems that I cannot ! Is there a work around (for example a filter that removes the % after the date has been formatted like {{ my_date|date|dream_filter }}, because if I just use DATE_FORMAT = "%Y-%m-%d" I got something like %2001-%6-%12)?
I am trying to set up Google App Engine unit testing for my web application. I downloaded the file from here.
I followed the instructions in the readmen by copying the directory gaeunit into the directory with the rest of my apps and registering 'gaeunit' in settings.py. This didn't seem sufficient to actually get things going. I also stuck url('^test(.*)', include('gaeunit.urls')) into my urls.py file.
When I go to the url http://localhost:8000/test, I get the following error:
[Errno 2] No such file or directory: '../../gaeunit/test'
Any suggestions? I'm not sure what I've done wrong. Thanks!
I have this error:
'people' is an invalid keyword argument for this function
class Passage(models.Model):
name= models.CharField(max_length = 255)
who = models.ForeignKey(UserProfil)
class UserPassage(models.Model):
passage = models.ForeignKey(Passage)
people = models.ManyToManyField(UserProfil, null=True)
class UserProfil(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=50)
I try:
def join(request):
user = request.user
user_profil = UserProfil.objects.get(user=user)
passage = Passage.objects.get(id=2)
#line with error
up = UserPassage.objects.create(people= user_profil, passage=passage)
return render_to_response('thanks.html')
How to do correctly?
Thanks!
I'd like everything to function correctly, except when it's mobile, the entire site will used a set of specific templates.
Also, I'd like to autodetect if it's mobile. If so, then use that set of templates throughout the entire site.
I have a handful of users on a server. After updating the site, they don't see the new pages. Is there a way to globally force their browsers and providers to display the new page? Maybe from settings.py? I see there are decorators that look like they do this on a function level.
I am trying to get a list of all existing model fields and properties for a given object. Is there a clean way to instrospect an object so that I can get a dict of fields and properties.
class MyModel(Model)
url = models.TextField()
def _get_location(self):
return "%s/jobs/%d"%(url, self.id)
location = property(_get_location)
What I want is something that returns a dict that looks like this:
{
'id' : 1,
'url':'http://foo',
'location' : 'http://foo/jobs/1'
}
I can use model._meta.fields to get the model fields, but this doesn't give me things that are properties but not real DB fields.
Sometimes the best way to debug something is to print some stuff to the page, and exit(), how can I do this in a Python/Django site?
e.g. in PHP:
echo $var;
exit();
Thanks
As far as I understand, the "Getting Started" guide of GAE with Python uses the webapp framework. However, it seems like it uses Django to render templates.
Does that mean that I can use the Django template engine without using its application framework?
There are a ton of questions like this, but they are mostly very generalized, so I'd like to get some views on my specific usage.
General:
I'm building a new project on my own in Django. It's focus will be on small businesses. I'd like to make it somewhat customizble for my clients so they can add to their customer/invoice/employee/whatever items. My models would reflect boilerplate items that all ModelX might have. For example:
first name
last name
email
address
...
Then my user's would be able to add fields for whatever data they might like. I'm still in design phase and am building this myself, so I've got some options.
Working on...
Right now the 'extra items' models have a FK to the generic model (Customer and CustomerDataPoints for example). All values in the extra data points are stored as char and will be coerced/parced into their actual format at view building. In this build the user could theoretically add whatever values they want, group them in sets and generally access them at will from the views relavent to that model.
Pros: Low storage overhead, very extensible, searchable
Cons: More sql joins
My other option is to use some type of markup, or key-value pairing stored directly onto the boilerplate models. This coul essentially just be any low-overhead method weather XML or literal strings. The view and form generated from the stored data would be taking control of validation and reoganizing on updates. Then it would just dump the data back in as a char/blob/whatever.
Something like:
<datapoint type='char' value='something' required='true' />
<datapoint type='date' value='01/01/2001' required='false' />
...
Pros: No joins needed, Updates for validation and views are decoupled from data
Cons: Much higher storage overhead, limited capacity to search on extra content
So my question is:
If you didn't live in the contraints impose by your company what method would you use? Why? What benefits or pitfalls do you see down the road for me as a small business trying to help other small businesses?
Just to clarify, I am not asking about custom UI elements, those I can handle with forms and template snippets. I'm asking primarily about data storage and retreival of non standardized data relative to a boilerplate model.
I have some odd self modifying code, but at the root of it is a pretty simple problem: I want to be able to execute a jmp (or a call) and then from that arbitrary point throw an exception and have it caught by the try/catch block that contained the jmp/call.
But when I do this (in gcc 4.4.1 x86_64) the exception results in a terminate() as it would if the exception was thrown from outside of a try/catch. I don't really see how this is different than throwing an exception from inside of some far-flung library, yet it obviously is because it just doesn't work.
How can I execute a jmp or call but still throw an exception back to the original try/catch? Why doesn't this try/catch continue to handle these exceptions as it would if the function was called normally?
The code:
#include <iostream>
#include <stdexcept>
using namespace std;
void thrower()
{
cout << "Inside thrower" << endl;
throw runtime_error("some exception");
}
int main()
{
cout << "Top of main" << endl;
try {
asm volatile (
"jmp *%0" // same thing happens with a call instead of a jmp
:
: "r"((long)thrower)
:
);
} catch (exception &e) {
cout << "Caught : " << e.what() << endl;
}
cout << "Bottom of main" << endl << endl;
}
The expected output:
Top of main
Inside thrower
Caught : some exception
Bottom of main
The actual output:
Top of main
Inside thrower
terminate called after throwing an instance of 'std::runtime_error'
what(): some exception
Aborted
I have derived a class from Exception, basically like so:
class MyException extends Exception {
private $_type;
public function type() {
return $this->_type; //line 74
}
public function __toString() {
include "sometemplate.php";
return "";
}
}
Then, I derived from MyException like so:
class SpecialException extends MyException {
private $_type = "superspecial";
}
If I throw new SpecialException("bla") from a function, catch it, and go echo $e, then the __toString function should load a template, display that, and then not actually return anything to echo.
This is basically what's in the template file
<div class="<?php echo $this->type(); ?>class">
<p> <?php echo $this->message; ?> </p>
</div>
in my mind, this should definitely work. However, I get the following error when an exception is thrown and I try to display it:
Fatal error: Cannot access private property SpecialException::$_type in C:\path\to\exceptions.php on line 74
Can anyone explain why I am breaking the rules here? Am I doing something horribly witty with this code? Is there a much more idiomatic way to handle this situation? The point of the $_type variable is (as shown) that I want a different div class to be used depending on the type of exception caught.