Search Results

Search found 73266 results on 2931 pages for 'django file upload'.

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

  • Django version in GAE

    - by Alex
    I'm tring to use Django 1.1 in GAE, But when I uncomment use_library('django', '1.1') in this script import os os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from google.appengine.dist import use_library #use_library('django', '1.1') # Google App Engine imports. from google.appengine.ext.webapp import util # Force Django to reload its settings. from django.conf import settings settings._target = None import django.core.handlers.wsgi import django.core.signals import django.db import django.dispatch.dispatcher # Unregister the rollback event handler. django.dispatch.dispatcher.disconnect( django.db._rollback_on_exception, django.core.signals.got_request_exception) def main(): # Create a Django application for WSGI. application = django.core.handlers.wsgi.WSGIHandler() # Run the WSGI CGI handler with that application. util.run_wsgi_app(application) if __name__ == "__main__": main() I receives AttributeError: 'module' object has no attribute 'disconnect' What is going on?

    Read the article

  • Django Admin: not seeing any app (permission problem?)

    - by Facundo
    I have a site with Django running some custom apps. I was not using the Django ORM, just the view and templates but now I need to store some info so I created some models in one app and enabled the Admin. The problem is when I log in the Admin it just says "You don't have permission to edit anything", not even the Auth app shows in the page. I'm using the same user created with syncdb as a superuser. In the same server I have another site that is using the Admin just fine. Using Django 1.1.0 with Apache/2.2.10 mod_python/3.3.1 Python/2.5.2, with psql (PostgreSQL) 8.1.11 all in Gentoo Linux 2.6.23 Any ideas where I can find a solution? Thanks a lot. UPDATE: It works from the development server. I bet this has something to do with some filesystem permission but I just can't find it. UPDATE2: vhost configuration file: <Location /> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE gpx.settings PythonDebug On PythonPath "['/var/django'] + sys.path" </Location> UPDATE 3: more info /var/django/gpx/init.py exists and is empty I run python manage.py from /var/django/gpx directory The site is GPX, one of the apps is contable and lives in /var/django/gpx/contable the user apache is webdev group and all these directories and files belong to that group and have rw permission UPDATE 4: confirmed that the settings file is the same for apache and runserver (renamed it and both broke) UPDATE 5: /var/django/gpx/contable/init.py exists This is the relevan part of urls.py: urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), ) urlpatterns += patterns('gpx', (r'^$', 'menues.views.index'), (r'^adm/$', 'menues.views.admIndex'),

    Read the article

  • Django 1.4 dependency when packaging a Precise application

    - by Caustic
    I am trying to package a program I wrote that depends on Django 1.4.1 in Ubuntu 12.04. As Django 1.4.1 isn't available in Precise I am wondering if it is best to: Package up Django 1.4.1 and drop it in my ppa OR write a script that wgets Django at build time and installs. OR Something better that I haven't thought of. I am still inexperienced with packaging and would appreciate some advice Thanks

    Read the article

  • Django JSON serializable error

    - by Hulk
    With the following code below, There is an error saying File "/home/user/web_pro/info/views.py", line 184, in headerview, raise TypeError("%r is not JSON serializable" % (o,)) TypeError: <lastname: jerry> is not JSON serializable In the models code header(models.Model): firstname = models.ForeignKey(Firstname) lastname = models.ForeignKey(Lastname) In the views code headerview(request): header = header.objects.filter(created_by=my_id).order_by(order_by)[offset:limit] l_array = [] l_array_obj = [] for obj in header: l_array_obj = [obj.title, obj.lastname ,obj.firstname ] l_array.append(l_array_obj) dictionary_l.update({'Data': l_array}) ; return HttpResponse(simplejson.dumps(dictionary_l), mimetype='application/javascript') what is this error and how to resolve this? thanks..

    Read the article

  • Processing file uploads before object is saved

    - by Dominic Rodger
    I've got a model like this: class Talk(BaseModel): title = models.CharField(max_length=200) mp3 = models.FileField(upload_to = u'talks/', max_length=200) seconds = models.IntegerField(blank = True, null = True) I want to validate before saving that the uploaded file is an MP3, like this: def is_mp3(path_to_file): from mutagen.mp3 import MP3 audio = MP3(path_to_file) return not audio.info.sketchy Once I'm sure I've got an MP3, I want to save the length of the talk in the seconds attribute, like this: audio = MP3(path_to_file) self.seconds = audio.info.length The problem is, before saving, the uploaded file doesn't have a path (see this ticket, closed as wontfix), so I can't process the MP3. I'd like to raise a nice validation error so that ModelForms can display a helpful error ("You idiot, you didn't upload an MP3" or something). Any idea how I can go about accessing the file before it's saved? p.s. If anyone knows a better way of validating files are MP3s I'm all ears - I also want to be able to mess around with ID3 data (set the artist, album, title and probably album art, so I need it to be processable by mutagen).

    Read the article

  • Use WatiN for automation upload file on the website

    - by MrDuDuDu
    I need upload file on the website. But Have a problem, i can't choose file automatic in code. Always browser show me choose file window. What wrong in my code? IE ie = new IE("https://www.xxxx.com/WFrmlogin.aspx"); FileUploadDialogHandler uploadHandler = new FileUploadDialogHandler(@"D:\065-6405_URGENT.xls"); ie.WaitForComplete(); ie.TextField(Find.ById("txtUser")).TypeText("login"); ie.TextField(Find.ById("txtPassWord")).TypeText("***"); ie.Button(Find.ById("btnok")).Click(); ie.WaitForComplete(); ie.GoTo("https://www.orientspareparts.com/inq/WFrmUpOption.aspx"); ie.WaitForComplete(); ie.DialogWatcher.Clear(); ie.AddDialogHandler(uploadHandler); // This code show choose file dialog ie.FileUpload(Find.ById("FilUpload")).ClickNoWait(); ie.Button(Find.ById("butUpload")).Click(); ie.WaitForComplete();

    Read the article

  • Django Template tag, generating template block tag

    - by Issy
    Hi Guys, Currently a bit stuck, wondering if anyone can assist. I am using django-adminfiles. Which is a near little application. I want to use it to insert images into posts/articles/pages for a site i am building. How django-adminfiles works is it inserts a placeholder i.e <<< ImageFile and this gets rendered using a django template. It also has the feature of inserting custom options i.e (Insert Medium Image) , i figured i would used this to automatically resize images and include it in the post (similar to how WP does it). Django-adminfiles makes use of sorl.thumbnail app to generate thumbnails. So i have tried testing generating thumbnails: The current template that is used to render the inserted image is: {% spaceless %} <img src="{{ upload.upload.url }}" width="{{ upload.width }}" height="{{ upload.height }}" class="{{ options.class }}" class="{{ options.size }}" alt="{% if options.alt %}{{ options.alt }}{% else %}{{ upload.title }}{% endif %}" /> {% endspaceless %} I tried modifying this to: {% load thumbnail %} {% spaceless %} <img src="{% thumbnail upload.upload.url 200x50 %}" width="{{ upload.width }}" height="{{ upload.height }}" class="{{ options.class }}" class="{{ options.size }}" alt="{% if options.alt %}{{ options.alt }}{% else %}{{ upload.title }}{% endif %}" /> {% endspaceless %} I get the error: Exception Value: Caught an exception while rendering: Source file: '/media/uploads/DSC_0014.jpg' does not exist. I figured the thumbnail needs the absolute path so tried putting that in the template, and that works. i.e this works: {% thumbnail '/Users/me/media/uploads/DSC_0014.jpg' 200x50 %} So basically i need to generate the absolute path to the file give the relative path (to web root). You could do this by passing the MEDIA_ROOT setting to the template, but the reason i want to do a template tag is to programmatically set the image size.

    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

  • 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 views getid

    - by Hulk
    class host(models.Model): emp = models.ForeignKey(getname) def __unicode__(self): return self.topic In views there is the code as, real =[] for emp in my_emp: real.append(host.objects.filter(emp=emp.id)) This above results only the values of emp,My question is that how to get the ids along with emp values. Thanks..

    Read the article

  • django-admin: creating,saving and relating a m2m model

    - by pastylegs
    I have two models: class Production(models.Model): gallery = models.ManyToManyField(Gallery) class Gallery(models.Model): name = models.CharField() I have the m2m relationship in my productions admin, but I want that functionality that when I create a new Production, a default gallery is created and the relationship is registered between the two. So far I can create the default gallery by overwriting the productions save: def save(self, force_insert=False, force_update=False): if not ( Gallery.objects.filter(name__exact="foo").exists() ): g = Gallery(name="foo") g.save() self.gallery.add(g) This creates and saves the model instance (if it doesn't already exist), but I don't know how to register the relationship between the two?

    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 syncdb error

    - by Hulk
    /mysite/project4 class notes(models.Model): created_by = models.ForeignKey(User) detail = models.ForeignKey(Details) Details and User are in the same module i.e,/mysite/project1 In project1 models i have defined class User(): ...... class Details(): ...... When DB i synced there is an error saying Error: One or more models did not validate: project4: Accessor for field 'detail' clashes with related field . Add a related_name argument to the definition for 'detail'. How can this be solved.. thanks..

    Read the article

  • Filter Queryset in Django inlineformset_factory

    - by Dave
    I am trying to use inlineformset_factory to generate a formset. My models are defined as: class Measurement(models.Model): subject = models.ForeignKey(Animal) experiment = models.ForeignKey(Experiment) assay = models.ForeignKey(Assay) values = models.CommaSeparatedIntegerField(blank=True, null=True) class Experiment(models.Model): date = models.DateField() notes = models.TextField(max_length = 500, blank=True) subjects= models.ManyToManyField(Subject) in my view i have: def add_measurement(request, experiment_id): experiment = get_object_or_404(Experiment, pk=experiment_id) MeasurementFormSet = inlineformset_factory(Experiment, Measurement, extra=10, exclude=('experiment')) if request.method == 'POST': formset = MeasurementFormSet(request.POST,instance=experiment) if formset.is_valid(): formset.save() return HttpResponseRedirect( experiment.get_absolute_url() ) else: formset = MeasurementFormSet(instance=experiment) return render_to_response("data_entry_form.html", {"formset": formset, "experiment": experiment }, context_instance=RequestContext(request)) but i want to restrict the Measurement.subject field to only subjects defined in the Experiment.subjects queryset. I have tried a couple of different ways of doing this but I am a little unsure what the best way to accomplish this is. I tried to over-ride the BaseInlineFormset class with a new queryset, but couldnt figure out how to correctly pass the experiment parameter.

    Read the article

  • queries in django

    - by Hulk
    How to query Employee to get all the address related to the employee, Employee.Add.all() doe not work.. class Employee(): Add = models.ManyToManyField(Address) parent = models.ManyToManyField(Parent, blank=True, null=True) class Address(models.Model): address_emp = models.CharField(max_length=512) description = models.TextField() def __unicode__(self): return self.name()

    Read the article

  • Django QuerySet filter method returns multiple entries for one record

    - by Yaroslav
    Trying to retrieve blogs (see model description below) that contain entries satisfying some criteria: Blog.objects.filter(entries__title__contains='entry') The results is: [<Blog: blog1>, <Blog: blog1>] The same blog object is retrieved twice because of JOIN performed to filter objects on related model. What is the right syntax for filtering only unique objects? Data model: class Blog(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Entry(models.Model): title = models.CharField(max_length=100) blog = models.ForeignKey(Blog, related_name='entries') def __unicode__(self): return self.title Sample data: b1 = Blog.objects.create(name='blog1') e1 = Entry.objects.create(title='entry 1', blog=b1) e1 = Entry.objects.create(title='entry 2', blog=b1)

    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: CheckboxMultiSelect problem with db queries

    - by xiackok
    firstly sorry for my bad english there is a simple model Person. That contains just languages: LANGUAGE_LIS = ( (1, 'English'), (2, 'Turkish'), (3, 'Spanish') ) class Person(models.Model): languages = models.CharField(max_length=100, choices=LANGUAGE_LIST) #languages is multi value (CheckBoxSelectMultiple) and here person_save_form: class person_save_form(forms.ModelForm): languages = forms.CharField(widget=forms.CheckBoxSelectMultiple(choices=LANGUAGE_LIST)) class Meta: model = Person it is ok. but how can i search persons for languages like "get persons who knows turkish and english" in the database (MySQL) record "languages" column seen like "[u'1', u'2']". but i want search persons like this: persons = Person.objects.filter(languages__in=request.POST.getlist('languages'))

    Read the article

  • Django many to many queries

    - by Hulk
    In the following, How to get designation when querying Emp sc=Emp.objects.filter(pk=profile.emp.id)[0] sc.desg //this gives an error class Emp(models.Model): name = models.CharField(max_length=255, unique=True) address1 = models.CharField(max_length=255) city = models.CharField(max_length=48) state = models.CharField(max_length=48) country = models.CharField(max_length=48) desg = models.ManyToManyField(Designation) class Designation(models.Model): description = models.TextField() title = models.TextField() def __unicode__(self): return self.board

    Read the article

  • Tricky model inheritance - Django

    - by RadiantHex
    Hi folks, I think this is a bit tricky, at least for me. :) So I have 4 models Person, Singer, Bassist and Ninja. Singer, Bassist and Ninja inherit from Person. The problem is that each Person can be any of its subclasses. e.g. A person can be a Singer and a Ninja. Another Person can be a Bassist and a Ninja. Another one can be all three. How should I organise my models? Help would be much appreciated!

    Read the article

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