Search Results

Search found 8161 results on 327 pages for 'django queries'.

Page 11/327 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Display/Edit fields across tables in a Django Form

    - by jamida
    I have 2 tables/models, which for all practical purposes are the same as the standard Author/Book example, but with the additional restriction that in my application each Author can only write 0 or 1 books. (eg, the ForeignKey field in the Book model is or can be a OneToOneField, and there may be authors who have no corresponding book in the Book table.) I would like to be able to display a form showing multiple books and also show some fields from the corresponding Author table (eg author_name, author_address). I followed the example of the inlineformset and but that doesn't even display the author name in the generated form.

    Read the article

  • Django, want to upload eather image (ImageField) or file (FileField)

    - by Serg
    I have a form in my html page, that prompts user to upload File or Image to the server. I want to be able to upload ether file or image. Let's say if user choose file, image should be null, and vice verso. Right now I can only upload both of them, without error. But If I choose to upload only one of them (let's say I choose image) I will get an error: "Key 'attachment' not found in <MultiValueDict: {u'image': [<InMemoryUploadedFile: police.jpg (image/jpeg)>]}>" models.py: #Description of the file class FileDescription(models.Model): TYPE_CHOICES = ( ('homework', 'Homework'), ('class', 'Class Papers'), ('random', 'Random Papers') ) subject = models.ForeignKey('Subjects', null=True, blank=True) subject_name = models.CharField(max_length=100, unique=False) category = models.CharField(max_length=100, unique=False, blank=True, null=True) file_type = models.CharField(max_length=100, choices=TYPE_CHOICES, unique=False) file_uploaded_by = models.CharField(max_length=100, unique=False) file_name = models.CharField(max_length=100, unique=False) file_description = models.TextField(unique=False, blank=True, null=True) file_creation_time = models.DateTimeField(editable=False) file_modified_time = models.DateTimeField() attachment = models.FileField(upload_to='files', blank=True, null=True, max_length=255) image = models.ImageField(upload_to='files', blank=True, null=True, max_length=255) def __unicode__(self): return u'%s' % (self.file_name) def get_fields(self): return [(field, field.value_to_string(self)) for field in FileDescription._meta.fields] def filename(self): return os.path.basename(self.image.name) def category_update(self): category = self.file_name return category def save(self, *args, **kwargs): if self.category is None: self.category = FileDescription.category_update(self) for field in self._meta.fields: if field.name == 'image' or field.name == 'attachment': field.upload_to = 'files/%s/%s/' % (self.file_uploaded_by, self.file_type) if not self.id: self.file_creation_time = datetime.now() self.file_modified_time = datetime.now() super(FileDescription, self).save(*args, **kwargs) forms.py class ContentForm(forms.ModelForm): file_name =forms.CharField(max_length=255, widget=forms.TextInput(attrs={'size':20})) file_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':25})) class Meta: model = FileDescription exclude = ('subject', 'subject_name', 'file_uploaded_by', 'file_creation_time', 'file_modified_time', 'vote') def clean_file_name(self): name = self.cleaned_data['file_name'] # check the length of the file name if len(name) < 2: raise forms.ValidationError('File name is too short') # check if file with same name is already exists if FileDescription.objects.filter(file_name = name).exists(): raise forms.ValidationError('File with this name already exists') else: return name views.py if request.method == "POST": if "upload-b" in request.POST: form = ContentForm(request.POST, request.FILES, instance=subject_id) if form.is_valid(): # need to add some clean functions # handle_uploaded_file(request.FILES['attachment'], # request.user.username, # request.POST['file_type']) form.save() up_f = FileDescription.objects.get_or_create( subject=subject_id, subject_name=subject_name, category = request.POST['category'], file_type=request.POST['file_type'], file_uploaded_by = username, file_name=form.cleaned_data['file_name'], file_description=request.POST['file_description'], image = request.FILES['image'], attachment = request.FILES['attachment'], ) return HttpResponseRedirect(".")

    Read the article

  • Django aggregation query on related one-to-many objects

    - by parxier
    Here is my simplified model: class Item(models.Model): pass class TrackingPoint(models.Model): item = models.ForeignKey(Item) created = models.DateField() data = models.IntegerField() In many parts of my application I need to retrieve a set of Item's and annotate each item with data field from latest TrackingPoint from each item ordered by created field. For example, instance i1 of class Item has 3 TrackingPoint's: tp1 = TrackingPoint(item=i1, created=date(2010,5,15), data=23) tp2 = TrackingPoint(item=i1, created=date(2010,5,14), data=21) tp3 = TrackingPoint(item=i1, created=date(2010,5,12), data=120) I need a query to retrieve i1 instance annotated with tp1.data field value as tp1 is the latest tracking point ordered by created field. That query should also return Item's that don't have any TrackingPoint's at all. If possible I prefer not to use QuerySet's extra method to do this. That's what I tried so far... and failed :( Item.objects.annotate(max_created=Max('trackingpoint__created'), data=Avg('trackingpoint__data')).filter(trackingpoint__created=F('max_created')) Any ideas?

    Read the article

  • Accessing django choice field

    - by Hulk
    there is a module as header , from test.models import SEL_VALUES class rubrics_header(models.Model): sel_values = models.IntegerField(choices=SEL_VALUES) So when SEL_VALUES is imported from test.modules.What is the code that has to go in views to get the choices in sel_values . And the test.modules has the following, class SEL_VALUES: vaue = 0 value2 = 1 class Entries(forms.Form) : models.IntegerField(choices=SEL_VALUES) SEL_VALUES = ((ACCESS.value,'NAME'),(ACCESS.value2,'DESIGNATION'))

    Read the article

  • Django RadioButtons with icons and not label?

    - by Asinox
    Hi guy's , i have an app that have 2 fields: company_name and logo, i'm displaying the companies like radiobutton in my Form from Model, but i want to show the logo company instead of the company label (company name) Any idea ? My forms: class RecargaForm(ModelForm): compania = forms.ModelChoiceField(queryset=Compania.objects.all(), initial=0 ,empty_label='None', widget=forms.RadioSelect()) class Meta: model = Recarga Thanks :)

    Read the article

  • django forms in diferent contexts

    - by z3a
    I'm in a middle of a problem, I have a url like /account/login that displays a login form. I need to include this form in another template that have a different url. I tried to use {%include%} but this don't work, the form is not shown. Any one have a clue about this??

    Read the article

  • Django unable to update model

    - by user292652
    i have the following function to override the default save function in a model match def save(self, *args, **kwargs): if self.Match_Status == "F": Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1) Team.objects.filter(pk=self.Team_two.id).update(Played=F('Played')+1) if self.Winner !="": Team.objects.filter(pk=self.Winner.id).update(Win=F('Win')+1, Points=F('Points')+3) else: return if self.Match_Status == "D": Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1) Team.objects.filter(pk=self.Team_two.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1) super(Match, self).save(*args, **kwargs) I am able to save the match model just fine but Team model does not seem to be updating at all and no error is being thrown. am i missing some thing here ?

    Read the article

  • django models objects filter

    - by ha22109
    Hello All, I have a model 'Test' ,in which i have 2 foreignkey models.py class Test(models.Model): id =models.Autofield(primary_key=True) name=models.ForeignKey(model2) login=models.ForeignKey(model1) status=models.CharField(max_length=200) class model1(models.Model): id=models.CharField(primary_key=True) . . is_active=models.IntergerField() class model2(model.Model): id=models.ForeignKey(model1) . . status=model.CharField(max_length=200) When i add object in model 'Test' , if i select certain login then only the objects related to that objects(model2) should be shown in field 'name'.How can i achieve this.THis will be runtime as if i change the login field value the objects in name should also change.

    Read the article

  • How to display total record count against models in django admin

    - by Rog
    Is there a neat way to make the record/object count for a model appear on the main model list in the admin module? I have found techniques for showing counts of related objects within sets in the list_display page (and I can see the total in the pagination section at the bottom of the same), but haven't come across a neat way to show the record count at the model list level.

    Read the article

  • Modify on-the-fly verbose_name in a model field on django admin

    - by PerroVerd
    Hi I have this sample model working with the admin class Author(models.Model): name = models.CharField(_('Text in here'), max_length=100) with verbose_name set as ugettext_lazy 'Text in here', but sometimes, depending on the site_id i want to present a diferent verbose name, so I modified the init in this way def __init__(self, *args, **kwargs): super(Author, self).__init__(*args, **kwargs) #some logic in here self._meta.get_field('name').verbose_name = _('Other text') It works, displaying the 'Other text' instead the 'Text in here'... except for the very first time the author/add view is used. ¿Is it the right way to do it? ¿How can i fix the first time problem? Thanks in advance

    Read the article

  • Django: How to set default language in admin on login

    - by lazerscience
    I'm saving an user's default language in his user profile and on login I want to set the admin's default language to it. One possibility I was thinking of is using a middleware, but I think if I do it on process_request I will not see an user object there since this is processed AFTER the middleware, so I could only set it after the next request! Any solutions are highly appreciated!

    Read the article

  • Django Forms - change the render multiple select widget

    - by John
    Hi, In my model I have a manytomany field mentors = models.ManyToManyField(MentorArea, verbose_name='Areas', blank=True) In my form I want to render this as: drop down box with list of all MentorArea objects which has not been associated with the object. Next to that an add button which will call a javascript function which will add it to the object. Then under that a ul list which has each selected MentorArea object with a x next to it which again calls a javascript function which will remove the MentorArea from the object. I know that to change how an field element is rendered you create a custom widget and override the render function and I have done that to create the add button. class AreaWidget(widgets.Select): def render(self, name, value, attrs=None, choices=()): jquery = u''' <input class="button def" type="button" value="Add" id="Add Area" />''' output = super(AreaWidget, self).render(name, value, attrs, choices) return output + mark_safe(jquery) However I don't know how to list the currently selected ones underneath as a list. Can anyone help me? Also what is the best way to filter down the list so that it only shows MentorArea objects which have not been added? I currently have the field as mentors = forms.ModelMultipleChoiceField(queryset=MentorArea.objects.all(), widget = AreaWidget, required=False) but this shows all mentors no matter if they have been added or not. Thanks

    Read the article

  • Django access data passed to form

    - by realshadow
    Hey, I have got a choiceField in my form, where I display filtered data. To filter the data I need two arguments. The first one is not a problem, because I can take it directly from an object, but the second one is dynamically generated. Here is some code: class GroupAdd(forms.Form): def __init__(self, *args, **kwargs): self.pid = kwargs.pop('parent_id', None) super(GroupAdd, self).__init__(*args, **kwargs) parent_id = forms.IntegerField(widget=forms.HiddenInput) choices = forms.ChoiceField( choices = [ [group.node_id, group.name] for group in Objtree.objects.filter( type_id = ObjtreeTypes.objects.values_list('type_id').filter(name = 'group'), parent_id = 50 ).distinct()] + [[0, 'Add a new one'] ], widget = forms.Select( attrs = { 'id': 'group_select' } ) ) I would like to change the parent_id that is passed into the Objtree.objects.filter. As you can see I tried in the init function, as well with kwargs['initial']['parent_id'] and then calling it with self, but that doesnt work, since its out of scope... it was pretty much my last effort. I need to acccess it either trough the initial parameter or directly trough parent_id field, since it already holds its value (passed trough initial). Any help is appreciated, as I am running out of ideas.

    Read the article

  • Django - Specifying default attr for Custom widget

    - by Pierre de LESPINAY
    I have created this widget class DateTimeWidget(forms.TextInput): attr = {'class': 'datetimepicker'} class Media: js = ('js/jquery-ui-timepicker-addon.js',) Then I use it on my form class SessionForm(forms.ModelForm): class Meta: model = Session def __init__(self, *args, **kwargs): super(SessionForm, self).__init__(*args, **kwargs) self.fields['start_time'].widget = DateTimeWidget() self.fields['end_time'].widget = DateTimeWidget() No css class is applied to my fields (I'm expecting datetimepicker applied to both start_time & end_time). I imagine I have put attr at a wrong location. Where am I supposed to specify it ?

    Read the article

  • Manually listing objects in Django (problem with field ordering)

    - by Chris
    I'm having some trouble figuring out the best/Djangoic way to do this. I'm creating something like an interactive textbook. It has modules, which are more or less like chapters. Each module page needs to list the topics in that module, grouped into sections. My question is how I can ensure that they list in the correct order in the template? Specifically: 1) How to ensure the sections appear in the correct order? 2) How to ensure the topics appear in the correct order in the section? I imagine I could add a field to each model purely for the sake of ordering, but the problem with that is that a topic might appear in different modules, and in whatever section they are in there they would again have to be ordered somehow. I would probably give up and do it all manually were it not for the fact that I need to have the Topic as object in the template (or view) so I can mark it up according to how the user has labeled it. So I suppose my question is really to do with whether I should create the contents pages manually, or whether there is a way of ordering the query results in a way I haven't thought of. Thanks for your help!

    Read the article

  • Custom Sorting on Custom Field in Django

    - by RotaJota
    In my app, I have defined a custom field to represent a physical quantity using the quantities package. class AmountField(models.CharField): def __init__(self, *args, **kwargs): ... def to_python(self, value): create_quantities_value(value) Essentially the way it works is it extends CharField to store the value as a string in the database "12 min" and represents it as a quantities object when using the field in a model array(12) * min Then in a model it is used as such: class MyModel(models.Model): group = models.CharField() amount = AmountField() class Meta: ordering = ['group', 'amount'] My issue is that these fields do not seem to sort by the quantity, but instead by the string. So if I have some objects that contain something like {"group":"A", "amount":"12 min"} {"group":"A", "amount":"20 min"} {"group":"A", "amount":"2 min"} {"group":"B", "amount":"20 min"} {"group":"B", "amount":"1 hr"} they end up sorted something like this: >>> MyModel.objects.all() [{A, 12 min}, {A, 2 min}, {A, 20 min}, {B, 1 hr}, {B, 20 min}] essentially alphabetical order. Can I give my custom AmountField a comparison function so that it will compare by the python value instead of the DB value?

    Read the article

  • Django: customizing the message after a successful form save

    - by chiurox
    Hello, whenever I save a model in my Admin interface, it displays the usual "successfully saved message." However, I want to know if it's possible to customize this message because I have a situation where I want to warn the user about what he just saved and the implications of these actions. class PlanInlineFormset(forms.models.BaseInlineFormset): def clean(self): ### How can I detect the changes? ### (self.changed_data doesn't work because it's an inline) ### and display what he/she just changed at the top AFTER the successful save? class PlanInline(admin.TabularInline): model = Plan formset = PlanInlineFormset

    Read the article

  • Django - markup parser in template or view?

    - by Amit Ron
    I am building a website where my pages are written in MediaWiki Markup, for which I have a working parser function in Python. Where exactly do I parse my markup: in the view's code, or in the template? My first guess would be something like: return render_to_response( 'blog/post.html', {'post': post, 'content': parseMyMarkup(post.content) }) Is this the usual convention, or should I do something different?

    Read the article

  • django admin app error (Model with property field): global name 'full_name' is not defined

    - by rxin
    This is my model: class Author(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200, blank=True) def __unicode__(self): return full_name def _get_full_name(self): "Returns the person's full name." if self.middle_name == '': return "%s %s" % (self.first_name, self.last_name) else: return "%s %s %s" % (self.first_name, self.middle_name, self.last_name) full_name = property(_get_full_name) Everything is fine except when I go into admin interface, I see TemplateSyntaxError at /bibbase2/admin/bibbase2/author/ Caught an exception while rendering: global name 'full_name' is not defined It seems like the built-in admin app doesn't work with a property field. Is there something wrong with my code?

    Read the article

  • Django model manager didn't work with related object when I do aggregated query

    - by Satoru.Logic
    Hi, all. I'm having trouble doing an aggregation query on a many-to-many related field. Let's begin with my models: class SortedTagManager(models.Manager): use_for_related_fields = True def get_query_set(self): orig_query_set = super(SortedTagManager, self).get_query_set() # FIXME `used` is wrongly counted return orig_query_set.distinct().annotate( used=models.Count('users')).order_by('-used') class Tag(models.Model): content = models.CharField(max_length=32, unique=True) creator = models.ForeignKey(User, related_name='tags_i_created') users = models.ManyToManyField(User, through='TaggedNote', related_name='tags_i_used') objects_sorted_by_used = SortedTagManager() class TaggedNote(models.Model): """Association table of both (Tag , Note) and (Tag, User)""" note = models.ForeignKey(Note) # Note is what's tagged in my app tag = models.ForeignKey(Tag) tagged_by = models.ForeignKey(User) class Meta: unique_together = (('note', 'tag'),) However, the value of the aggregated field used is only correct when the model is queried directly: for t in Tag.objects.all(): print t.used # this works correctly for t in user.tags_i_used.all(): print t.used #prints n^2 when it should give n Would you please tell me what's wrong with it? Thanks in advance.

    Read the article

  • Django templates tag error

    - by Hulk
    def _table_(request,id,has_permissions): dict = {} dict.update(get_newdata(request,rid)) return render_to_response('home/_display.html',context_instance=RequestContext(request,{'dict': dict, 'rid' : rid, 'has_permissions' : str(has_permissions)})) In templates the code is as, {% if has_permissions == "1" %} <input type="button" value="Edit" id="edit" onclick="javascript:edit('{{id}}')" style="display:inline;"/>&nbsp;&nbsp;&nbsp;&nbsp; {% endif %} There is a template error in has_permissions line. Can any 1 tell me what is wrong here. has_permissions has the value 1 or 0.

    Read the article

  • django generic view update/create: update works but create raises IntegrityError

    - by smarber
    I'm using CreateView and UpdateView directely into urls.py of my application whose name is dydict. In the file forms.py I'm using ModelForm and I'm exluding a couple of fields from being shown, some of which sould be set when either creating or updating. So, as mentioned in the title, update part works but create part doesn't which is obvious because required fields that I have exluded are sent empty which is not allowed in my case. So the question here is, how should I do to fill exluded fields into the file forms.py so that I don't have to override CreateView? Thanks in advance.

    Read the article

  • querying for timestamp field in django

    - by Hulk
    In my views i have the date in the following format s_date=20090106 and e_date=20100106 The model is defined as class Activity(models.Model): timestamp = models.DateTimeField(auto_now_add=True) how to query for the timestamp filed with the above info. Activity.objects.filter(timestamp>=s_date and timestamp<=e_date) Thanks.....

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >