Search Results

Search found 3554 results on 143 pages for 'django modelformsets'.

Page 26/143 | < Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >

  • django model Form. Include fields from related models

    - by Tom
    Hi. I have a model, called Student, which has some fields, and a OneToOne relationship with user (django.contrib.auth.User). class Student(models.Model): phone = models.CharField(max_length = 25 ) birthdate = models.DateField(null=True) gender = models.CharField(max_length=1,choices = GENDER_CHOICES) city = models.CharField(max_length = 50) personalInfo = models.TextField() user = models.OneToOneField(User,unique=True) Then, I have a ModelForm for that model class StudentForm (forms.ModelForm): class Meta: model = Student Using the fields attribute in class Meta, i've managed to show only some fields in a template. However, can I indicate which user fields to show? Something as: fields =('personalInfo','user.username') is currently not showing anything. Works with only StudentFields though/ Thanks in advance.

    Read the article

  • django internationlisation

    - by ha22109
    Hello I need to have multiple language support of my django admin application.I can create the messege files.But how can i change the text of my models.The heading ,fields etc .I m only able to change the static elements which are there in my template. here is example of my class class Mymodel(model.Models): id=models.IntegerField(primary_key=true) name=models.CharField(max_length=200) group=models.CharField(max_length=200) class Meta: managed=False verbose_name_plural='My admin' db_table='my_admin' one more question.In my home page it is showing my verbose name 'My admin' which i mentioned.But when i go to list page it shows me the class name 'mymodel'.Why so.Can i changed that to

    Read the article

  • Django comparing model instances for equality

    - by orokusaki
    I understand that, with a singleton situation, you can perform such an operation as: spam == eggs and if spam and eggs are instances of the same class with all the same attribute values, it will return True. In a Django model, this is natural because two separate instances of a model won't ever be the same unless they have the same .pk value. The problem with this is that if a reference to an instance has attributes that have been updated by middleware somewhere along the way and it hasn't been saved, and you're trying to it to another variable holding a reference to an instance of the same model, it will return False of course because they have different values for some of the attributes. Obviously I don't need something like a singleton , but I'm wondering if there some official Djangonic (ha, a new word) method for checking this, or if I should simply check that the .pk value is the same with: spam.pk == eggs.pk I'm sorry if this was a huge waste of time, but it just seems like there might be a method for doing this, and something I'm missing that I'll regret down the road if I don't find it.

    Read the article

  • Use variable as dictionary key in Django template

    - by CaptainThrowup
    I'd like to use a variable as an key in a dictionary in a Django template. I can't for the life of me figure out how to do it. If I have a product with a name or ID field, and ratings dictionary with indices of the product IDs, I'd like to be able to say: {% for product in product_list %} <h1>{{ ratings.product.id }}</h1> {% endfor %} In python this would be accomplished with a simple ratings[product.id] But I can't make it work in the templates. I've tried using with... no dice. Ideas?

    Read the article

  • Django view function design

    - by dragoon
    Hi, I have the view function in django that written like a dispatcher calling other functions depending on the variable in request.GET, like this: action = '' for act in ('view1', 'view2', 'view3', 'view4', ... ): if act in request.GET: action = act break ... if action == '': response = view0(request, ...) elif action == 'view1': response = view1(request, ...) elif action == 'view2': response = view2(request, ...) ... The global dispatcher function contains many variable initialization routines and these variables are then used in viewXX functions. So I feed that this is bad view design but I don't know how I can rewrite it?

    Read the article

  • Django Passing Custom Form Parameters to Formset

    - by Paolo Bergantino
    I have a Django Form that looks like this: class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) I call this form with something like this: form = ServiceForm(affiliate=request.affiliate) Where request.affiliate is the logged in user. This works as intended. My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this: ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) And then I need to create it like this: formset = ServiceFormSet() Now how can I pass affiliate=request.affiliate to the individual forms this way?

    Read the article

  • django admin gives warning "Field 'X' doesn't have a default value"

    - by noam
    I have created two models out of an existing legacy DB , one for articles and one for tags that one can associate with articles: class Article(models.Model): article_id = models.AutoField(primary_key=True) text = models.CharField(max_length=400) class Meta: db_table = u'articles' class Tag(models.Model): tag_id = models.AutoField(primary_key=True) tag = models.CharField(max_length=20) article=models.ForeignKey(Article) class Meta: db_table = u'article_tags' I want to enable adding tags for an article from the admin interface, so my admin.py file looks like this: from models import Article,Tag from django.contrib import admin class TagInline(admin.StackedInline): model = Tag class ArticleAdmin(admin.ModelAdmin): inlines = [TagInline] admin.site.register(Article,ArticleAdmin) The interface looks fine, but when I try to save, I get: Warning at /admin/webserver/article/382/ Field 'tag_id' doesn't have a default value

    Read the article

  • Django file uploads - Just can't work it out

    - by phoebebright
    OK I give up - after 5 solid hours trying to get a django form to upload a file, I've checked out all the links in stackoverflow and googled and googled. Why is it so hard, I just want it to work like the admin file upload? So I get that I need code like: if submitForm.is_valid(): handle_uploaded_file(request.FILES['attachment']) obj = submitForm.save() and I can see my file in request.FILES['attachment'] (yes I have enctype set) but what am I supposed to do in handle_uploaded_file? The examples all have a fixed file name but obviously I want to upload the file to the directory I defined in the model, but I can't see where I can find that. def handle_uploaded_file(f): destination = open('fyi.xml', 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() Bet I'm going to feel really stupid when someone points out the obvious!

    Read the article

  • Popularity Algorithm - SQL / Django

    - by RadiantHex
    Hi folks, I've been looking into popularity algorithms used on sites such as Reddit, Digg and even Stackoverflow. Reddit algorithm: t = (time of entry post) - (Dec 8, 2005) x = upvotes - downvotes y = {1 if x > 0, 0 if x = 0, -1 if x < 0) z = {1 if x < 0, otherwise x} log(z) + (y * t)/45000 I have always performed simple ordering within SQL, I'm wondering how I should deal with such ordering. Should it be used to define a table, or could I build an SQL with the ordering within the formula (without hindering performance)? I am also wondering, if it is possible to use multiple ordering algorithms in different occasions, without incurring into performance problems. I'm using Django and PostgreSQL. Help would be much appreciated! ^^

    Read the article

  • Tips/Process for web-development using Django in a small team

    - by Mridang Agarwalla
    We're developing a web app uing Django and we're a small team of 3-4 programmers — some doing the UI stuff and some doing the Backend stuff. I'd love some tips and suggestions from the people here. This is out current setup: We're using Git as as our SCM tool and following this branching model. We're following the PEP8 for your style guide. Agile is our software development methodology and we're using Jira for that. We're using the Confluence plugin for Jira for documentation and I'm going to be writing a script that also dumps the PyDocs into Confluence. We're using virtualenv for sandboxing We're using zc.buildout for building This is whatever I can think of off the top of my head. Any other suggestions/tips would be welcome. I feel that we have a pretty good set up but I'm also confident that we could do more. Thanks.

    Read the article

  • Django: How to create a model dynamically just for testing

    - by muhuk
    I have a Django app that requires a settings attribute in the form of: RELATED_MODELS = ('appname1.modelname1.attribute1', 'appname1.modelname2.attribute2', 'appname2.modelname3.attribute3', ...) Then hooks their post_save signal to update some other fixed model depending on the attributeN defined. I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?) Solutions that allow me to use test fixtures would be great.

    Read the article

  • django-haystack ordering - How do I handle this?

    - by Bartek
    Hi there, I'm using django-haystack for a search page on my site. I'm basically done, but not quite happy with the ordering and not quite sure how haystack decides how to order everything. I know I can over-ride the SearchQuerySet by using order_by but that over-rides it entirely. Let's say I want to force the search to order by in stock (BooleanField), so that the products that are in stock show up on top, but then do everything else as it normally would. How do I do that? I tried doing order_by('-in_stock', 'content') figure content was what it used by default but it produces very different results from if I just leave it to do its own ordering. Thanks for any input on this matter!

    Read the article

  • Django queries Especial Caracters

    - by Jorge Machado
    Hi, I Working on location from google maps and using django to. My question is: I have a String in request.GET['descricao'] lets say it contains "Via rapida". In my database i have store = "Via Rápida" i'm doing : local = Local.objects.filter(name__icontains=request.GET['descricao']) with that i can get everthing fine like "Via Rapida" but the result that have "Via rápida" never get match in the query (ASCI caracter may be ?) what must i do given a string "Via rapida" match "via rápida" and "via rapida" ? Regular Expressions ? how ? Thanks

    Read the article

  • user model password field default password field in django

    - by imran-glt
    Hi, I've created a custom user model in my application. This user model is working fine, but there are a couple of problems I have with it. 1) The change password link in the my register.html page doesn't work? 2) The default password box on the add/edit page for a user is a little unfriendly. Ideally, what I'd like is the two password fields from the change password form on the add/edit user form in the admin, which will automatically turn convert the entered password into a valid encrypted password in Django. This would make the admin system MUCH friendlier and much more suited to my needs, as a fair number of user accounts will be created and maintained manually in this app, and the person responsible for doing so will likely be scared off at the sight of that admin field, or just type a clear text password and wonder why it doesn't work. Is this possible / How do I do this?

    Read the article

  • Can this be done with the ORM? - Django

    - by RadiantHex
    Hi folks, I have a few item listed in a database, ordered through Reddit's algorithm. This is it: def reddit_ranking(post): t = time.mktime(post.created_on.timetuple()) - 1134000000 x = post.score if x>0: y=1 elif x==0: y=-0 else: y=-1 if x<0: z=1 else: z=x return (log(z) + y * t/45000) I'm wondering if there is any clever way of using Django's ORM, in order to UPDATE the models in bulk. Without doing this: items = Item.objects.filter(created_on__gte=datetime.now()-timedelta(days=7)) for item in items: item.reddit_rank = reddit_rank(item) item.save() I know about the F() object, but I can't figure out if this function can be performed inside the ORM. Any ideas? Help would be very much appreciated!

    Read the article

  • Porting Django's templates engine to C

    - by sandra
    Hi folks, I recently wrote a simple and tiny embedded HTTP server for my C++ app (QT) and I played a little bit with Ry's http-parser and loved it. This guy is crazy. So I told to myself: "Hey! Why not port the django template engine to C?" That'd be awesome! I know, it won't be an easy task (not at all, I know) but I'd really love to implement this. So I came here for inspiration, ideas, opinions... I'd really love to have some pointers on the subject, ideas, what is already done, which major problems I'll encounter (and how to solve them) - How not to reinvent the wheel... anyway, you got the idea :) Thanks a million times! P.S. Simple code snippets, and links to tools and libs are very welcome! P.P.S. I'm already aware of grantlee, I took a look into its sources. Well... that's C++ and its specific to Qt.

    Read the article

  • How to limit choice field options based on another choice field in django admin

    - by umnik700
    I have the following models: class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) item = models.ForeignKey(Item) In the admin interface when creating a new Demo, after user picks category from the dropdown, I would like to limit the number of choices in the "items" drop-down. If user selects another category then the item choices should update accordingly. I would like to limit item choices right on the client, before it even hits the form validation on the server. This is for usability, because the list of items could be 1000+ being able to narrow it down by category would help to make it more manageable. Is there a "django-way" of doing it or is custom JavaScript the only option here?

    Read the article

  • Django: ordering by backward related field property

    - by Silver Light
    Hello! I have two models related one-to-many: a Post and a Comment: class Post(models.Model): title = models.CharField(max_length=200); content = models.TextField(); class Comment(models.Model): post = models.ForeignKey('Post'); body = models.TextField(); date_added = models.DateTimeField(); I want to get a list of posts, ordered by the date of the latest comment. If I would write a custom SQL query it would look like this: SELECT `posts`.`*`, MAX(`comments`.`date_added`) AS `date_of_lat_comment` FROM `posts`, `comments` WHERE `posts`.`id` = `comments`.`post_id` GROUP BY `posts`.`id` ORDER BY `date_of_lat_comment` DESC How can I do same thing using django ORM?

    Read the article

  • Edit the opposite side of a many to many relationship with django generic form

    - by Ed
    I have two models: class Actor(models.Model): name = models.CharField(max_length=30, unique = True) event = models.ManyToManyField(Event, blank=True, null=True) class Event(models.Model): name = models.CharField(max_length=30, unique = True) long_description = models.TextField(blank=True, null=True) In a previous question: http://stackoverflow.com/questions/2503243/django-form-linking-2-models-by-many-to-many-field, I created an EventForm with a save function: class EventForm(forms.ModelForm): class Meta: model = Event def save(self, commit=True): instance = forms.ModelForm.save(self) instance.actors_set.clear() for actor in self.cleaned_data['actors']: instance.actors_set.add(actors) return instance This allowed me to add m2m links from the other side of the defined m2m connection. Now I want to edit the entry. I've been using a generic function: def generic_edit(request, modelname, object_id): modelname = modelname.lower() form_class = form_dict[modelname] return update_object(request, form_class = form_class, object_id = object_id, template_name = 'createdit.html' ) but this pulls in all the info except the many-to-many selections saved to this object. I think I need to do something similar to this: http://stackoverflow.com/questions/1700202/editing-both-sides-of-m2m-in-admin-page, but I haven't figured it out. How do I use the generic update_object to edit the other side of many-to-many link?

    Read the article

  • Evaluating Django Chained QuerySets Locally

    - by jnadro52
    Hello All: I am hoping someone can help me out with a quick question I have regarding chaining Django querysets. I am noticing a slow down because I am evaluating many data points in the database to create data trends. I was wondering if there was a way to have the chained filters evaluated locally instead of hitting the database. Here is a (crude) example: pastries = Bakery.objects.filter(productType='pastry') # <--- will obviously always hit DB, when evaluated cannoli = pastries.filter(specificType='cannoli') # <--- can this be evaluated locally instead of hitting the DB when evaluated, as long as pastries was evaluated? I have checked the docs and I do not see anything specifying this, so I guess it's not possible, but I wanted to check with the 'braintrust' first ;-). BTW - I know that I can do this myself by implementing some methods to loop through these datapoints and evaluate the criteria, but there are so many datapoints that my deadline does not permit me manually implementing this. Thanks in advance.

    Read the article

  • ImportError and Django driving me crazy

    - by John Peebles
    OK, I have the following directory structure (it's a django project): - project -- app and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py I'm trying to do the following: import urllib2 import os import sys import time import datetime import re import BeautifulSoup sys.path.append('/home/userspace/Development/') os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' from project.app.models import ClassName and this code just isn't working. I get an error of: Traceback (most recent call last): File "scraper.py", line 14, in from project.app.models import ClassName ImportError: No module named project.app.models This code above used to work, but broke somewhere along the line and I'm extremely confused as to why I'm having problems. On SnowLeopard using python2.5.

    Read the article

  • Django database caching

    - by hekevintran
    I have a Django form that uses an integer field to lookup a model object by its primary key. The form has a save() method that uses the model object referred to by the integer field. The model's manager's get() method is called twice, once in the clean method and once in the save() method: class MyForm(forms.Form): id_a = fields.IntegerField() def clean_id_a(user_id): id_a = self.cleaned_data['id_a'] try: # here is the first call to get MyModel.objects.get(id=id_a) except User.DoesNotExist: raise ValidationError('Object does not exist') def save(self): id_a = self.cleaned_data['id_a'] # here is the second call to get my_model_object = MyModel.objects.get(id=id_a) # do other stuff I wasn't sure whether this hits the database two times or one time so I returned the object itself in the clean method so that I could avoid a second get() call. Does calling get() hit the database two times? Or is the object cached in the thread? class MyForm(forms.Form): id_a = fields.IntegerField() def clean_id_a(user_id): id_a = self.cleaned_data['id_a'] try: # here is my workaround return MyModel.objects.get(id=id_a) except User.DoesNotExist: raise ValidationError('Object does not exist') def save(self): # looking up the cleaned value returns the model object my_model_object = self.cleaned_data['id_a'] # do other stuff

    Read the article

  • How do I find the "concrete class" of a django model baseclass

    - by Mr Shark
    I'm trying to find the actual class of a django-model object, when using model-inheritance. Some code to describe the problem: class Base(models.model): def basemethod(self): ... class Child_1(Base): pass class Child_2(Base): pass If I create various objects of the two Child classes and the create a queryset containing them all: Child_1().save() Child_2().save() (o1, o2) = Base.objects.all() I want to determine if the object is of type Child_1 or Child_2 in basemethod, I can get to the child object via o1.child_1 and o2.child_2 but that reconquers knowledge about the childclasses in the baseclass. I have come up with the following code: def concrete_instance(self): instance = None for subclass in self._meta.get_all_related_objects(): acc_name = subclass.get_accessor_name() try: instance = self.__getattribute__(acc_name) return instance except Exception, e: pass But it feels brittle and I'm not sure of what happens when if I inherit in more levels.

    Read the article

  • In django models, how to make all table names not have the app label?

    - by Luigi
    I have a database that was already being used by other applications before i began writing a web interface with django for it. The table names follow simple naming standards, so the django model Customer should map to the table "customer" in the db. At the same time I'm adding new tables/models. Since I find it cumbersome to use app_customer every time i have to write a query (django's ORM is definitely not enough for them) in the other applications and I don't want to rename the existing tables, what is the best way to make all models in my django app use tables without applabel_, besides adding a Meta class with db_table= to each model? Is there any reason why I shouldn't do this? I have only one web app that needs to access this db, everything else doesn't use django models.

    Read the article

  • how to change display text in django admin foreignkey dropdown

    - by FurtiveFelon
    Hi all, I have a task list, with ability to assign users. So i have foreignkey to User model in the database. However, the default display is username in the dropdown menu, i would like to display full name (first last) instead of the username. If the foreignkey is pointing to one of my own classes, i can just change the str function in the model, but User is a django authentication model, so i can't easily change it directly right? Anyone have any idea how to accomplish this? Thanks a lot!

    Read the article

< Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >