Search Results

Search found 3558 results on 143 pages for 'django templatetags'.

Page 82/143 | < Previous Page | 78 79 80 81 82 83 84 85 86 87 88 89  | Next Page >

  • Django | capture sub domain as a string

    - by MMRUser
    How do I capture a part of sub-domain name and get that name as a string in my views through a request. ex: user.domain.com developer.domain.com I want to capture the user part of this domain name through a request (lets say when the first time user hits the page). Thanks.

    Read the article

  • Django Template Inheritance -- Missing Images?

    - by user367817
    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!

    Read the article

  • Putting links into text in Django

    - by Dane Larsen
    I have a notifications app that generates notifications for users. The notification class has to be really general, because notifications are generated by all sorts of different things. My question is this: How do I insert links into the text of the notifications? What I tried was this: note = Notification(..., notification="""%s %s has accepted the task: <a href="/tasks/%d/">%s</a>.""" % (request.user.first_name, request.user.last_name, task.id, task.name), ...) In retrospect, it's obvious this wouldn't work. How should I go about this? Thanks in advance!

    Read the article

  • How to disable translations during unit tests in django?

    - by Denilson Sá
    I'm using Django Internationalization tools to translate some strings from my application. The code looks like this: from django.utils.translation import ugettext as _ def my_view(request): output = _("Welcome to my site.") return HttpResponse(output) Then, I'm writing unit tests using the Django test client. These tests make a request to the view and compare the returned contents. How can I disable the translations while running the unit tests? I'm aiming to do this: class FoobarTestCase(unittest.TestCase): def setUp(self): # Do something here to disable the string translation. But what? # I've already tried this, but it didn't work: django.utils.translation.deactivate_all() def testFoobar(self): c = Client() response = c.get("/foobar") # I want to compare to the original string without translations. self.assertEquals(response.content.strip(), "Welcome to my site.")

    Read the article

  • Passing list of values to django view via jQuery ajax call

    - by finspin
    I'm trying to pass a list of numeric values (ids) from one web page to another with jQuery ajax call. I can't figure out how to pass and read all the values in the list. I can successfully post and read 1 value but not multiple values. Here is what I have so far: jQuery: var postUrl = "http://localhost:8000/ingredients/"; $('li').click(function(){ values = [1, 2]; $.ajax({ url: postUrl, type: 'POST', data: {'terid': values}, traditional: true, dataType: 'html', success: function(result){ $('#ingredients').append(result); } }); }); /ingredients/ view: def ingredients(request): if request.is_ajax(): ourid = request.POST.get('terid', False) ingredients = Ingredience.objects.filter(food__id__in=ourid) t = get_template('ingredients.html') html = t.render(Context({'ingredients': ingredients,})) return HttpResponse(html) else: html = '<p>This is not ajax</p>' return HttpResponse(html) With Firebug I can see that POST contains both ids but probably in the wrong format (terid=1&terid=2). So my ingredients view picks up only terid=2. What am I doing wrong? EDIT: To clarify, I need the ourid variable pass values [1, 2] to the filter in the ingredients view.

    Read the article

  • django many to many validation when add()

    - by Julien
    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)

    Read the article

  • Django 1.2 - Pb with a form in a template (WSGIRequest)

    - by Tom
    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 !

    Read the article

  • Django model help

    - by dotty
    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")

    Read the article

  • Asynchronous database update in Django?

    - by Mark
    I have a big form on my site. When the users fill it out and submit it, most of the data just gets dumped to the database, and then they get redirected to a new page. However, I'd also like to use the data to query another site, and then parse the results. That might take a bit longer. It's not essential that the user sees these results right away, so I was wondering if it's possible to asynchronously call a function that will handle this, and then return an HttpResponse from my view like usual without making them wait? If so... how? Any particular libraries I should look at?

    Read the article

  • optimizing the jquery in django

    - by sankar
    I have done the following code which actually dynamically generate the values in the third list box using ajax and jquery concepts. Thoug it works, i need to optimize it. Below is the code i am working on now. <html> <head> <title>Comparison based on ID Number</title> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> {% if form.errors %} <p style="color: red;"> Please correct the error{{ form.errors|pluralize }} below. </p> {% endif %} <form action="/idnumber/" method="post" align= "center">{% csrf_token %} <p>Select different id numbers and the name of the <b> Measurement Group </b>to start the comparison</p> <table align = "center"> <tr> <th><label for="id_criteria_1">Id Number 1:</label></th> <th> {{ form.idnumber_1 }} </th> </tr> <tr> <th><label for="id_criteria_2">Id Number 2:</label></th> <th> {{ form.idnumber_2 }} </th> </tr> <tr> <th><label for="group_name_list">Group Name:</label></th> <th><select name="group_name_list" id="id_group_name_list"> <option>Select</option> </select> </th> </tr> <script> $('#id_idnumber_2').change( function get_group_names() { var value1 = $('#id_idnumber_1').attr('value'); var value2 = $(this).attr('value'); alert(value1); alert(value2); var request = $.ajax({ url: "/getGroupnamesforIDnumber/", type: "GET", data: {idnumber_1 : value1,idnumber_2 : value2}, dataType: "json", success: function(data) { alert(data); var myselect = document.getElementById("group_name_list"); document.getElementById("group_name_list").options.length = 1; var length_of_data = data.length; alert(length_of_data); try{ for(var i = 0;i < length_of_data; i++) { myselect.add(new Option(data[i].group_name, "i"), myselect.options[i]) //add new option to beginning of "sample" } } catch(e){ //in IE, try the below version instead of add() for(var i = 0;i < length_of_data; i++) { myselect.add(new Option(data[i].group_name, data[i].group_name)) //add new option to end of "sample" } } } }); }); </script> <tr align = "center"><th><input type="submit" value="Submit"></th></tr> </table> </form> </body> </html> everything works fine but there is a little problem in my code. (ie) my ajax function calls only when there is a change in the select list 2 (ie) 'id_number_2'. I want to make it call in such a way that which ever select box, the third list box should be updated automatically. Can anyone please help me on this with a possible logical solution

    Read the article

  • Django Aggregation Across Reverse Relationship

    - by Tom
    Given these two models: class Profile(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_('user')) about = models.TextField(_('about'), blank=True) zip = models.CharField(max_length=10, verbose_name='zip code', blank=True) website = models.URLField(_('website'), blank=True, verify_exists=False) class ProfileView(models.Model): profile = models.ForeignKey(Profile) viewer = models.ForeignKey(User, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) I want to get all profiles sorted by total views. I can get a list of profile ids sorted by total views with: ProfileView.objects.values('profile').annotate(Count('profile')).order_by('-profile__count') But that's just a dictionary of profile ids, which means I then have to loop over it and put together a list of profile objects. Which is a number of additional queries and still doesn't result in a QuerySet. At that point, I might as well drop to raw SQL. Before I do, is there a way to do this from the Profile model? ProfileViews are related via a ForeignKey field, but it's not as though the Profile model knows that, so I'm not sure how to tie the two together. As an aside, I realize I could just store views as a property on the Profile model and that may turn out to be what I do here, but I'm still interested in learning how to better use the Aggregation functions.

    Read the article

  • Downloading a csv file in django

    - by spyder
    I am trying to download a CSV file using HttpResponse to make sure that the browser treats it as an attachment. I follow the instructions provided here but my browser does not prompt a "Save As" dialog. I cannot figure out what is wrong with my function. All help is appreciated. dev savefile(request): try: myfile = request.GET['filename'] filepath = settings.MEDIA_ROOT + 'results/' destpath = os.path.join(filepath, myfile) response = HttpResponse(FileWrapper(file(destpath)), mimetype='text/csv' ) response['Content-Disposition'] = 'attachment; filename="%s"' %(myfile) return response except Exception, err: errmsg = "%s"%(err) return HttpResponse(errmsg) Happy Pat's day!

    Read the article

  • Django i18n and SEO

    - by etam
    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.

    Read the article

  • django forms from two tables referencial integrity

    - by dana
    i have a class named cv,and a class named university, and each user that completes his cv, should choose a University he studyes at. My problem is: one student can study at one or 2 or three universities, or may be a user that is not student. I need to take this data into a form, and i use ModelForm. The data from the Cv class, and from the University class in the same form, and the user can add one or more universities, or no university. (in the same form) How should i do it? Should i use ModelForm? if i have a foreign key in the CV class, and the user is not a student (so he is at zero universities), i may get an referencial integrity error. thanks a lot

    Read the article

  • Django: remove all m2m relations

    - by pistacchio
    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

    Read the article

  • Can't iterate over nestled dict in django

    - by fredrik
    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

    Read the article

  • How to make django test framework read from live database?

    - by lfborjas
    I realize there's a similar question here, but this one has a different approach: I have a django app that does queries over data indexed with djapian ; I'd like to write unit tests for this app's search component, and, obviously, I'd need the django settings module and all connections with the database active, so the test runner that django provides seems ideal. however, the django testing framework creates a dummy database and I'd hate to dump all my data to a fixture and then index it (the tests would take forever!); My data isn't at risk because the tests would only read from the database, so, how could this be achieved? -I'm new at this whole unit testing thing, so the solution of writing a new test runner I read in that similar question doesn't enlighten me a bit, at least not without some details

    Read the article

  • django url from another template than the one associated with the view-function

    - by dana
    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!

    Read the article

  • django forms overwrite data when saved

    - by dana
    If a have a form, with the data from a user, let's say a CV, and i save the data from the form into a database, but i don't want that a CV from the same user to be stored in the database more than once(when edited form instance) I want it to be overwritten every time it is saved by one same user. How can i do it? thanks a lot

    Read the article

  • Django: request object to template context transparancy

    - by anars
    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.

    Read the article

  • Structure for Django methods that span different models

    - by Duncan
    I have two models (say A and B) which are independent and have independent methods. I want to add some methods that operate on both models though. for example, addX() will create an object from both models A and B. What's the best way to structure code in this situation, since it doesnt make sense to have the method belong to either of the models methods. Is the standard to write a service for the kind of 'abstract' model?

    Read the article

  • django modeling

    - by SledgehammerPL
    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?

    Read the article

  • django access to parent

    - by SledgehammerPL
    model: class Product(models.Model): name = models.CharField(max_length = 128) (...) def __unicode__(self): return self.name 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) def __unicode__(self): return unicode(self.quantity!=0 and self.quantity or '') + ' ' + unicode(self.unit) + ' ' + self.product.genitive And now I'd like to get list of the most often useable products: ReceiptComponent.objects.values('product').annotate(Count('product')).order_by('-product__count' the example result: [{'product': 3, 'product__count': 5}, {'product': 6, 'product__count': 4}, {'product': 5, 'product__count': 3}, {'product': 7, 'product__count': 2}, {'product': 1, 'product__count': 2}, {'product': 11, 'product__count': 1}, {'product': 8, 'product__count': 1}, {'product': 4, 'product__count': 1}, {'product': 9, 'product__count': 1}] It's almost what I need. But I'd prefer having Product object not product value, because I'd like to use this in views.py for generating list.

    Read the article

< Previous Page | 78 79 80 81 82 83 84 85 86 87 88 89  | Next Page >