I'm using django.contrib.auth.views.login to log in users. When login is failed, the user and password fields get posted back to the form.
What's the proper way to clean those?
I have this model:
class blog(models.Model):
user = models.ForeignKey(User)
mail = models.EmailField(max_length=60, null=False, blank=False)
name = models.CharField(max_length=60, blank=True, null=True)
I want that (user,email) are unique togheter. For example:
This is allowed:
1, [email protected], myblog
2, [email protected], secondblog
This is NOT allowed:
1, [email protected], myblog
1, [email protected], secondblog
Is this possible in Django ?
Hi all,
I have a similar problem as a previously solved problem of mine, except this time solution doesn't seem to work:
http://stackoverflow.com/questions/2991365/how-to-auto-insert-the-current-user-when-creating-an-object-in-django-admin
Previously i used to override the save_model to stamp the user submitting the article. Now i need to do the same for comments, it doesn't seem to work anymore.
Anyone have any ideas?
Thanks a lot!
Jason
I'm new to Django and setting up my first site. I have a Share model and a template called share_list.html that uses an object_list like this:
{% for object in object_list %}
I setup haystack using their tutorial and the search template looks like this:
{% for result in page.object_list %}
I would like to modify the search.html template to have an include of the share_list so I don't have to repeat myself. How can I make it use the same object_list?
I use solr+django-haystack
I set settings.HAYSTACK_INCLUDE_SPELLING = True
and rebuild index
I'm trying to get any suggestion using:
SearchQuerySet().auto_query('tryng ani word
her').spelling_suggestion()
But I always get None
What should I do to get at least one working suggestion ? may be I
need add some configuration into solr config or have some specific
data indexed ?
I need a regular expression to validate string with one or more of these characters:
a-z
A-Z
'
àòèéùì
simple white space
FOR EXAMPLE these string are valide:
D' argon calabrò
maryòn l' Ancol
these string are NOT valide:
hello38239
my_house
work [tab] with me
I tryed this:
re.match(r"^[a-zA-Z 'òàèéìù]+$", self.cleaned_data['title'].strip())
It seems to work in my python shell but in Django I get this error:
SyntaxError at /home/
("Non-ASCII character '\\xc3' ...
Why ?
Hi,
in my Django (1.2) project, I want to prepopulate a field in a modelform, but my new value is ignored.
This is the snippet:
class ArtefactForm(ModelForm):
material = CharField(widget=AutoCompleteWidget('material', force_selection=False))
def __init__(self, *args, **kwargs):
super(ArtefactForm, self).__init__(*args, **kwargs)
self.fields['material'].initial = 'Test'
I also tried with self.base_fields, but no effect: there is always the database-value displaying in the form. Any ideas?
hi using Django to create a stock photo site, i have a ImageField in my model, the problem is that when the user update the image field, the original image file isn't deleted from the hard disk.
how can I make to delete those images after an update?
Thanks!
I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although I have pretty good experience with python and PHP but I have no idea how to use either of the framework. We have plenty of time to experiment and learn one of the above frameworks.Could you please specify which one would be preferred for such a scenario considering speed, features, and security of the site.
Thanks,
niting
I have an object:
POP_CULTURE_TYPES = (
('SG','Song'),
('MV', 'Movie'),
('GM', 'Game'),
('TV', 'TV'),
)
class Pop_Culture(models.Model):
name = models.CharField(max_length=30, unique=True)
type = models.CharField(max_length=2, choices = POP_CULTURE_TYPES, blank=True, null=True)
Then I have a function:
def choice_list(request, modelname, field_name):
mdlnm = get.model('mdb', modelname.lower())
mdlnm = mdlnm.objects.values_list(field_name, flat=True).distinct().order_by(field_name)
return render_to_response("choice_list.html", {
'model' : modelname,
'field' : field_name,
'field_list' : mdlnm })
This gives me a distinct list of all the "type" entries in the database in the "field_list" variable passed in render_to_response. But I don't want a list that shows:
SG
MV
I want a list that shows:
Song
Movie
I can do this on an individual object basis if I was in the template
object.get_type_display
But how do I get a list of all of the unique "type" entries in the database as their full names for output into a template?
I hope this question was clearly described. . .
Given a reference app ( called guide), how can I create additional apps that will reuse the same model/admin/views than guide - the motivation behind is to be able to individually control each subapp.
guide
guideApp1
exact same models/admin/views than guide
guideApp2
exact same models/admin/views than guide
in the Admin site, I should have :
1 section for guideApp1 with all the tables defined in guide, that applies to guideApp1
1 section for guideApp12 with all the tables defined in guide, that applies to guideApp2
I'm trying to validate a form containing a ModelChoiceField:
state = forms.ModelChoiceField(queryset=State.objects.all(), empty_label=None)
When it is used in normal circumstances, everything goes just fine. But I'd like to protect the form from the invalid input. It's pretty obvious that I must get forms.ValidationError when I put invalid value in this field, isn't it? But if I try to submit a form with a value 'invalid' in 'state' field, I get
ValueError: invalid literal for int() with base 10: 'invalid'
and not the expected forms.ValidationError. What should I do? I tried to place a def clean_state(self) to check this field but that didn't work plus I don't think this is a good solution, there must be something more simple but I just missed that.
I want to use unique hashes for each model rather than ids.
I implemented the following function to use it across the board easily.
import random,hashlib
from base64 import urlsafe_b64encode
def set_unique_random_value(model_object,field_name='hash_uuid',length=5,use_sha=True,urlencode=False):
while 1:
uuid_number = str(random.random())[2:]
uuid = hashlib.sha256(uuid_number).hexdigest() if use_sha else uuid_number
uuid = uuid[:length]
if urlencode:
uuid = urlsafe_b64encode(uuid)[:-1]
hash_id_dict = {field_name:uuid}
try:
model_object.__class__.objects.get(**hash_id_dict)
except model_object.__class__.DoesNotExist:
setattr(model_object,field_name,uuid)
return
I'm seeking feedback, how else could I do it? How can I improve it? What is good bad and ugly about it?
I pass the query with comments to my template:
COMM = CommentModel.gql("ORDER BY created")
doRender(self,CP.template,{'CP':CP,'COMM':COMM, 'authorize':authorize()})
And I want to output the number of comments as a result, and I try to do things like that:
<a href="...">{{ COMM|length }} comments</a>
Thats does not work (yeah, since COMM is GqlQuery, not a list). What can I do with that? Is there a way to convert GqlQuery to list or is there another solution? (first question)
Second question is, how to filter this list in template? Is there a construct like this:
<a href="...">{{ COMM|where(reference=smth)|length }} comments</a>
so that I can get not only the number of all comments, but only comments with certain db.ReferenceProperty() property, for example.
Last question: is it weird to do such things using templates?
Lets say we want a library of javascript-based pieces of functionality (I'm thinking jquery):
For example:
an ajax dialog
a date picker
a form validator
a sliding menu bar
an accordian thingy
There are four pieces of code for each: some Python, CSS, JS, & HTML.
What is the best way to arrange all these pieces so that:
each javascript 'module' can be neatly reused by different views
the four bits of code that make up the completed function stay together
the css/js/html parts appear in their correct places in the response
common dependencies between modules are not repeated (eg: a javascript file in common)
x--------------
It would be nice if, or is there some way to ensure that, when called from a templatetag, the templates respected the {% block %} directives. Thus one could create a single template with a block each for CSS, HTML, and JS, in a single file. Invoke that via a templatetag which is called from the template of whichever view wants it. That make any sense. Can that be done some way already? My templatetag templates seem to ignore the {% block %} directives.
x--------------
There's some very relevant gasbagging about putting such media in forms here http://docs.djangoproject.com/en/dev/topics/forms/media/ which probably apply to the form validator and date picker examples.
I'm trying to install MySQLdb for python.
but when I run the setup, this is the error I get.
well I know why its giving all the missing file statements, but dont know where to change the bold marked location from.
Please help
gaurav-toshniwals-macbook-7:MySQL-python-1.2.3c1 gauravtoshniwal$ python setup.py build
running build
running build_py
copying MySQLdb/release.py - build/lib.macosx-10.3-fat-2.6/MySQLdb
running build_ext
building '_mysql' extension
gcc-4.0 -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -O3 -Dversion_info=(1,2,3,'gamma',1) -D_version_=1.2.3c1 -I/Applications/MAMP/Library/include/mysql -I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c _mysql.c -o build/temp.macosx-10.3-fat-2.6/_mysql.o
_mysql.c:36:23: error: my_config.h: No such file or directory
_mysql.c:36:23: error: my_config.h: No such file or directory
_mysql.c:38:19: error: mysql.h: No such file or directory
_mysql.c:38:19:_mysql.c:39:26: error: mysqld_error.h: No such file or directory
error: _mysql.c:40:20:mysql.h: No such file or directory
Hey guys/gals!
I had a question for you, something that I can't seem to find the solution for... Basically, I have a model called Environment, and I am passing all of them to a view, and there are particular environments that I would like to exclude. Now, I know there is a exclude function on a queryset, but I can't seem to figure out how to use it for multiple options... For example, I tried this but it didn't work:
kwargs = {"name": "env1", "name": "env2"}
envs = Environment.objects.exclude( kwards )
But the only thing that it will exclude is the last "name" value in the list of kwargs. I understand why it does that now, but I still can't seem to exclude multiple objects with one command. Any help is much appreciated!
Shawn
Originally started here: http://stackoverflow.com/questions/2650181/django-in-query-as-a-string-result-invalid-literal-for-int-with-base-10
I have a number of apps within my site, currently working with a simple "Blog" app. I have developed a 'Favorite' app, easily enough, that leverages the ContentType framework in Django to allow me to have a 'favorite' of any type... trying to go the other way, however, I don't know what I'm doing, and can't find any examples for.
I'll start off with the favorite model:
favorite/models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
class Favorite(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
user = models.ForeignKey(User)
content_object = generic.GenericForeignKey()
class Admin:
list_display = ('key', 'id', 'user')
class Meta:
unique_together = ("content_type", "object_id", "user")
Now, that allows me to loop through the favorites (on a user's "favorites" page, for example) and get the associated blog objects via {{ favorite.content_object.title }}.
What I want now, and can't figure out, is what I need to do to the blog model to allow me to have some tether to the favorite (so when it is displayed in a list it can be highlighted, for example).
Here is the blog model:
blog/models.py
from django.db import models
from django.db.models import permalink
from django.template.defaultfilters import slugify
from category.models import Category
from section.models import Section
from favorite.models import Favorite
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Blog(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=140, editable=False)
author = models.ForeignKey(User)
homepage = models.URLField()
feed = models.URLField()
description = models.TextField()
page_views = models.IntegerField(null=True, blank=True, default=0 )
created_on = models.DateTimeField(auto_now_add = True)
updated_on = models.DateTimeField(auto_now = True)
def __unicode__(self):
return self.title
@models.permalink
def get_absolute_url(self):
return ('blog.views.show', [str(self.slug)])
def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(self.title)
duplicate_count = Blog.objects.filter(slug__startswith = slug).count()
if duplicate_count:
slug = slug + str(duplicate_count)
self.slug = slug
super(Blog, self).save(*args, **kwargs)
class Entry(models.Model):
blog = models.ForeignKey('Blog')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=140, editable=False)
description = models.TextField()
url = models.URLField(unique=True)
image = models.URLField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
slug = slugify(self.title)
duplicate_count = Entry.objects.filter(slug__startswith = slug).count()
if duplicate_count:
slug = slug + str(duplicate_count)
self.slug = slug
super(Entry, self).save(*args, **kwargs)
class Meta:
verbose_name = "Entry"
verbose_name_plural = "Entries"
Any guidance?
I'm trying to find a way to cache the results of a query that won't change with frequency. For example, categories of products from an e-commerce (cellphones, TV, etc).
I'm thinking of using the template fragment caching, but in this fragment, I will iterate over a list of these categories. This list is avaliable in any part of the site, so it's in my base.html file. Do I have always to send the list of categories when rendering the templates? Or is there a more dynamic way to do this, making the list always available in the template?
Hey
I have a model where :
LIST_OPTIONS = (
('cheap','cheap'),
('expensive','expensive'),
('normal', 'normal'),
)
then I have assigned the LIST_OPTIONS to nature variable.
nature = models.CharField(max_length=15, choices=LIST_OPTIONS, null=False, blank=False).
then I save it:
if self.pk:
new=False
else:
new=True
super(Listing, self).save(force_insert, force_update)
if new and notification:
notification.send(User.objects.all().exclude(id=self.owner.id),
"listing_new",
{'listing':self, },
)
then in my management.py:
def create_notice_types(app, created_models,verbosity, **kwargs):
notification.create_notice_type("listing_new", _("New Listing"),
_("someone has posted a new listing"), default=2)
and now in my notice.html I want to show to users different sentences based on the options that they have choose so something like this:
LINK href="{{ listing.owner.get_absolute_url }} {{listing.owner}}
{% ifequal listing.nature "For Sale" %}
created a {{ listing.nature }} listing, <a href="{{ listing.get_absolute_url }}">{{listing.title}}</a>.
{% ifequals listing.equal "Give Away"%}
is {{ listing.nature }} , LINK href="{{ listing.get_absolute_url }}" {{listing.title}}.
{% ifequal listing.equal "Looking For"%}
is {{ listing.nature }} , LINK href="{{ listing.get_absolute_url }}" {{listing.title}}
{% endifequal %}
{% endifequal %}
{% endifequal %}
Could you please help me out with this. Thank you
I'm sure this is really simple, but I can't for the life of me find any documentation explaining how to do this.
How do I get the results of a ManyToMany field inside a join as opposed to doing this:
{% for tag in article.tags.all %}
Which results in an extra query? What I'd like to do is fetch all related tags when I retrieve the initial article, so I could then do something like:
{% for tag in article.tags %}
Without the .all and the extra query.
Thanks!
I tried something like:
MyModel.objects.filter(year__week=1)
It doesn't work. For now, I calculate the first day and the last day of the week and then use gte and lte, but it's less than efficient given that SQL comes with a Week function.
Hay I've got a question about relationships.
I want to Users to have Friendships. So a User can be a friend with another User. I'm assuming i'll need to use the ManyToManyField, through a Friendship table. But i cannot get it to work. Any ideas?
Here are my models.
class User(models.Model):
username = models.CharField(max_length=999)
password = models.CharField(max_length=999)
created_on = models.DateField(auto_now = False, auto_now_add = True)
updated_on = models.DateField(auto_now = True, auto_now_add = False)
friends = models.ManyToManyField('User', through='Friendship')
class Friendship(models.Model):
user = models.ForeignKey('User')
friend = models.ForeignKey('User')
Thanks
Hi,
Can someone tell me if a form in an inlineformset should go through validation if the DELETE field is checked. I have a form that uses an inlineformset and when I check the DELETE box it fails because the required fields are blank. If I put data in the fields it will pass validation and then be deleted.
Is that how it is supposed to work, I would have thought that if it is marked for delete it would bypass the validation for that form.
Regards
Andrew
Follow up - but I would still appreciate some others opinions/help
What I have figured out is that for validation to work the a formset form must either be empty or complete(valid) otherwise it will have errors when it is created and will not be deleted. As I have a couple of hidden fields in my formset forms and they are pre-populated when the page loads via javascript the form fails validation on the other required fields which might still be blank.
The way I have gotten around this by adding in a check in the add_fields that tests if the DELETE input is True and if it is it makes all fields on the form not required, which means it passes validation and will then delete.
def add_fields(self, form, index)
#add other fields that are required....
deleteValue = form.fields['DELETE'].widget.value_from datadict(form.data, form.files, form.add_prefix('DELETE'))
if bool(deleteValue) or deleteValue == '':
for name, field in form.fields.items():
form.fields[name].required= False
This seems to be an odd way to do things but I cannot figure out another way. Is there a simpler way that I am missing?
I have also noticed that when I add the new form to my page and check the Delete box, there is no value passed back via the request, however an existing form (one loaded from the database) has a value of on when the Delete box is checked. If the box is not checked then the input is not in the request at all.
Thanks
Andrew