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?
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 ?
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'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
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
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??
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
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
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?
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?
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!
hello,
i want to make a notification function, and i need fields from 2 different models.
how can i access those fields?
in my notification view i wrote this
data = Notices.objects.filter(last_login<date_follow)
where last_login belongs to the model class User , and date_follow to Follow
but it is not a proper and correct way of accessing those variables.
How can i access them? I need to compare the two dates for realising the notifications that one did not see since his last login.
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.
I'm trying to customize how my form is displayed by using a form_snippet as suggested in the docs. Here's what I've come up with so far:
{% for field in form %}
<tr>
<th><label for="{{ field.html_name }}">{{ field.label }}:</label></th>
<td>
{{ field }}
{% if field.help_text %}<br/><small class="help_text">{{ field.help_text }}</small>{% endif %}
{{ field.errors }}
</td>
</tr>
{% endfor %}
Of course, field.html_name is not what I'm looking for. I need the id of the input field. How can I get that?
Also, is there a way I can determine if the field is required, so that I can display an asterisk beside the label?
I have the following model
class Plugin(models.Model):
name = models.CharField(max_length=50)
# more fields
which represents a plugin that can be downloaded from my site. To track downloads, I have
class Download(models.Model):
plugin = models.ForiegnKey(Plugin)
timestamp = models.DateTimeField(auto_now=True)
So to build a view showing plugins sorted by downloads, I have the following query:
# pbd is plugins by download - commented here to prevent scrolling
pbd = Plugin.objects.annotate(dl_total=Count('download')).order_by('-dl_total')
Which works, but is very slow. With only 1,000 plugins, the avg. response is 3.6 - 3.9 seconds (devserver with local PostgreSQL db), where a similar view with a much simpler query (sorting by plugin release date) takes 160 ms or so.
I'm looking for suggestions on how to optimize this query. I'd really prefer that the query return Plugin objects (as opposed to using values) since I'm sharing the same template for the other views (Plugins by rating, Plugins by release date, etc.), so the template is expecting Plugin objects - plus I'm not sure how I would get things like the absolute_url without a reference to the plugin object.
Or, is my whole approach doomed to failure? Is there a better way to track downloads? I ultimately want to provide users some nice download statistics for the plugins they've uploaded - like downloads per day/week/month. Will I have to calculate and cache Downloads at some point?
EDIT: In my test dataset, there are somewhere between 10-20 Download instances per Plugin - in production I expect this number would be much higher for many of the plugins.
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..
I'm in a situation where I must output a quite large list of objects by a CharField used to store street addresses.
My problem is, that obviously the data is ordered by ASCII codes since it's a Charfield, with the predictable results .. it sort the numbers like this;
1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21....
Now the obvious step would be to change the Charfield the proper field type (IntegerField let's say), however it cannot work since some address might have apartments .. like "128A".
I really don't know how I can order this properly ..
Hey guys, I know this question has been brought up numerous times, but I'm not quite getting the full implementation. As you can see below, I've got a form that I can dynamically tell how many rows to create. How can I create an "Add Row" link that tells the view how many rows to create? I would really like to do it without augmenting the url...
# views.py
def myView(request):
if request.method == "POST":
form = MyForm(request.POST, num_rows=1)
if form.is_valid():
return render_to_response('myform_result.html', context_instance=RequestContext(request))
else:
form = MyForm(num_rows=1)
return render_to_response('myform.html', {'form':form}, context_instance=RequestContext(request))
# forms.py
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
num_rows = kwargs.pop('num_rows',1)
super(MyForm, self).__init__(*args, **kwargs)
for row in range(0, num_rows):
field = forms.CharField(label="Row")
self.fields[str(row)] = field
# myform.html http://example.com/myform
<form action="." method="POST" accept-charset="utf-8">
<ul>
{% for field in form %}
<li style="margin-top:.25em">
<span class="normal">{{ field.label }}</span>
{{ field }}
<span class="formError">{{ field.errors }}</span>
</li>
{% endfor %}
</ul>
<input type="submit" value="Save">
</form>
<a href="ADD_ANOTHER_ROW?">+ Add Row</a>