Search Results

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

Page 31/143 | < Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >

  • Django database caching

    - by hekevintran
    The object user has a foreign key relationship to address. Is there a difference between samples 1 and 2? Does sample 1 run the query multiple times? Or is the address object cached? # Sample 1 country = user.address.country city = user.address.city state = user.address.state # Sample 2 address = user.address country = address.country city = address.city state = address.state

    Read the article

  • django: displaying group users count in admin

    - by gruszczy
    I would like to change admin for a group, so it would display how many users are there in a certain group. I'd like to display this in the view showing all groups, the one before you enter admin for certain group. Is it possible? I am talking both about how to change admin for a group and how to add function to list_display.

    Read the article

  • How to deal with multiple sub-type of one super-type in Django admin

    - by Henri
    What would be the best solution for adding/editing multiple sub-types. E.g a super-type class Contact with sub-type class Client and sub-type class Supplier. The way shown here works, but when you edit a Contact you get both inlines i.e. sub-type Client AND sub-type Supplier. So even if you only want to add a Client you also get the fields for Supplier of vice versa. If you add a third sub-type , you get three sub-type field groups, while you actually only want one sub-type group, in the mentioned example: Client. E.g.: class Contact(models.Model): contact_name = models.CharField(max_length=128) class Client(models.Model): contact = models.OneToOneField(Contact, primary_key=True) user_name = models.CharField(max_length=128) class Supplier(models.Model): contact.OneToOneField(Contact, primary_key=True) company_name = models.CharField(max_length=128) and in admin.py class ClientInline(admin.StackedInline): model = Client class SupplierInline(admin.StackedInline): model = Supplier class ContactAdmin(admin.ModelAdmin): inlines = (ClientInline, SupplierInline,) class ClientAdmin(admin.ModelAdmin): ... class SupplierAdmin(admin.ModelAdmin): ... Now when I want to add a Client, i.e. only a Client I edit Contact and I get the inlines for both Client and Supplier. And of course the same for Supplier. Is there a way to avoid this? When I want to add/edit a Client that I only see the Inline for Client and when I want to add/edit a Supplier that I only see the Inline for Supplier, when adding/editing a Contact? Or perhaps there is a different approach. Any help or suggestion will be greatly appreciated.

    Read the article

  • Display additional data while iterating over a Django formset

    - by Jannis
    Hi, I have a list of soccer matches for which I'd like to display forms. The list comes from a remote source. matches = ["A vs. B", "C vs. D", "E vs, F"] matchFormset = formset_factory(MatchForm,extra=len(matches)) formset = MatchFormset() On the template side, I would like to display the formset with the according title (i.e. "A vs. B"). {% for form in formset.forms %} <fieldset> <legend>{{TITLE}}</legend> {{form.team1}} : {{form.team2}} </fieldset> {% endfor %} Now how do I get TITLE to contain the right title for the current form? Or asked in a different way: how do I iterate over matches with the same index as the iteration over formset.forms? Thanks for your input!

    Read the article

  • Django CSRF failure when form posts to a different frame

    - by Leopd
    I'm building a page where I want to have a form that posts to an iframe on the same page. The Template looks like this: <form action="form-results" method="post" target="resultspane" > {% csrf_token %} <input name="query"> <input type=submit> </form> <iframe src="form-results" name="resultspane" width="100%" height="70%"> </iframe> The view behind form-results is getting CSRF errors. Is there something special needed for cross-frame posting?

    Read the article

  • Django: Only one of two fields can be filled in

    - by Giovanni Di Milia
    I have this model: class Journals(models.Model): jid = models.AutoField(primary_key=True) code = models.CharField("Code", max_length=50) name = models.CharField("Name", max_length=2000) publisher = models.CharField("Publisher", max_length=2000) price_euro = models.CharField("Euro", max_length=2000) price_dollars = models.CharField("Dollars", max_length=2000) Is there a way to let people fill out either price_euro or price_dollars? I do know that the best way to solve the problem is to have only one field and another table that specify the currency, but I have constraints and I cannot modify the DB. Thanks!

    Read the article

  • Django model field value preprocessing before returning

    - by Satoru.Logic
    Hi, all. I have a Note model class like this: class Note(models.Model): author = models.ForeignKey(User, related_name='notes') content = NoteContentField(max_length=256) NoteContentField is a custom sub-class of CharField that override the to_python method in purpose of doing some twitter-text-conversion processing. class NoteContentField(models.CharField): __metaclass__ = models.SubfieldBase def to_python(self, value): value = super(NoteContentField, self).to_python(value) from ..utils import linkify return mark_safe(linkify(value)) However, this doesn't work. When I save a Note object like this: note = Note(author=request.use, content=form.cleaned_data['content']) The conversed value is saved into the database, which is not what I wanna see. Would you please tell me what's wrong with this? Thanks in advance.

    Read the article

  • Django - Better evaluation of relationship at the model level

    - by Brant
    Here's a simple relational pair of models. class Shelf(models.Model): name = models.CharField(max_length=100) def has_books(self): if Book.objects.filter(shelf=self): return True else: return False class Book(models.Model): shelf = models.ForeignKey(Shelf) name = models.CharField(max_length=100) Is there a better (or alternative) way to write the "has_book" method? I'm not a fan of the double database hit but I want to do this at the model level.

    Read the article

  • inverse relation to multiple inheriting classes in django

    - by Ofri Raviv
    Here are my schematic models: class Law(models.Model): ... class Bill(models.Model): ... # data for a proposed law, or change of an existing law class PrivateBill(Bill): ... # data for a Bill that was initiated by a parliament member class GovernmentBill(Bill): ... # data for a Bill that was initiated by the government It is possible and likely that in the future I (or maybe someone else) would want to add more Bill types. Every Bill should point to a Law (indicating what law this bill is going to change) and my question is: What is the best way to implement this? If I add the ForeignKey(Law) to Bill, I'll have a relation from every Bill to Law, but a Law would only have an inverse relation to Bills (bill_set), and not a different inverse relation to each type of bill. Of course I'll be able to filter each type of bill to get only the ones pointing to a specific Law, but this is something I think I'll need to use often, so I think having privatebill_set, governmentbill_set etc would make the code more readable. Another possible solution is to add the foreign key to each of the inheriting classes (this would give me a privatebill_set, governmentbill_set, futurebill_set), but that seems hairy because I would be relying on future programmers to remember to add that relation. How would you solve this?

    Read the article

  • Keeping track of changes - Django

    - by RadiantHex
    Hi folks!! I have various models of which I would like to keep track and collect statistical data. The problem is how to store the changes throughout time. I thought of various alternative: Storing a log in a TextField, open it and update it every time the model is saved. Alternatively pickle a list and store it in a TextField. Save logs on hard drive. What are your suggestions?

    Read the article

  • Django excluding specific instances from queryset without using field lookup

    - by Agos
    Hi, I sometimes have the need to make sure some instances are excluded from a queryset. This is the way I do it usually: unwanted_instance = Mymodel.objects.get(pk=bad_luck_number) uninteresting_stuff_happens() my_results = MyModel.objects.exclude(id=unwanted_instance.id) or, if I have more of them: my_results = MyModel.objects.exclude(id_in=[uw_in1.id, uw_in2.id, uw_in3.id]) This 'feels' a bit clunky, so I tried if I was lucky: my_ideally_obtained_results = MyModel.objects.exclude(unwanted_instance) Which doesn't work. But I read here on SO that a subquery can be used as parameter for exclude. Am I out of luck? Am I missing some functionality (checked the docs, but didn't find any useful pointer)

    Read the article

  • Complex Django filter question

    - by HWM-Rocker
    Lets say I have this class (simplified): class Tag (...): children = models.ManyToManyField(null=True, symmetrical=False) Now I already implemented the functions get_parents, get_all_ancestors. Is there a nice pythonic way to just the top level tags? If I had designed my Tags differently (to point to the parents instead) I would just make get_all_parents().filter(children=null). My first thought is to create a new function that will go recursively through all parents and save those that has none. But is there a possibility with filters or Query-objects to do the same (with fewer lines of code)? Thanks for your help. [edit] When it is finished, it should be a hierarchical tagging system. Each tag can have children, parents, but only the children are saved. I want to get all the top level tags, that point through many children / childrens children to my tag.

    Read the article

  • Changing User ModelAdmin for Django admin

    - by Leon
    How do you override the admin model for Users? I thought this would work but it doesn't? class UserAdmin(admin.ModelAdmin): list_display = ('email', 'first_name', 'last_name') list_filter = ('is_staff', 'is_superuser') admin.site.register(User, UserAdmin) I'm not looking to override the template, just change the displayed fields & ordering. Solutions please?

    Read the article

  • Doubt about django model API

    - by Clash
    Hello guys! So, here is what I want to do. I have a model Staff, that has a foreign key to the User model. I also have a model Match that has a foreign key to the User model. I want to select how much Matches every Staff has. I don't know how to do that, so far I only got it working for the User model. From Staff, it will not allow to annonate Match. This is what is working right now User.objects.annotate(ammount=Count("match")).filter(Q(ammount__gt=0)).order_by("ammount") And this is what I wanted to do Staff.objects.annotate(ammount=Count("match")).filter(Q(ammount__gt=0)).order_by("ammount") And by the way, is there any way to filter the matches? I want to filter the matches by a certain column. Thanks a lot in advance!

    Read the article

  • Check if Django model field choices exists

    - by Justin Lucas
    I'm attempting to check if a value exists in the choices tuple set for a model field. For example lets say I have a Model like this: class Vote(models.Model): VOTE_TYPE = ( (1, "Up"), (-1, "Down"), ) value = models.SmallIntegerField(max_length=1, choices=VOTE_TYPES) Now lets say in a view I have a variable new_value = 'Up' that I would like to use as the value field in a new Vote. How can I first check to see if the value of that variable exists in the VOTE_TYPE tuple? Thank you.

    Read the article

  • Django - transactions in the model?

    - by orokusaki
    Models (disregard typos / minor syntax issues. It's just pseudo-code): class SecretModel(models.Model): some_unique_field = models.CharField(max_length=25, unique=True) # Notice this is unique. class MyModel(models.Model): secret_model = models.OneToOneField(SecretModel, editable=False) # Not in the form spam = models.CharField(max_length=15) foo = models.IntegerField() def clean(self): SecretModel.objects.create(some_unique_field=self.spam) Now if I go do this: MyModel.objects.create(spam='john', foo='OOPS') # Obviously foo won't take "OOPS" as it's an IntegerField. #.... ERROR HERE MyModel.objects.create(spam='john', foo=5) # So I try again here. #... IntegrityError because SecretModel with some_unique_field = 'john' already exists. I understand that I could put this into a view with a request transaction around it, but I want this to work in the Admin, and via an API, etc. Not just with forms, or views. How is it possible?

    Read the article

  • Inline Form Validation in Django

    - by allanhenderson
    Newbie request that seems difficult to implement. I would like to make an entire inline formset within an admin change form compulsory.. so in my current scenario when I hit save on an Invoice form (in Admin) the inline Order form is blank. I'd like to stop people creating invoices with no orders associated. Anyone know an easy way to do that? Normal validation like (required=True) on the model field doesn't appear to work in this instance. Thanks!!

    Read the article

  • Multiprogramming in Django, writing to the Database

    - by Marcus Whybrow
    Introduction I have the following code which checks to see if a similar model exists in the database, and if it does not it creates the new model: class BookProfile(): # ... def save(self, *args, **kwargs): uniqueConstraint = {'book_instance': self.book_instance, 'collection': self.collection} # Test for other objects with identical values profiles = BookProfile.objects.filter(Q(**uniqueConstraint) & ~Q(pk=self.pk)) # If none are found create the object, else fail. if len(profiles) == 0: super(BookProfile, self).save(*args, **kwargs) else: raise ValidationError('A Book Profile for that book instance in that collection already exists') I first build my constraints, then search for a model with those values which I am enforcing must be unique Q(**uniqueConstraint). In addition I ensure that if the save method is updating and not inserting, that we do not find this object when looking for other similar objects ~Q(pk=self.pk). I should mention that I ham implementing soft delete (with a modified objects manager which only shows non-deleted objects) which is why I must check for myself rather then relying on unique_together errors. Problem Right thats the introduction out of the way. My problem is that when multiple identical objects are saved in quick (or as near as simultaneous) succession, sometimes both get added even though the first being added should prevent the second. I have tested the code in the shell and it succeeds every time I run it. Thus my assumption is if say we have two objects being added Object A and Object B. Object A runs its check upon save() being called. Then the process saving Object B gets some time on the processor. Object B runs that same test, but Object A has not yet been added so Object B is added to the database. Then Object A regains control of the processor, and has allready run its test, even though identical Object B is in the database, it adds it regardless. My Thoughts The reason I fear multiprogramming could be involved is that each Object A and Object is being added through an API save view, so a request to the view is made for each save, thus not a single request with multiple sequential saves on objects. It might be the case that Apache is creating a process for each request, and thus causing the problems I think I am seeing. As you would expect, the problem only occurs sometimes, which is characteristic of multiprogramming or multiprocessing errors. If this is the case, is there a way to make the test and set parts of the save() method a critical section, so that a process switch cannot happen between the test and the set?

    Read the article

  • Joining different models in Django

    - by Andrew Roberts
    Let's say I have this data model: class Workflow(models.Model): ... class Command(models.Model): workflow = models.ForeignKey(Workflow) ... class Job(models.Model): command = models.ForeignKey(Command) ... Suppose somewhere I want to loop through all the Workflow objects, and for each workflow I want to loop through its Commands, and for each Command I want to loop through each Job. Is there a way to structure this with a single query? That is, I'd like Workflow.objects.all() to join in its dependent models, so I get a collection that has dependent objects already cached, so workflows[0].command_set.get() doesn't produce an additional query. Is this possible?

    Read the article

  • Problem bounding name to a class in Django

    - by martinthenext
    Hello! I've got a view function that has to decide which form to use depending on some conditions. The two forms look like that: class OpenExtraForm(forms.ModelForm): class Meta: model = Extra def __init__(self, *args, **kwargs): super(OpenExtraForm, self).__init__(*args, **kwargs) self.fields['opening_challenge'].label = "lame translation" def clean_opening_challenge(self): challenge = self.cleaned_data['opening_challenge'] if challenge is None: raise forms.ValidationError('??????? ???, ??????????? ?????? ???. ???????????') return challenge class HiddenExtraForm(forms.ModelForm): class Meta: model = Extra exclude = ('opening_challenge') def __init__(self, *args, **kwargs): super(HiddenExtraForm, self).__init__(*args, **kwargs) The view code goes like that: @login_required def manage_extra(request, extra_id=None, hidden=False): if not_admin(request.user): raise Http404 if extra_id is None: # Adding a new extra extra = Extra() if hidden: FormClass = HiddenExtraForm else: FormClass = OpenExtraForm else: # Editing an extra extra = get_object_or_404(Extra, pk=extra_id) if extra.is_hidden(): FromClass = HiddenExtraForm else: FormClass = OpenExtraForm if request.POST: form = FormClass(request.POST, instance=extra) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(view_extra, args=[extra.id])) else: form = FormClass(instance=extra) return render_to_response('form.html', { 'form' : form, }, context_instance=RequestContext(request) ) The problem is somehow if extra.is_hidden() returns True, the statement FromClass = HiddenExtraForm doesn't work. I mean, in all other conditions that are used in the code it works fine: the correct Form classes are intantiated and it all works. But if extra.is_hidden(), the debugger shows that the condition is passed and it goes to the next line and does nothing! As a result I get a UnboundLocalVar error which says FormClass hasn't been asssigned at all. Any ideas on what's happening?

    Read the article

  • Django Initial for a ManyToMany Field

    - by gramware
    I have a form that edits an instance of my model. I would like to use the form to pass all the values as hidden with an inital values of username defaulting to the logged in user so that it becomes a subscribe form. The problem is that the normal initial={'field':value} doesn't seem to work for manytomany fields. how do i go about it? my views.py @login_required def event_view(request,eventID): user = UserProfile.objects.get(pk=request.session['_auth_user_id']) event = events.objects.get(eventID = eventID) if request.method == 'POST': form = eventsSusbcribeForm( request.POST,instance=event) if form.is_valid(): form.save() return HttpResponseRedirect('/events/') else: form = eventsSusbcribeForm(instance=event) return render_to_response('event_view.html', {'user':user,'event':event, 'form':form},context_instance = RequestContext( request )) my forms.py class eventsSusbcribeForm(forms.ModelForm): eventposter = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput()) details = forms.CharField(widget=forms.Textarea(attrs={'cols':'50', 'rows':'5'}),label='Enter Event Description here') date = forms.DateField(widget=SelectDateWidget()) class Meta: model = events exclude = ('deleted') def __init__(self, *args, **kwargs): super(eventsSusbcribeForm, self).__init__(*args, **kwargs) self.fields['username'].initial = (user.id for user in UserProfile.objects.filter())

    Read the article

  • Django: Overriding ModelAdmin save_model not working

    - by tufelkinder
    Even after obj.save(), the obj still does not have an id, so I cannot access or manipulate the m2m records. Just keep getting a "instance needs to have a primary key value before a many-to-many relationship can be used" error. def save_model(self, request, obj, form, change): obj.save() # this doesn't work super(Table2Admin, self).save_model(request, obj, form, change) # still doesn't save for tb1 in obj.table1.all: tb1_obj = ThroughTable.objects.get(table1=bk, table2=obj) # do other stuff What am I doing wrong? Why do I need to do to save this model?

    Read the article

< Previous Page | 27 28 29 30 31 32 33 34 35 36 37 38  | Next Page >