Search Results

Search found 6723 results on 269 pages for 'django models'.

Page 16/269 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Dropdown sorting in django-admin

    - by Andrey
    I'd like to know how can I sort values in the Django admin dropdowns. For example, I have a model called Article with a foreign key pointing to the Users model, smth like: class Article(models.Model): title = models.CharField(_('Title'), max_length=200) slug = models.SlugField(_('Slug'), unique_for_date='publish') author = models.ForeignKey(User) body = models.TextField(_('Body')) status = models.IntegerField(_('Status')) categories = models.ManyToManyField(Category, blank=True) publish = models.DateTimeField(_('Publish date')) I edit this model in django admin: class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'publish', 'status') list_filter = ('publish', 'categories', 'status') search_fields = ('title', 'body') prepopulated_fields = {'slug': ('title',)} admin.site.register(Article, ArticleAdmin) and of course it makes the nice user select dropdown for me, but it's not sorted and it takes a lot of time to find a user by username.

    Read the article

  • Query multiple models with one value

    - by swoei
    I have multiple models which all have a FK to the same model. All I know is the FK how can I determine which of the models has the FK attached? Below an example to clearify: class ModelA(models.Model): title = models.CharField("title", max_length=80) class ModelB(models.Model): fk = models.ForeignKey(ModelA) class ModelC(models.Model): fk = models.ForeignKey(ModelA) How can I figure out without using a try/except on each model whether B or C has the FK? (The FK can only be in one of them, for the record in this case I only added two models but in the real world app there are multiple possible x amount of models which have the FK to modelA)

    Read the article

  • Django display manytomany field in form when definition is on other model

    - by John
    Hi I have the definition for my manytomany relationship on one model but want to display the field on the form of my other model. How do I do this? for example: # classes class modelA(models.Model): name = models.CharField(max_length=300) manytomany = models.ManyToManyField(modelA) class modelB(models.Model): name = models.CharField(max_length=300) # forms class modelBForm(forms.ModelForm): class Meta: model = modelB If I then used modelBForm it would show a select box with the models from modelA rather than just name. Thanks

    Read the article

  • Doing a count over a filter query efficiently in django

    - by apple_pie
    Hello, Django newbie here, I need to do a count over a certain filter in a django model. If I do it like so: my_model.objects.filter(...).count() I'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count. To my knowledge it's much more efficient to do the count without retrieving those rows like so "SELECT COUNT(*) FROM ...". Is there a way to do so in django?

    Read the article

  • unittest import error with virtualenv + google-app-engine-django

    - by Ray Yun
    I'm working with google-app-engine-django + zipped django. Just running "python manage.py test" succeeded without error. But with virtualenv, test was failed with "import unittest error". same error with Django 1.1. - OSX 10.5.6 - google-app-engine-django (r101 via svn) : r100 was failed with launcher 1.3.0 - GoogleAppLauncher 1.3.0 - Django 1.1 & 1.1.1 (zipped) : both failed - virtualenv 1.4.5 - virtualenvwrapper 1.24 Error Message: (django_appengine)Reiot:warclouds Reiot$ python manage.py test WARNING:root:Could not read datastore data from /var/folders/UZ/UZ1vQeLFH2ShHk4kIiLcFk+++TI/-Tmp-/django_google-app-engine-django.datastore INFO:root:zipimporter('/Volumes/data/Documents/warclouds/django.zip', 'django/core/serializers/') .WARNING:root:Can't open zipfile /Users/Reiot/.virtualenvs/django_appengine/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg: IOError: [Errno 13] file not accessible: '/Users/Reiot/.virtualenvs/django_appengine/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg' WARNING:root:Can't open zipfile /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg: IOError: [Errno 13] file not accessible: '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg' ERROR:root:Exception encountered handling request Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3177, in _HandleRequest self._Dispatch(dispatcher, self.rfile, outfile, env_dict) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3120, in _Dispatch base_env_dict=env_dict) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 515, in Dispatch base_env_dict=base_env_dict) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2379, in Dispatch self._module_dict) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2289, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2185, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/Volumes/data/Documents/warclouds/main.py", line 28, in <module> from appengine_django import InstallAppengineHelperForDjango File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1264, in Decorate return func(self, *args, **kwargs) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1914, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1264, in Decorate return func(self, *args, **kwargs) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1816, in FindAndLoadModule description) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1264, in Decorate return func(self, *args, **kwargs) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1767, in LoadModuleRestricted description) File "/Volumes/data/Documents/warclouds/appengine_django/__init__.py", line 44, in <module> import unittest ImportError: No module named unittest INFO:root:"GET / HTTP/1.1" 500 - INFO:root:zipimporter('/Users/Reiot/.virtualenvs/django_appengine/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '') INFO:root:zipimporter('/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg', '') F........................................................... ====================================================================== FAIL: a request to the default page works in the dev_appserver ---------------------------------------------------------------------- Traceback (most recent call last): File "/Volumes/data/Documents/warclouds/appengine_django/tests/integration_test.py", line 176, in testBasic self.assertEquals(rv.status_code, 200) AssertionError: 500 != 200 I also tried with console import but it was ok. > which python /Users/Reiot/.virtualenvs/django_appengine/bin/python > python >>> import unittest Here is my environments: $ mkvirtualenv --no-site-packages no-django $ mkvirtualenv --no-site-packages django-1.1 $ mkvirtualenv --no-site-packages django-1.1.1 (django-1.1)$ easy_install Django-1.1.tar (django-1.1.1)$ easy_install Django-1.1.1.tar $ mkdir google-app-engine-django-svn $ cp -r google-app-engine-django-svn google-app-engine-django-svn-django-1.1 // copy appropriate django.zip $ cp -r google-app-engine-django-svn google-app-engine-django-svn-django-1.1.1 // copy appropriate django.zip

    Read the article

  • Django: How can I add weight/ordering to a many to many relationship?

    - by Klaas van Schelven
    I'm having Pages with TextBlocks on them. Text Blocks may appear on different pages, pages may have several text blocks on them. Every page may have these blocks in an ordering of it's own. This can be solved by using a separate through parameter. Like so: class TextBlock(models.Model): title = models.CharField(max_length=255) text = models.TextField() class Page(models.Model): textblocks = models.ManyToManyField(TextBlock, through=OrderedTextBlock) class OrderedTextBlock(models.Model): text_block = models.ForeignKey(TextBlock) product_page = models.ForeignKey(ProductPage) weight = models.IntegerField() class Meta: ordering = ('weight',) But I'm not very enthousiastic about the violations of DRY for my app. (There's a lot of ordered ManyToMany relations). Is there a recommended way to go about this?

    Read the article

  • Overwrite clean method in Django Custom Forms

    - by John
    Hi I have wrote a custom widget class AutoCompleteWidget(widgets.TextInput): """ widget to show an autocomplete box which returns a list on nodes available to be tagged """ def render(self, name, value, attrs=None): final_attrs = self.build_attrs(attrs, name=name) if not self.attrs.has_key('id'): final_attrs['id'] = 'id_%s' % name if not value: value = '[]' jquery = u""" <script type="text/javascript"> $("#%s").tokenInput('%s', { hintText: "Enter the word", noResultsText: "No results", prePopulate: %s, searchingText: "Searching..." }); $("body").focus(); </script> """ % (final_attrs['id'], reverse('ajax_autocomplete'), value) output = super(AutoTagWidget, self).render(name, "", attrs) return output + mark_safe(jquery) class MyForm(forms.Form): AutoComplete = forms.CharField(widget=AutoCompleteWidget) this widget uses a jquery function which autocompletes a word based on entries from the database. You can preset its initial values by setting prePopulate to a json string in the form ['name': 'some name', 'id': 'some id'] I do this by setting the inital value of the form field to this json string jquery_string = ['name': 'some name', 'id': 'some id'] form = MyForm(initial={'AutoComplete':jquery_string}) When submitting the form the the value of AutoComplete is returned as a comma seperated list of the selected ids e.g. 12,45,43,66 which if what I want. However if there is an error in the form, for example a required field has not been entered the value of the AutoComplete field is now 12,45,43,66 and not the json string which it requires. What is the best way to solve this. I was thinking about overwriting the clean method in the form class but I'm not sure how to find out if any other element has returned an error. e.g. if forms.errors form.cleaned_date['autocomplete'] = json string return form.cleaned_data Thanks

    Read the article

  • django admin: Add a "remove file" field for Image- or FileFields

    - by w-
    I was hunting around the net for a way to easily allow users to blank out imagefield/filefields they have set in the admin. I found this http://www.djangosnippets.org/snippets/894/ What was really interesting to me here was the code posted in the comment by rfugger remove_the_file = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_the_file'): object.the_file = '' return object When i try to use this in my own form I basically added this to my admin.py which already had a BlahAdmin class BlahModelForm(forms.ModelForm): class Meta: model = Blah remove_img01 = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_img01'): object.img01 = '' return object when i run it I get this error maximum recursion depth exceeded while calling a Python object at this line object = super(self.__class__, self).save(*args, **kwargs) When i think about it for a bit, it seems obvious that it is just infinitely calling itself causing the error. My problem is i can't figure out what is the correct way i should be doing this. Any suggestions? thanks

    Read the article

  • int() error in django views

    - by Hulk
    def displaydata(request): response_dict = {} offset = int(request.GET.get('iDisplayStart')) There is an error as, int() argument must be a string or a number at the above said line (i.e,`request.GET.get('iDisplayStart')) And in the template code, $(document).ready(function() { $.ajaxSetup({ cache: false }); oTable = $('#qp_table').dataTable( { "aoColumns": [ {"sWidth": "5%" }, {"sWidth": "35%" }, {"sWidth": "27%" }, {"sWidth": "15%"}, { "bSortable": false, "sWidth": "0%"}, {"bSortable": false, "sWidth": "0%"} ], "aaSorting": [[0, 'asc']], "bProcessing": true, "bServerSide": true, "sAjaxSource": "/diaplaydata/", "bJQueryUI": true, "sPaginationType": "full_numbers", "bFilter": false, "oLanguage" : { "sZeroRecords": "No data found", "sProcessing" : "Fetching Data" } });

    Read the article

  • django templates array assignment

    - by Hulk
    The following is in views: rows=query.evaluation_set.all() row_arr = [] for row in rows: row_arr.append(row.row_details) dict.update({'row_arr' : row_arr ,'col_arr' : col_arr}) return render_to_response('valuemart/show.html',context_instance=RequestContext(request,{'dict': dict})) How to extract the row_Arr array in the templates in javascript and list out all its values.row_Arr contains data of a column <script> var row_arr = '{{dict.row_arr}}'; //extract values here </script> Thanks..

    Read the article

  • Django Formset management-form validation error

    - by gramware
    I have a form and a formset on my template. The problem is that the formset is throwing validation error claiming that the management form is "missing or has been tampered with". Here is my view @login_required def home(request): user = UserProfile.objects.get(pk=request.session['_auth_user_id']) blogz = list(blog.objects.filter(deleted='0')) delblog = modelformset_factory(blog, exclude=('poster','date' ,'title','content')) if request.user.is_staff== True: staff = 1 else: staff = 0 staffis = 1 if request.method == 'POST': delblogformset = delblog(request.POST) if delblogformset.is_valid(): delblogformset.save() return HttpResponseRedirect('/home') else: delblogformset = delblog(queryset=blog.objects.filter( deleted='0')) blogform = BlogForm(request.POST) if blogform.is_valid(): blogform.save() return HttpResponseRedirect('/home') else: blogform = BlogForm(initial = {'poster':user.id}) blogs= zip(blogz,delblogformset.forms) paginator = Paginator(blogs, 10) # Show 25 contacts per page # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: blogs = paginator.page(page) except (EmptyPage, InvalidPage): blogs = paginator.page(paginator.num_pages) return render_to_response('home.html', {'user':user, 'blogform':blogform, 'staff': staff, 'staffis': staffis, 'blog':blogs, 'delblog':delblogformset}, context_instance = RequestContext( request )) my template {%block content%} <h2>Home</h2> {% ifequal staff staffis %} {% if form.errors %} <ul> {% for field in form %} <H3 class="title"> <p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p> </H3> {% endfor %} </ul> {% endif %} <h3>Post a Blog to the Front Page</h3> <form method="post" id="form2" action="" class="infotabs accfrm"> {{ blogform.as_p }} <input type="submit" value="Submit" /> </form> <br> <br> {% endifequal %} <div class="pagination"> <span class="step-links"> {% if blog.has_previous %} <a href="?page={{ blog.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ blog.number }} of {{ blog.paginator.num_pages }}. </span> {% if blog.has_next %} <a href="?page={{ blog.next_page_number }}">next</a> {% endif %} </span> <form method="post" action="" class="usertabs accfrm"> {{delblog.management_form}} {% for b, form in blog.object_list %} <div class="blog"> <h3>{{b.title}}</h3> <p>{{b.content}}</p> <p>posted by <strong>{{b.poster}}</strong> on {{b.date}}</p> {% ifequal staff staffis %}<p>{{form.as_p}}<input type="submit" value="Delete" /></p>{% endifequal %} </div> {% endfor %} </form> {%endblock%}

    Read the article

  • Django and floatformat tag

    - by Hellnar
    Hello, I want to modify / change the way the floatformat works. By default it changes the input decimal as such: {{ 1.00|floatformat }} -> 1 {{ 1.50|floatformat }} -> 1.5 {{ 1.53|floatformat }} -> 1.53 I want to change this abit as such: If there is a floating part, it should keep the first 2 floating digits. If no floating (which means .00) it should simply cut out the floating part. IE: {{ 1.00|floatformat }} -> 1 {{ 1.50|floatformat }} -> 1.50 {{ 1.53|floatformat }} -> 1.53

    Read the article

  • django admin - adding fields on the fly

    - by Thomas
    Basically I am writing a simple shopping cart. Each item can have multiple prices. (i.e. shirts where each size is priced differently). I would like to have a single price field in my admin panel, where when the first price is entered, an additional price field pops up. However I am kind of at a loss as to how to do this. What would be the best way to do this?

    Read the article

  • Django Custom Widget For ManyToMany field

    - by John
    Does anyone know of a widget that displays 2 select boxes. One shows a list of all object in a model and the other shows the objects which have been selected. The user can then select an object from the first list, click an button which moves it to the 'selected' list. Then when the form is saved the objects in the selected list are saved in the manytomany field. Thanks

    Read the article

  • Changing data in a django modelform

    - by Matt Hampel
    I get data in from POST and validate it via this standard snippet: entry_formset = EntryFormSet(request.POST, request.FILES, prefix='entries') if entry_formset.is_valid(): .... The EntryFormSet modelform overrides a foreign key field widget to present a text field. That way, the user can enter an existing key (suggested via an Ajax live search), or enter a new key, which will be seamlessly added. I use this try-except block to test if the object exists already, and if it doesn't, I add it. entity_name = request.POST['entries-0-entity'] try: entity = Entity.objects.get(name=entity_name) except Entity.DoesNotExist: entity = Entity(name=entity_name) entity.slug = slugify(entity.name) entity.save() However, I now need to get that entity back into the entry_formset. It thinks that entries-0-entity is a string (that's how it came in); how can I directly access that value of the entry_formset and get it to take the object reference instead?

    Read the article

  • Django javascript escape characters

    - by Hulk
    There is a text area in which the data is entered as, 122 //Enter button pushed Address Name //Enter button pushed 1 And the same is tored in the db.And the data is fetched in views and returned it to template as, <script> {% for i in dict.row_arr %} var ii= ('{{ i }}'); row_arr.push( ii ); {% endfor %} </script> Here there is an error as Error: unterminated string literal Line: 40, Column: 12 Source Code: var ii= ('1212 And when the html source shows up as, var ii= ('1212 1 21 11212121212'); row_arr.push( ii ); How should the escape function be applied here. Thanks..

    Read the article

  • Django: Overriding the clean() method in forms - question about raising errors

    - by Monika Sulik
    I've been doing things like this in the clean method: if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']: raise forms.ValidationError('The type and organization do not match.') if self.cleaned_data['start'] > self.cleaned_data['end']: raise forms.ValidationError('The start date cannot be later than the end date.') But then that means that the form can only raise one of these errors at a time. Is there a way for the form to raise both of these errors? EDIT #1: Any solutions for the above are great, but would love something that would also work in a scenario like: if self.cleaned_data['type'].organized_by != self.cleaned_data['organized_by']: raise forms.ValidationError('The type and organization do not match.') if self.cleaned_data['start'] > self.cleaned_data['end']: raise forms.ValidationError('The start date cannot be later than the end date.') super(FooAddForm, self).clean() Where FooAddForm is a ModelForm and has unique constraints that might also cause errors. If anyone knows of something like that, that would be great...

    Read the article

  • How to create a UserProfile form in Django with first_name, last_name modifications ?

    - by Natim
    If think my question is pretty obvious and almost every developer working with UserProfile should be able to answer it. However, I could not find any help on the django documentation or in the Django Book. When you want to do a UserProfile form in with Django Forms, you'd like to modify the profile fields as well as some User field. But there is no forms.UserProfileForm (yet?) ! How do you do that ?

    Read the article

  • Django - testing using large tables of static data

    - by Michael B
    I am using "manage.py test" along with a JSON fixture I created using using 'dumpdata' My problem is that several of the tables in the fixture are very large (for example one containing the names of all cities in the US) which makes running a test incredibly slow. Seeing as several of these tables are never modified by the program (eg - the city names will never need to be modified), it doesn't make much sense to create and tear down these tables for every test run. Is there a better way to be testing this code using this kind of data?

    Read the article

  • Problem in adding custom fields to django-registration

    - by Pankaj Singh
    I tried extending RegistrationFormUniqueEmail class CustomRegistrationFormUniqueEmail(RegistrationFormUniqueEmail): first_name = forms.CharField(label=_('First name'), max_length=30,required=True) last_name = forms.CharField(label=_('Last name'), max_length=30, required=True) def save(self, profile_callback=None): new_user = super(CustomRegistrationFormUniqueEmail, self).save(profile_callback=profile_callback) new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] return new_user then changing view # form = form_class(data=request.POST, files=request.FILES) form = CustomRegistrationFormUniqueEmail(data=request.POST, files=request.FILES) but still I am seeing default view containg four fields only .. help is needed

    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: 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

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >