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.
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?
I find that it's pretty common most people hardcode the navigation into their templates, but I'm dealing with a pretty dynamic news site which might be better off if the primary nav was db driven.
So I was thinking of having a Navigation model where each row would be a link.
link_id INT primary key
link_name varchar(255)
url varchar(255)
order INT
active boolean
If anyone's done something similar in the past, would you say this sort of schema is good enough?
I also wanted for there to be an optional dropdown in the admin near the url field so that a user could choose a Category model's slug since category links would be common, but I'm not quite sure how that would be 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
Hi,
if I have two simple models:
class Tag(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
title = models.CharField(max_length=100)
tags = models.ManyToManyField(Tag, blank=True)
given a Post object with a number of Tags added to it, I know hot to remove any of them, but how to do a mass remove (remove all)? Thanks
Does anyone have any clue why this doesn't work as expected.
If i use the python shell and do
team.game_set
or
team.games
It returns an error
AttributeError: 'Team' object has no attribute 'game'
If i create a Game object and call
game.home_team
it returns the correct team object
Heres my model
class Team(models.Model):
name = models.CharField(blank=True, max_length=100)
class Game(models.Model):
home_team = models.ForeignKey(Team, related_name="home_team")
Hi,
how do you prepare i18n in your websites? I mean what do you do avoid the situation when you search for i18ned websites in Polish you get English description cause English is the default one.
Thanks in advance,
Etam.
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
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?
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?
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?
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
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'))
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?
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.
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 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 ?
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
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..
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
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.