Search Results

Search found 5330 results on 214 pages for 'django auth'.

Page 92/214 | < Previous Page | 88 89 90 91 92 93 94 95 96 97 98 99  | Next Page >

  • How to find all records that share the same field value as some other record?

    - by Gj
    I need to extract all records which have a field which does NOT have a unique value. I can't figure out an elegant way to do it - using annotation or some other way. I see a "value_annotate" method to the object manager but it's unclear if it's at all related. Currently I'm using the inelegant way of simple looping through all values and doing a get on the value, and if there's an exception it means it's not unique.. Thanks

    Read the article

  • Filtering results and pagination

    - by alj
    I have a template that shows a filter form and below it a list of the result records. I bind the form to the request so that the filter form sets itself to the options the user submitted when the results are returned. I also use pagination. Using the code in the pagination documentation means that when the user clicks for the next page, the form data is lost. What is the best way of dealing with pagination and filtering in this way? Passing the querystring to the paginiation links. Change the pagination links to form buttons and therefore submit the filter form at the same time, but this assumes that the user hasn't messed about with the filter options. As above but with the original data as hidden fields. ALJ

    Read the article

  • Is it possible to render a template from middleware?

    - by pajton
    I have a middleware that does some processing. On certain conditions it raises an exception and the user sees my 500.html template - correctly responding to 500 http status. Now, on some exceptions I would like to render different template than default 500.html. Is it possible/how to achieve that?

    Read the article

  • Is a many-to-many relationship with extra fields the right tool for my job?

    - by whichhand
    Previously had a go at asking a more specific version of this question, but had trouble articulating what my question was. On reflection that made me doubt if my chosen solution was correct for the problem, so this time I will explain the problem and ask if a) I am on the right track and b) if there is a way around my current brick wall. I am currently building a web interface to enable an existing database to be interrogated by (a small number of) users. Sticking with the analogy from the docs, I have models that look something like this: class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) dob = models.DateField() class Album(models.Model): artist = models.ForeignKey(Musician) name = models.CharField(max_length=100) class Instrument(models.Model): artist = models.ForeignKey(Musician) name = models.CharField(max_length=100) Where I have one central table (Musician) and several tables of associated data that are related by either ForeignKey or OneToOneFields. Users interact with the database by creating filtering criteria to select a subset of Musicians based on data the data on the main or related tables. Likewise, the users can then select what piece of data is used to rank results that are presented to them. The results are then viewed initially as a 2 dimensional table with a single row per Musician with selected data fields (or aggregates) in each column. To give you some idea of scale, the database has ~5,000 Musicians with around 20 fields of related data. Up to here is fine and I have a working implementation. However, it is important that I have the ability for a given user to upload there own annotation data sets (more than one) and then filter and order on these in the same way they can with the existing data. The way I had tried to do this was to add the models: class UserDataSets(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100) description = models.CharField(max_length=64) results = models.ManyToManyField(Musician, through='UserData') class UserData(models.Model): artist = models.ForeignKey(Musician) dataset = models.ForeignKey(UserDataSets) score = models.IntegerField() class Meta: unique_together = (("artist", "dataset"),) I have a simple upload mechanism enabling users to upload a data set file that consists of 1 to 1 relationship between a Musician and their "score". Within a given user dataset each artist will be unique, but different datasets are independent from each other and will often contain entries for the same musician. This worked fine for displaying the data, starting from a given artist I can do something like this: artist = Musician.objects.get(pk=1) dataset = UserDataSets.objects.get(pk=5) print artist.userdata_set.get(dataset=dataset.pk) However, this approach fell over when I came to implement the filtering and ordering of query set of musicians based on the data contained in a single user data set. For example, I could easily order the query set based on all of the data in the UserData table like this: artists = Musician.objects.all().order_by(userdata__score) But that does not help me order by the results of a given single user dataset. Likewise I need to be able to filter the query set based on the "scores" from different user data sets (eg find all musicians with a score 5 in dataset1 and < 2 in dataset2). Is there a way of doing this, or am I going about the whole thing wrong?

    Read the article

  • How to add an additional field to a queryset?

    - by Mark
    I've got a list of affiliates (users who have referred someone to the site): affiliates = User.objects.annotate(referral_count=Count('referrals')).filter(referral_count__gt=0) And a count of the number of users each affiliate has referred within a time frame: new_users = User.objects.filter(date_joined__gt=sd, date_joined__lte=ed) new_referrals = User.objects.filter(referrals__user__in=new_users).annotate(referral_count=Count('referrals')) How can I do something like new_referrals['affiliate.username'].referral_count from within my template? Note that this is not just a syntax issue, I also need to index new_referrals somehow so that I'm able to do this. Either this, or if I can somehow add a new_referral_count to the first query, that'd work too.

    Read the article

  • Template does not exist: 500.html

    - by xRobot
    I have created a template for 500 http error. I have insert my template 500.html in: 1) /project/ 2) /project/templates/ 3) /python2.5/ 4) /python2.5/templates/ . but I always get this error: TemplateDoesNotExist: 500.html Same problem for Http 404 error. WHY ???

    Read the article

  • Reading file data during form's clean method

    - by Dominic Rodger
    So, I'm working on implementing the answer to my previous question. Here's my model: class Talk(models.Model): title = models.CharField(max_length=200) mp3 = models.FileField(upload_to = u'talks/', max_length=200) Here's my form: class TalkForm(forms.ModelForm): def clean(self): super(TalkForm, self).clean() cleaned_data = self.cleaned_data if u'mp3' in self.files: from mutagen.mp3 import MP3 if hasattr(self.files['mp3'], 'temporary_file_path'): audio = MP3(self.files['mp3'].temporary_file_path()) else: # What goes here? audio = None # setting to None for now ... return cleaned_data class Meta: model = Talk Mutagen needs file-like objects - the first case (where the uploaded file is larger than the size of file handled in memory) works fine, but I don't know how to handle InMemoryUploadedFile that I get otherwise. I've tried: # TypeError (coercing to Unicode: need string or buffer, InMemoryUploadedFile found) audio = MP3(self.files['mp3']) # TypeError (coercing to Unicode: need string or buffer, cStringIO.StringO found) audio = MP3(self.files['mp3'].file) # Hangs seemingly indefinitely audio = MP3(self.files['mp3'].file.read()) Is there something wrong with mutagen, or am I doing it wrong?

    Read the article

  • Auto-arrange <li> elements into equal columns

    - by 47
    I have several values I'm rendering as elements on my template and I want to further this by having them arranged into equal (or near-equal columns) automatically in the template. How can I achieve this? So far I'm rendering all the values as <ul> {% for feature in features %} <li>{{ feature }}</li> {% endfor %} </ul>

    Read the article

  • Automark model names/attributes for translation

    - by Saosin
    Is there any way one could automatically mark all model names and attributes for translation, without specifying verbose_name/_plural on each one of them? Doesn't feel very DRY to do this every time: class Profile(models.Model): length = models.IntegerField(_('length')) weight = models.IntegerField(_('weight')) favorite_movies = models.CharField(_('favorite movies'), max_length=100) favorite_quote = models.CharField(_('favorite quote'), max_length=30) religious_views = models.CharField(_('religious views'), max_length=30) political_views = models.CharField(_('political views'), max_length=30) class Meta: verbose_name = _('profile') verbose_name_plural = _('profiles')

    Read the article

  • Loading from pickled data causes database error with new saves

    - by hibbie
    In order to save time moving data I pickled some models and dumped them to file. I then reloaded them into another database using the same exact model. The save worked fine and the objects kept their old id which is what I wanted. However, when saving new objects I run into nextval errors. Not being very adept with postgres, I'm not sure how to fix this so I can keep old records with their existing ID while being able to continue adding new data. Thanks, Thomas

    Read the article

  • How to display more things in admin.StackedInline

    - by FurtiveFelon
    Hi all, I have Article model and a Comment model. Comment is created in admin.py as admin.StackedInline, and it has several fields, notably content and lastUpdate. For lastUpdate, i have specified as follows: lastUpdate = models.DateTimeField('last update', auto_now=True). Understandably, lastUpdate is not displayed when i try to add new comment (or edit old ones). However, i would like it to display for older comments if possible, as a read only thing. Is there anyway of accomplishing that? Thanks a lot! Jason

    Read the article

  • HttpResponseRedirect question

    - by Hulk
    Cant we send a dictionary variable when using HttpResponseRedirect render_to_response('edited/display.html',context_instance=RequestContext(request,{'newlist': newlist})) //How can the dictionary and the request sent back again //sumthing like this return HttpResponseRedirect('edited/display.html',context_instance=RequestContext(request,{'newlist': newlist}))

    Read the article

  • Extending a form field to add new validations.

    - by duallain
    I've written an app that uses forms to collect information that is then sent in an email. Many of these forms have a filefield used to attach files to the email. I'd like to validate two things, the size of the file (to ensure the emails are accepted by our mail server. I'd also like to check the file extension, to discourage attaching file types not useable for our users. (This is the python class I'm trying to extend) class FileField(Field): widget = FileInput default_error_messages = { 'invalid': _(u"No file was submitted. Check the encoding type on the form."), 'missing': _(u"No file was submitted."), 'empty': _(u"The submitted file is empty."), 'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'), } def __init__(self, *args, **kwargs): self.max_length = kwargs.pop('max_length', None) super(FileField, self).__init__(*args, **kwargs) def clean(self, data, initial=None): super(FileField, self).clean(initial or data) if not self.required and data in EMPTY_VALUES: return None elif not data and initial: return initial # UploadedFile objects should have name and size attributes. try: file_name = data.name file_size = data.size except AttributeError: raise ValidationError(self.error_messages['invalid']) if self.max_length is not None and len(file_name) > self.max_length: error_values = {'max': self.max_length, 'length': len(file_name)} raise ValidationError(self.error_messages['max_length'] % error_values) if not file_name: raise ValidationError(self.error_messages['invalid']) if not file_size: raise ValidationError(self.error_messages['empty']) return data

    Read the article

  • Get value of selected field from a dropdown list

    - by 47
    I have this class in my model: class ServiceCharge(models.Model): name = models.CharField(max_length=30) amount = models.PositiveIntegerField() extends_membership = models.BooleanField(default=False) def __unicode__(self): return str(self.name) What I want to have is in the form for charging users a service charge, when a charge is selected from the dropdown menu, the two values for amount and extends_membership are updated on the form depending on the selected charge. My forms.py: class vModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return "%s" % obj.name class PayServiceChargeForm(PaymentsForm): service_charge = vModelChoiceField(queryset=ServiceCharge.objects.all(), empty_label=" ") class Meta(PaymentsForm.Meta): exclude = ('member', 'payment_type', 'transacted_by', 'description') Then the form template: <table border="0"> <tr> <td><strong>{% trans "Service Charge" %}</strong></td> <td>{{ form.service_charge }}</td> <td><strong>{% trans "Extends Membership" %}</strong></td> <td>{{ form.extends_membership }}</td> </tr> <tr> <td valign="top"><strong>{% trans "Expiry Date" %}</strong></td> <td valign="top">{{ form.expiry_date }}</td> <td valign="top"><strong>{% trans "Amount" %}</strong></td> <td>{{ form.amount }}</td> </tr> </table> I was trying out some jQuery but I got stuck after getting the currently selected charge: <script type="text/javascript"> $(document).ready(function(){ $("#id_service_charge").change(onSelectChange); }); function onSelectChange(){ var selected = $("#id_service_charge option:selected"); var output = ""; if(selected.val() != 0){ charge = selected.val(); .... (update values) .... } } </script>

    Read the article

  • passing an argument to a custom save() method

    - by Nick
    How do I pass an argument to my custom save method, preserving proper *args, **kwargs for passing to te super method? I was trying something like: form.save(my_value) and def save(self, my_value=None, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) print my_value But this doesn't seem to work. What am I doing wrong?

    Read the article

  • Post and Comment with the same Model.

    - by xRobot
    I have created a simple project where everyone can create one or more Blog. I want to use this models for Post and for Comment: class Post_comment(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(_('object ID')) content_object = generic.GenericForeignKey() # Hierarchy Field parent = models.ForeignKey('self', null=True, blank=True, default=None, related_name='children') # User Field user = models.ForeignKey(User) # Date Fields date_submitted = models.DateTimeField(_('date/time submitted'), default = datetime.now) date_modified = models.DateTimeField(_('date/time modified'), default = datetime.now) title = models.CharField(_('title'), max_length=60, blank=True, null=True) post_comment = models.TextField(_('post_comment')) markup = models.IntegerField(choices=MARKUP_CHOICES, default=DEFAULT_MARKUP, null=True, blank=True) if it is a comment the parent is not null. So in most case the text field will contain a little bit of text. Can I use this model for both Post and Comment ?

    Read the article

  • How to design model for multi-tiered data?

    - by Chris
    Say I have three types of object: Area, Subarea and Topic. I want to be able to display an Area, which is just a list of Subareas and the Topics contained in those Subareas. I never want to be able to display Subareas separately - they're just for breaking up the Topics. Topics can, however, appear in multiple Areas (but probably under the same Subarea). How would I design a model for this? I could use ForeignKey from Topic to Subarea and from Subarea to Area, but it seems unnecessarily complex given that I never want to interact with subareas themselves. Also, none of these objects are ever altered or added to by the user. They're just for me to represent information. Maybe there is a better way to represent it all?

    Read the article

  • ManyToManyField error when having recursive structure. How to solve it?

    - by luc
    Hello, I have the following table in the model with a recursive structure (a page can have children pages) class DynamicPage(models.Model): name = models.CharField("Titre",max_length=200) parent = models.ForeignKey('self',null=True,blank=True) I want to create another table with manytomany relation with this one: class UserMessage(models.Model): name = models.CharField("Nom", max_length=100) page = models.ManyToManyField(DynamicPage) The generated SQL creates the following constraint: ALTER TABLE `website_dynamicpage` ADD CONSTRAINT `parent_id_refs_id_29c58e1b` FOREIGN KEY (`parent_id`) REFERENCES `website_dynamicpage` (`id`); I would like to have the ManyToMany with the page itself (the id) and not with the parent field. How to modify the model to make the constraint using the id and not the parent? Thanks in advance

    Read the article

  • URL redirection if wrong url

    - by xRobot
    I have this method in my book model: def get_absolute_url(self): return "/book/%s/%s/%i/%i/" % ( self.book_title, self.book_editor, self.book_pages, self.id) So the urls of each book are like this: example.com/book/the-bible/gesu-crist/938/12/ I want that if there is an error in the url, then I get redirected to the real url by using book.id in the end of the url. For example if I go to: example.com/book/A-bible/gesu-crist/938/12/ the I will get redirected to: example.com/book/the-bible/gesu-crist/938/12/ How can I do that ?

    Read the article

  • How to set title and class in the HTML for the options of a ModelChoiceField?

    - by celopes
    I have a model class MyModel(models.Model): name = models.CharField(max_length=80, unique=True) parent = models.ForeignKey('self', null=True, blank=True) I want to render a ModelChoiceField for that model that looks like: <select name="mymodel" id="id_mymodel"> <option value="1" title="Value 1" class="">Value 1</option> <option value="2" title="Value 2" class="Value 1">Value 2</option> </select> The differences between this output and the default output for a ModelChoiceField are the title and class elements in the OPTION tag. They don't exist in ModelChoiceField's default output. For my purposes: The title element is supposed to be the Option Name. The class element is supposed to be self.parent.name. (this is my problem) So, in the HTML snippet above, Value 1 has no parent and Value 2 has a parent of Value 1. What is the best mechanism to change ModelChoiceField's default HTML output? EDIT: I understand how to create a new Widget for rendering HTML. The problem is how to render a value from the underlying model in each of the options.

    Read the article

  • How to save links in TextFields

    - by xRobot
    I have a simple Blog model with a TextField. What is the best way to save links in the TextField ? 1) Saving link in the database in this form: http://www.example.com and then using some filter in the template to trasform it in form: <a rel="nofollow" href="http://www.example.com>http://www.example.com</a> 2) Saving link in the database directly in this form: <a rel="nofollow" href="http://www.example.com>http://www.example.com</a>

    Read the article

  • Best Practice for Context Processors vs. Template Tags?

    - by mawimawi
    In which cases is it better to create template tags (and load them into the template), than creating a context processor (which fills the request automatically)? e.g. I have a dynamic menu that has to be included into all templates, so I'm putting it into my base.html. What is the preferred usage: context processor or custom template tag? And why?

    Read the article

< Previous Page | 88 89 90 91 92 93 94 95 96 97 98 99  | Next Page >