Howdy,
I have got the following file heirarchy:
project
other stuff
templates
images
images for site
app1
templates for app1
registration
login template
base.html (base for entire site)
style.css (for base.html)
In the login template, I am extending 'base.html.' 'base.html' uses 'style.css' along with all of the images in the 'templates/images' directory. For some reason, none of the CSS styles or images will show up in the login template, even though I'm extending it.
Does this missing image issue have something to do with screwed up "media" settings somewhere? I never understood those, but this is a major roadblock in my proof-of-concept, so any help is appreciated.
Thanks!
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.
Hi
i have a Category model with parent/child self relation For primary category and sub categories :
class Place(models.Model):
name = models.CharField(_("name"), max_length=100)
categories = models.ManyToManyField("Category", verbose_name=_("categories"))
class Category(models.Model):
name = models.CharField(_("name"), max_length=100)
parent = models.ForeignKey('self', blank=True, null=True, related_name='child_set')
i need to prevent orphans, to prevent this kind of errors (in admin web interface)
c_parent = Category(name='Restaurant')
c_parent.save()
c_child = Category(name="Japanese restaurant", parent=c_parent)
c_child.save()
place1 = Place (name="Planet sushi")
place1.save()
place1.categories.add(c_parent)
place1.categories.add(c_child)
So now we have a new Place called "Planet sushi", it's a Restaurant (root category), and a Japanese Restaurant (sub category)
but i want to prevent this kind of things :
place2 = Place (name="Tokyofood")
place2.save()
place2.categories.add(c_child)
because parent is not set, or is not the correct parent category
where can i do form validation for the admin ? and other forms (because any user can add a new place and will have to choose correct categories for)
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'm not sure why, but this condition will never evaluate True for me. I'm feeding it datetime.today() in the urls file. Am I missing something?
Template:
{% load humaize %}
{{ entry.date|naturalday }} {# Evals to "today" #}
{% ifequal entry.date|naturalday "today" %}
True
{{ entry.date|date:"fA"|lower }} {{ entry.date|naturalday|title }}
{% else %}
False
{{ entry.date|naturalday|title }}
{% endifequal %}
Hi, I'm trying to display a form on a template, but I get a fantastic error :
Caught AttributeError while rendering: 'WSGIRequest' object has no attribute 'get'
The error is in this line : {% for field in form.visible_fields %}
My view :
def view_discussion(request, discussion_id):
discussion = get_object_or_404(Discussion, id=discussion_id)
form = BaseMessageForm(request)
return render(request,'ulule/discussions/view_discussion.html', {
'discussion':discussion,
'form':form,
})
My form :
class BaseMessageForm(forms.Form):
message_content = forms.CharField(widget=forms.HiddenInput())
My template :
<form action="" method="post">
{% csrf_token %}
{% for field in form.visible_fields %}
<div class="fieldWrapper">
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<p><input type="submit" value="Send message" /></p>
</form>
Thanks a lot for your help !
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?
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,
Im trying to iterate over a nestled dict list. The first level works fine. But the second level is treated like a string not dict.
In my template I have this:
{% for product in Products %}
<li>
<p>{{ product }}</p>
{% for partType in product.parts %}
<p>{{ partType }}</p>
{% for part in partType %}
<p>{{ part }}</p>
{% endfor %}
{% endfor %}
</li>
{% endfor %}
It's the {{ part }} that just list 1 char at the time based on partType. And it seams that it's treated like a string. I can however via dot notation reach all dict but not with a for loop. The current output looks like this:
Color
C
o
l
o
r
Style
S
.....
The Products object looks like this in the log:
[{'product': <models.Products.Product object at 0x1076ac9d0>, 'parts': {u'Color': {'default': u'Red', 'optional': [u'Red', u'Blue']}, u'Style': {'default': u'Nice', 'optional': [u'Nice']}, u'Size': {'default': u'8', 'optional': [u'8', u'8.5']}}}]
What I trying to do is to pair together a dict/list for a product from a number of different SQL queries.
The web handler looks like this:
typeData = Products.ProductPartTypes.all()
productData = Products.Product.all()
langCode = 'en'
productList = []
for product in productData:
typeDict = {}
productDict = {}
for type in typeData:
typeDict[type.typeId] = { 'default' : '', 'optional' : [] }
productDict['product'] = product
productDict['parts'] = typeDict
defaultPartsData = Products.ProductParts.gql('WHERE __key__ IN :key', key = product.defaultParts)
optionalPartsData = Products.ProductParts.gql('WHERE __key__ IN :key', key = product.optionalParts)
for defaultPart in defaultPartsData:
label = Products.ProductPartLabels.gql('WHERE __key__ IN :key AND partLangCode = :langCode', key = defaultPart.partLabelList, langCode = langCode).get()
productDict['parts'][defaultPart.type.typeId]['default'] = label.partLangLabel
for optionalPart in optionalPartsData:
label = Products.ProductPartLabels.gql('WHERE __key__ IN :key AND partLangCode = :langCode', key = optionalPart.partLabelList, langCode = langCode).get()
productDict['parts'][optionalPart.type.typeId]['optional'].append(label.partLangLabel)
productList.append(productDict)
logging.info(productList)
templateData = { 'Languages' : Settings.Languges.all().order('langCode'), 'ProductPartTypes' : typeData, 'Products' : productList }
I've tried making the dict in a number of different ways. Like first making a list, then a dict, used tulpes anything I could think of.
Any help is welcome!
Bouns: If someone have an other approach to the SQL quires, that is more then welcome. I feel that it kinda stupid to run that amount of quires. What is happening that each product part has a different label base on langCode.
..fredrik
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
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.
Heyy there,
i have an application, and in my urls.py i have something like that:
urlpatterns = patterns('',
url(r'^profile_view/(?P<id>\d+)/$',
profile_view,
name='profile_view'),)
meaning that the profile_view function has id as a parameter. Now, i want to call that function from another template than the one associated with the def-view that has this url.
How should i do that? i have to put two render_to_response to one same function, in order to render the objects from both models?
thank you!
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
As a bit of a followup question to my previous , I need to pass a parameter to a view. This parameter is not known until the JS executes.
In my URLConf:
url(r'^person/device/program/oneday/(?P<meter_id>\d+)/(?P<day_of_the_week>\w+)/$',
therm_control.Get_One_Day_Of_Current_Thermostat_Schedule.as_view(),
name="one-day-url"),
I can pass it this URL and it works great! ( thanks to you guys).
http://127.0.0.1:8000/personview/person/device/program/oneday/149778/Monday/
In My template I have this:
var one_day_url = "{% url personview:one-day-url meter_id=meter_id day_of_the_week='Monday' %}";
In my javascript:
$.ajax({
type: 'GET',
url: one_day_url ,
dataType: "json",
timeout: 30000,
beforeSend: beforeSendCallback,
success: successCallback,
error: errorCallback,
complete: completeCallback
});
When this triggers it works fine except I dont necessarily want Monday all the time.
If I change the javascript to this:
var one_day_url = "{% url personview:one-day-url meter_id=meter_id %}";
and then
$.ajax({
type: 'GET',
url: one_day_url + '/Monday/',
dataType: "json",
timeout: 30000,
beforeSend: beforeSendCallback,
success: successCallback,
error: errorCallback,
complete: completeCallback
});
I get the Caught NoReverseMatch while rendering error. I assume because the URLconf still wants to rewrite to include the ?P\w+) .
I seems like if I change the URL conf that breaks the abailty to find the view , and if I do what I do above it gives me the NoREverseMatch error.
Any guidance would be appreciated.
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'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'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 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?
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'))
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'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