Hello,
How can I find an image, depending on the text?
I have image model with keywords:
class Post(models.Model):
image = ImageField(_('Image'), blank=True, upload_to='folder')
keywords = models.CharField(_('Keywords'), max_length=80)
And model which will serve as the search for a suitable image
class TextSearch(models.Model):
body = models.TextField(_('Text'))
Concept:
Drinks are made of components. E.g. 10ml of Vodka. In some receipt the component is very particular (10ml of Finlandia Vodka), some not (10 ml of ANY Vodka).
I wonder how to model a component to solve this problem - on stock I have particular product, which can satisfy more requirements.
The model for now is:
class Receipt(models.Model):
name = models.CharField(max_length=128)
(...)
components = models.ManyToManyField(Product, through='ReceiptComponent')
def __unicode__(self):
return self.name
class ReceiptComponent(models.Model):
product = models.ForeignKey(Product)
receipt = models.ForeignKey(Receipt)
quantity = models.FloatField(max_length=9)
unit = models.ForeignKey(Unit)
class Admin:
pass
def __unicode__(self):
return unicode(self.quantity!=0 and self.quantity or '') + ' ' + unicode(self.unit) + ' ' + self.product.genitive
class Product(models.Model):
name = models.CharField(max_length = 128)
(...)
class Admin:
pass
def __unicode__(self):
return self.name
class Stock(Store):
products = models.ManyToManyField(Product)
class Admin:
pass
def __unicode__(self):
return self.name
I think about making some table which joins real product (on stock) with abstract product (receiptcomponent). But maybe there's easy solution?
Hi,
I want to check if a user has any new messages each time they load the page. Up until now, I have been doing this inside of my views but it's getting fairly hard to maintain since I have a fair number of views now.
I assume this is the kind of thing middleware is good for, a check that will happen every single page load. What I need it to do is so:
Check if the user is logged in
If they are, check if they have any messages
Store the result so I can reference the information in my templates
Has anyone ever had to write any middleware like this? I've never used middleware before so any help would be greatly appreciated.
I want to let users use their google account to login to my website. Exactly the way SO lets me. Can anyone please point in the right direction? I'm assuming the oAuth library is to be used but what I'd really like is a snippet of code I can directly copy paste and get this to work.
I would like to use the EmailField in a form. However, instead of only storing
[email protected]
I want to store
"ACME Support" <[email protected]>
The reason is, that when I send email, I would like a "friendly name" to appear.
Can this be done?
Hi!
I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views:
render_to_response(...., ( {'menu': RequestContext(request)}))
The request object contains the key,value pair which is injected using a custom context processor. While this works, I had hoped there was a more generic way of passing selected parts of the request object to the template context. I've tried passing it by generic views, but as it turns out the request object isn't instantiated when parsing the urlpatterns list.
if a have a declaration like
theclass = Classroom.objects.get(classname = classname)
members = theclass.members.all()
and i want to display all the members(of a class) in a template, how should i do it??
if i write:
{{theclass.members.all}}
the output is an empty list(though the class has some members)
How should the elements of a m2m table be displayed in a template?
thanks!
I followed the Djangoappengine instructions.
I used their django-testapp and copied the following folders in the django-testapp folder according to what I understood the instructions to say:
django
djangoappengine
djangotoolbox
I then started the dev server by running:
manage.py runserver
Then navigated to
http://localhost:8000/
and got the "It worked!" page, which is great, but it says the following at the bottom:
You're seeing this message because you
have DEBUG = True in your Django
settings file and you haven't
configured any URLs. Get to work!
I am an absolute beginner with Django and App Engine and Djangoappengine and Django-nonrel, so I am pretty lost.
How do I configure URLs? Or a link to the how to will help.
I took a look at the Django tutorial, but am unsure how much of it is relevant to Djangoappengine and Django-nonrel as a lot of the starting steps have to do with SQL databases.
Basically some direction on how to get my app running will be great.
Thanx much.
I've used django ImageFieldFile,
from django.db.models.fields.files import ImageFieldFile
now I want to restrict the user to use only Image files when uploading from browser
I'm trying to make a form that handles the checking of a domain: the form should fail based on a variable that was set earlier in another form.
Basically, when a user wants to create a new domain, this form should fail if the entered domain exists.
When a user wants to move a domain, this form should fail if the entered domain doesn't exist.
I've tried making it dynamic overload the initbut couldn't see a way to get my passed variabele to the clean function.
I've read that this dynamic validation can be accomplished using a factory method, but maybe someone can help me on my way with this?
Here's a simplified version of the form so far:
#OrderFormStep1 presents the user with a choice: create or move domain
class OrderFormStep2(forms.Form):
domain = forms.CharField()
extension = forms.CharField()
def clean(self):
cleaned_data = self.cleaned_data
domain = cleaned_data.get("domain")
extension = cleaned_data.get("extension")
if domain and extension:
code = whoislookup(domain+extension);
#Raise error based on result from OrderFormStep1
#raise forms.ValidationError('error, domain already exists')
#raise forms.ValidationError('error, domain does not exist')
return cleaned_data
I've been tasked with providing a workshop for my co-workers to teach them Django.
They're all good programmers but they've never done any web programming.
I was thinking to just go through the Django tutorial with them, but are there things in there that wouldn't make sense to non-web programmers?
Do they need any kind of webdev background first? Any thoughts on a good way to provide the basics so that Django will make sense?
if i have queries on multiple tables like:
d = Relations.objects.filter(follow = request.user).filter(date_follow__lt = last_checked)
r = Reply.objects.filter(reply_to = request.user).filter(date_reply__lt = last_checked)
article = New.objects.filter(created_by = request.user)
vote = Vote.objects.filter(voted = article).filter(date__lt = last_checked)
and i want to display the results from all of them ordered by date (i mean not listing all the replies, then all the votes, etc ).
Somehow, i want to 'join all these results', in a single queryset.
Is there possible?
Hy guys sorry for this post but i need help with my application, i need optimize my view. I have 5 models, how i can do this?
def save(request):
# get the request.POST in content
if request.POST:
content = request.POST
dicionario = {}
# create a dict to get the values in content
for key,value in content.items():
# get my fk Course.objects
if key == 'curso' :
busca_curso = Curso.objects.get(id=value)
dicionario.update({key:busca_curso})
else:
dicionario.update({key:value})
#create the new teacher
Professor.objects.create(**dicionario)
my questions are?
1 - How i can do this function in a generic way? Can I pass a variable in a %s to create and
get? like this way ?
foo = "Teacher" , bar = "Course"
def save(request, bar, foo):
if request post:
...
if key == 'course' :
get_course = (%s.objects.get=id=value) %bar
...
(%s.objects.create(**dict)) %foo ???
i tried do this in my view but don't work =/, can somebody help me to make this work ? Thanks
I use dumpdata to output all my apps's classes. One of my app has one class that never get's outputted and I don't know where to start looking to know what's wrong. The class is used regularly, every other classes in the app are dumped fine and dumpdata doesn't throw any error.
Any cue ?
this is the code:
http://code.google.com/p/google-app-engine-samples/source/browse/trunk/django_example
and can you import 'settings' to the views.py
thanks
I've got a view that I'm trying to test with the Client object. Can I get to the variables I injected into the render_to_response of my view?
Example View:
def myView(request):
if request.method == "POST":
# do the search
return render_to_response('search.html',{'results':results},context_instance=RequestContext(request))
else:
return render_to_response('search.html',context_instance=RequestContext(request)
Test:
c = Client()
response = c.post('/school/search/', {'keyword':'beagles'})
# how do I get to the 'results' variable??
The urlconf and view is as follows:
url(r'^register/$',
register,
{ 'backend': 'registration.backends.default.DefaultBackend' },
name='registration_register'),
def register(request, backend, success_url=None, form_class=None,
disallowed_url='registration_disallowed',
template_name='registration/registration_form.html',
extra_context=None):
What i want to do is redirect users to the register page and specify a success_url. I tried reverse('registration.views.register', kwargs={'success_url':'/test/' }) but that doesn't seem to work. I've been trying for hours and can't get my mind around getting it right. Thanks
I've just set our development Django site to use redis for a cache backend and it was all working fine. I brought down redis to see what would happen, and sure enough Django 404's due to cache backend behaviour. Either the Connection was refused, or various other errors.
Is there any way to instruct Django to ignore Cache errors, and continue processing the normal way? It seems weird that caching is a performance optimization, but can bring down an entire site if it fails.
I tried to write a wrapper around the backend like so:
class CacheClass(redis_backend.CacheClass):
""" Wraps the desired Cache, and falls back to global_settings default on init failure """
def __init__(self, server, params):
try:
super(CacheClass, self).__init__(server, params)
except Exception:
from django.core import cache as _
_.cache = _.get_cache('locmem://')
But that won't work, since I'm trying to set the cache type in the call that sets the cache type. It's all a very big mess.
So, is there any easy way to swallow cache errors? Or to set the default cache backend on failure?
Intro
I am working on an e-commerce website. And we want to add a feature where a user can refer others via a custom link e.g.:
http://mysite.com/a1t2312 or http://mysite.com/?ref=a1t2312 (a1t231 being the referral code).
A user following such a link, will navigate a few pages on the site. And if he reached the 'buy' page and purchases something - the original referrer will get a discount.
The question is:
What is the best method to track the referral code ? Put it in the user's cookies ? Stick it somehow into the session ? Other method ?
Thanks
Hi,
I have following case: I want to use uncompressed js/css files during development (to debug js for example) but on production I want to switch automatically to minified versions of that files.
some simple solution is to put in your template:
<script src="some_js.{% if not debug %}min.{% endif %}js"....
but this require manully providing that such file exist and to do minifaction manullay after original file change.
How do you accomplish this in your projects? Is there any tool for this?
hi guys,
i have a notification list, and i want to order them by day, meaning, that i want to have in my notification list every day a title like 'Monday 16th od September' and the notifications for that day.
I did not find anywhere how it should be done
thanks a lot!
I have the following model
class DNS(models.Model):
domain = models.ForeignKey(Domain)
host_start = models.CharField(max_length=150, blank=True, null=True)
type = models.SmallIntegerField(max_length=1, default=0, choices=DNS_CHOICE)
value = models.SmallIntegerField(max_length=3, default=0, blank=True, null=True)
ip = models.IPAddressField(blank=True, null=True)
host_end = models.ForeignKey("DNS", blank=True, null=True)
other_end = HostnameField(max_length=150, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
sticky = models.BooleanField(default=0)
other = models.BooleanField(default=0)
When I try to init a form with just foreignkeys on host_end.. it always shows all entries in the DNS table
domain = Domain.objects.get(id=request.GET['domain'], user=request.user, active=1)
form = DNSFormCNAME(initial={'ip': settings.MAIN_IP, 'type': request.GET['type'], 'host_end': DNS.objects.filter(domain=domain)})
I just want the zones that match that domain.. not all domains.
Here's my function:
def check_form(request):
if request.method == 'POST':
form = UsersForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
try:
newUser = form.save()
return HttpResponseRedirect('/testproject/summery/)
except Exception, ex:
# sys.stderr.write('Value error: %s\n' % str(ex)
return HttpResponse("Error %s" % str(ex))
else:
return render_to_response('index.html', {'form': form}, context_instance=RequestContext(request))
else:
form = CiviguardUsersForm()
return render_to_response('index.html',context_instance=RequestContext(request))
I want to pass each and every field in to a page call summery and display all the fields when user submits the form, so then users can view it before confirming the registration.
Thanks..