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.
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!
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
I've gotten myself stuck on how to handle inheritance in my model when it comes to my controllers/views.
Basic Model:
public class Procedure : Entity
{
public Procedure() { }
public int Id { get; set; }
public DateTime ProcedureDate { get; set; }
public ProcedureType Type { get; set; }
}
public ProcedureA : Procedure
{
public double VariableA { get; set; }
public int VariableB { get; set; }
public int Total { get; set; }
}
public ProcedureB : Procedure
{
public int Score { get; set; }
}
etc... many of different procedures eventually.
So, I do things like list all the procedures:
public class ProcedureController : Controller
{
public virtual ActionResult List()
{
IEnumerable<Procedure> procedures = _repository.GetAll();
return View(procedures);
}
}
but now I'm kinda stuck. Basically, from the list page, I need to link to pages where the specific subclass details can be viewed/edited and I'm not sure what the best strategy is.
I thought I could add an action on the ProcedureController that would conjure up the right subclass by dynamically figuring out what repository to use and loading the subclass to pass to the view. I had to store the class in the ProcedureType object. I had to create/implement a non-generic IRepository since I can't dynamically cast to a generic one.
public virtual ActionResult Details(int procedureID)
{
Procedure procedure = _repository.GetById(procedureID, false);
string className = procedure.Type.Class;
Type type = Type.GetType(className, true);
Type repositoryType = typeof (IRepository<>).MakeGenericType(type);
var repository = (IRepository)DependencyRegistrar.Resolve(repositoryType);
Entity procedure = repository.GetById(procedureID, false);
return View(procedure);
}
I haven't even started sorting out how the view is going to determine which partial to load to display the subclass details.
I'm wondering if this is a good approach? This makes determining the URL easy. It makes reusing the Procedure display code easy.
Another approach is specific controllers for each subclass. It simplifies the controller code, but also means many simple controllers for the many procedure subclasses. Can work out the shared Procedure details with a partial view. How to get to construct the URL to get to the controller/action in the first place?
Time to not think about it. Hopefully someone can show me the light. Thanks in advance.
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...
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!
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)?
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.
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 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.
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.
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?
Hello,
I have a Model-Driven Struts2 action that provides correct JSON response. When I re-structure the action I get an empty JSON response back. Has anyone got inheritance working with Struts2 Model-Driven actions?
Ive tried explicitly setting include properties in struts config:
<result name="json" type="json">
<param name="includeProperties">
jsonResponse
</param>
</result>
Code for all actions below - not actual code in use - I have edited and stripped down for clarity.
Thanks in advance.
Action providing correct response:
public class Bike extends ActionSupport implements ModelDriven, Preparable {
@Autowired private Service bikeService;
private JsonResponse jsonResponse;
private com.ets.model.Vehicle bike;
private int id;
public Bike() {
jsonResponse = new JsonResponse("Bike");
}
@Override
public void prepare() throws Exception {
if (id == 0) {
bike = new com.ets.model.Bike();
} else {
bike = bikeService.find(id);
}
}
@Override
public Object getModel() {
return bike;
}
public void setId(int id) {
this.id = id;
}
public void setBikeService(@Qualifier("bikeService") Service bikeService) {
this.bikeService = bikeService;
}
public JsonResponse getJsonResponse() {
return jsonResponse;
}
public String delete() {
try {
bike.setDeleted(new Date(System.currentTimeMillis()));
bikeService.updateOrSave(bike);
jsonResponse.addActionedId(id);
jsonResponse.setAction("delete");
jsonResponse.setValid(true);
} catch (Exception exception) {
jsonResponse.setMessage(exception.toString());
}
return "json";
}
}
Re-structured Actions providing incorrect response:
public abstract class Vehicle extends ActionSupport implements ModelDriven {
@Autowired protected Service bikeService;
@Autowired protected Service carService;
protected JsonResponse jsonResponse;
protected com.ets.model.Vehicle vehicle;
protected int id;
protected abstract Service service();
@Override
public Object getModel() {
return bike;
}
public void setId(int id) {
this.id = id;
}
public void setBikeService(@Qualifier("bikeService") Service bikeService) {
this.bikeService = bikeService;
}
public void setCarService(@Qualifier("carService") Service carService) {
this.carService = carService;
}
public JsonResponse getJsonResponse() {
return jsonResponse;
}
public String delete() {
try {
vehicle.setDeleted(new Date(System.currentTimeMillis()));
service().updateOrSave(vehicle);
jsonResponse.addActionedId(id);
jsonResponse.setAction("delete");
jsonResponse.setValid(true);
} catch (Exception exception) {
jsonResponse.setMessage(exception.toString());
}
return "json";
}
}
public class Bike extends Vehicle implements Preparable {
public Bike() {
jsonResponse = new JsonResponse("Bike");
}
@Override
public void prepare() throws Exception {
if (id == 0) {
vehicle = new com.ets.model.Bike();
} else {
vehicle = bikeService.find(id);
}
}
@Override
protected Service service() {
return bikeService;
}
}
public class Car extends Vehicle implements Preparable {
public Car() {
jsonResponse = new JsonResponse("Car");
}
@Override
public void prepare() throws Exception {
if (id == 0) {
vehicle = new com.ets.model.Car();
} else {
vehicle = carService.find(id);
}
}
@Override
protected Service service() {
return carService;
}
}