Search Results

Search found 4773 results on 191 pages for 'django orm'.

Page 7/191 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • How to customize a many-to-many inline model in django admin

    - by Jonathan
    I'm using the admin interface to view invoices and products. To make things easy, I've set the products as inline to invoices, so I will see the related products in the invoice's form. As you can see I'm using a many-to-many relationship. In models.py: class Product(models.Model): name = models.TextField() price = models.DecimalField(max_digits=10,decimal_places=2) class Invoice(models.Model): company = models.ForeignKey(Company) customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product) In admin.py: class ProductInline(admin.StackedInline): model = Invoice.products.through class InvoiceAdmin(admin.ModelAdmin): inlines = [FilteredApartmentInline,] admin.site.register(Product, ProductAdmin) The problem is that django presents the products as a table of drop down menus (one per associated product). Each drop down contains all the products listed. So if I have 5000 products and 300 are associated with a certain invoice, django actually loads 300x5000 product names. Also the table is not aesthetic. How can I change it so that it'll just display the product's name in the inline table? Which form should I override, and how?

    Read the article

  • django cross-site reverse a url

    - by tutuca
    I have a similar question than django cross-site reverse. But i think I can't apply the same solution. I'm creating an app that lets the users create their own site. After completing the signup form the user should be redirected to his site's new post form. Something along this lines: new_post_url = 'http://%s.domain:9292/manage/new_post %site.domain' logged_user = authenticate(username=user.username, password=user.password) if logged_user is not None: login(request, logged_user) return redirect(new_product_url) Now, I know that "new_post_url" is awful and makes babies cry so I need to reverse it in some way. I thought in using django.core.urlresolvers.reverse to solve this but that only returns urls on my domain, and not in the user's newly created site, so it doesn't works for me. So, do you know a better/smarter way to solve this?

    Read the article

  • Load django template from the database

    - by Björn Lindqvist
    Hello, Im trying to render a django template from a database outside of djangos normal request-response structure. But it appears to be non-trivial due to the way django templates are compiled. I want to do something like this: >>> s = Template.objects.get(pk = 123).content >>> some_method_to_render(s, {'a' : 123, 'b' : 456}) >>> ... the rendered output here ... How do you do this?

    Read the article

  • How to use multiple flatpages models in a django app?

    - by the_drow
    I have multiple models that can be converted to flatpages but have to have some extra information (For example I have an about us page but I also have a blog). However I understand that there must be only one flatpages model since the middleware only returns the flatpages instance and does not resolve the child models. What do I have to do? EDIT: It seems I need to change the views. Here's the current code: from django.contrib.flatpages.models import FlatPage from django.template import loader, RequestContext from django.shortcuts import get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.core.xheaders import populate_xheaders from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_protect DEFAULT_TEMPLATE = 'flatpages/default.html' # This view is called from FlatpageFallbackMiddleware.process_response # when a 404 is raised, which often means CsrfViewMiddleware.process_view # has not been called even if CsrfViewMiddleware is installed. So we need # to use @csrf_protect, in case the template needs {% csrf_token %}. # However, we can't just wrap this view; if no matching flatpage exists, # or a redirect is required for authentication, the 404 needs to be returned # without any CSRF checks. Therefore, we only # CSRF protect the internal implementation. def flatpage(request, url): """ Public interface to the flat page view. Models: `flatpages.flatpages` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object """ if not url.endswith('/') and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith('/'): url = "/" + url # Here instead of getting the flat page it needs to find if it has a page with a child model. f = get_object_or_404(FlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) return render_flatpage(request, f) @csrf_protect def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) # Here I need to be able to configure what I am passing in the context c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response

    Read the article

  • Create Django formset wihtout multiple queries

    - by Martin
    I need to display multiple forms (up to 10) of a model on a page. This is the code I use for to accomplish this. TheFormSet = formset_factory(SomeForm, extra=10) ... formset = TheFormSet(prefix='party') return render_to_response('template.html', { 'formset' : formset, }) The problem is, that it seems to me that Django queries the database for each of the forms in the formset, even though the data displayed in them is the same. Is this the way Formsets work or am I doing something wrong? Is there a way around it inside django or would I have to use JavaScript for a workaround?

    Read the article

  • django auth_views.login and redirects

    - by Zayatzz
    Hello I could not understand why after logging in from address: http://localhost/en/accounts/login/?next=/en/test/ I get refirected to http://localhost/accounts/profile/ So i ran search in django files and found that this address is the default LOGIN_REDIRECT_URL for django. What i did not understand is why it gets redirected to there. I guessed, that my login form's post address should be : /accounts/login/?next=/en/test/ instead of /accounts/login/ I wrote it into template and it worked. But since the redirect url changes dynamically, how can i make this login post forms address change dynamically too? is there a templatetag for that or something? Alan

    Read the article

  • Calling a method from within a django model save() override

    - by Jonathan
    I'm overriding a django model save() method. Within the override I'm calling another method of the same class and instance which calculates one of the instance's fields based on other fields of the same instance. class MyClass(models.Model): field1 = models.FloatField() field2 = models.FloatField() field3 = models.FloatField() def calculateField1(self) self.field1 = self.field2 + self.field3 def save(self, *args, **kwargs): self.calculateField1() super(MyClass, self).save(*args, **kwargs) The override method is called when I change the model in admin. Alas I've discovered that within calculateField1() field2 and field3 have the values of the instance from before I edited them in admin. If I enter the instance again in admin and save again, only then field1 receives the correct value as field2 and field3 are already updated. Is this the correct behavior on django's side? If yes, then how can I use the new values within calculateField1? I cannot implement the calculation within the save() as calculateField1() actually quite long and I need it to be called from elsewhere.

    Read the article

  • Django | django-socialregistration error

    - by MMRUser
    I'm trying to add the facebook connect feature to my site, I decided to use django socialregistration.All are setup including pyfacebook, here is my source code. settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'facebook.djangofb.FacebookMiddleware', 'socialregistration.middleware.FacebookMiddleware', ) urls.py (r'^callback/$', 'fbproject.fbapp.views.callback'), views.py def callback(request): return render_to_response('canvas.fbml') Template <html> <body> {% load facebook_tags %} {% facebook_button %} {% facebook_js %} </body> </html> but when I point to the URL, I'm getting this error Traceback (most recent call last): File "C:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 279, in run self.result = application(self.environ, self.start_response) File "C:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 651, in __call__ return self.application(environ, start_response) File "C:\Python26\lib\site-packages\django\core\handlers\wsgi.py", line 241, in __call__ response = self.get_response(request) File "C:\Python26\lib\site-packages\django\core\handlers\base.py", line 73, in get_response response = middleware_method(request) File "build\bdist.win32\egg\socialregistration\middleware.py", line 13, in process_request request.facebook.check_session(request) File "C:\Python26\lib\site-packages\facebook\__init__.py", line 1293, in check_session self.session_key_expires = int(params['expires']) ValueError: invalid literal for int() with base 10: 'None' Django 1.1.1 *Python 2.6.2*

    Read the article

  • Manditory read-only fields in django

    - by jamida
    I'm writing a test "grade book" application. The models.py file is shown below. class Student(models.Model): name = models.CharField(max_length=50) parent = models.CharField(max_length=50) def __unicode__(self): return self.name class Grade(models.Model): studentId = models.ForeignKey(Student) finalGrade = models.CharField(max_length=3) I'd like to be able to change the final grade for several students in a modelformset but for now I'm just trying one student at a time. I'm also trying to create a form for it that shows the student name as a field that can not be changed, the only thing that can be changed here is the finalGrade. So I used this trick to make the studentId read-only. class GradeROForm(ModelForm): studentId = forms.ModelChoiceField(queryset=Student.objects.all()) def __init__(self, *args, **kwargs): super(GradeROForm,self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.id: self.fields['studentId'].widget.attrs['disabled']='disabled' def clean_studentId(self): instance = getattr(self,'instance',None) if instance: return instance.studentId else: return self.cleaned_data.get('studentId',None) class Meta: model=Grade And here is my view: def modifyGrade(request,student): student = Student.objects.get(name=student) mygrade = Grade.objects.get(studentId=student) if request.method == "POST": myform = GradeROForm(data=request.POST, instance=mygrade) if myform.is_valid(): grade = myform.save() info = "successfully updated %s" % grade.studentId else: myform=GradeROForm(instance=mygrade) return render_to_response('grades/modifyGrade.html',locals()) This displays the form like I expect, but when I hit "submit" I get a form validation error for the student field telling me this field is required. I'm guessing that, since the field is "disabled", the value is not being reported in the POST and for reasons unknown to me the instance isn't being used in its place. I'm a new Django/Python programmer, but quite experienced in other languages. I can't believe I've stumbled upon such a difficult to solve problem in my first significant django app. I figure I must be missing something. Any ideas?

    Read the article

  • Django Upload form to S3 img and form validation

    - by citadelgrad
    I'm fairly new to both Django and Python. This is my first time using forms and upload files with django. I can get the uploads and saves to the database to work fine but it fails to valid email or check if the users selected a file to upload. I've spent a lot of time reading documentation trying to figure this out. Thanks! views.py def submit_photo(request): if request.method == 'POST': def store_in_s3(filename, content): conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(AWS_STORAGE_BUCKET_NAME) mime = mimetypes.guess_type(filename)[0] k = Key(bucket) k.key = filename k.set_metadata("Content-Type", mime) k.set_contents_from_file(content) k.set_acl('public-read') if imghdr.what(request.FILES['image_url']): qw = request.FILES['image_url'] filename = qw.name image = filename content = qw.file url = "http://bpd-public.s3.amazonaws.com/" + image data = {image_url : url, user_email : request.POST['user_email'], user_twittername : request.POST['user_twittername'], user_website : request.POST['user_website'], user_desc : request.POST['user_desc']} s = BeerPhotos(data) if s.is_valid(): #import pdb; pdb.set_trace() s.save() store_in_s3(filename, content) return HttpResponseRedirect(reverse('photos.views.thanks')) return s.errors else: return errors else: form = BeerPhotoForm() return render_to_response('photos/submit_photos.html', locals(),context_instance=RequestContext(request) forms.py class BeerPhotoForm(forms.Form): image_url = forms.ImageField(widget=forms.FileInput, required=True,label='Beer',help_text='Select a image of no more than 2MB.') user_email = forms.EmailField(required=True,help_text='Please type a valid e-mail address.') user_twittername = forms.CharField() user_website = forms.URLField(max_length=128,) user_desc = forms.CharField(required=True,widget=forms.Textarea,label='Description',) template.html <div id="stylized" class="myform"> <form action="." method="post" enctype="multipart/form-data" width="450px"> <h1>Photo Submission</h1> {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} <label><span>Click here</span></label> <input type="submit" class="greenbutton" value="Submit your Photo" /> </form> </div>

    Read the article

  • Invalidating Memcached Keys on save() in Django

    - by Zack
    I've got a view in Django that uses memcached to cache data for the more highly trafficked views that rely on a relatively static set of data. The key word is relatively: I need invalidate the memcached key for that particular URL's data when it's changed in the database. To be as clear as possible, here's the meat an' potatoes of the view (Person is a model, cache is django.core.cache.cache): def person_detail(request, slug): if request.is_ajax(): cache_key = "%s_ABOUT_%s" % settings.SITE_PREFIX, slug # Check the cache to see if we've already got this result made. json_dict = cache.get(cache_key) # Was it a cache hit? if json_dict is None: # That's a negative Ghost Rider person = get_object_or_404(Person, display = True, slug = slug) json_dict = { 'name' : person.name, 'bio' : person.bio_html, 'image' : person.image.extra_thumbnails['large'].absolute_url, } cache.set(cache_key) # json_dict will now exist, whether it's from the cache or not response = HttpResponse() response['Content-Type'] = 'text/javascript' response.write(simpljson.dumps(json_dict)) # Make sure it's all properly formatted for JS by using simplejson return response else: # This is where the fully templated response is generated What I want to do is get at that cache_key variable in it's "unformatted" form, but I'm not sure how to do this--if it can be done at all. Just in case there's already something to do this, here's what I want to do with it (this is from the Person model's hypothetical save method) def save(self): # If this is an update, the key will be cached, otherwise it won't, let's see if we can't find me try: old_self = Person.objects.get(pk=self.id) cache_key = # Voodoo magic to get that variable old_key = cache_key.format(settings.SITE_PREFIX, old_self.slug) # Generate the key currently cached cache.delete(old_key) # Hit it with both barrels of rock salt # Turns out this doesn't already exist, let's make that first request even faster by making this cache right now except DoesNotExist: # I haven't gotten to this yet. super(Person, self).save() I'm thinking about making a view class for this sorta stuff, and having functions in it like remove_cache or generate_cache since I do this sorta stuff a lot. Would that be a better idea? If so, how would I call the views in the URLconf if they're in a class?

    Read the article

  • Formatting inline many-to-many related models presented in django admin

    - by Jonathan
    I've got two django models (simplified): class Product(models.Model): name = models.TextField() price = models.IntegerField() class Invoice(models.Model): company = models.TextField() customer = models.TextField() products = models.ManyToManyField(Product) I would like to see the relevant products as a nice table (of product fields) in an Invoice page in admin and be able to link to the individual respective Product pages. My first thought was using the admin's inline - but django used a select box widget per related Product. This isn't linked to the Product pages, and also as I have thousands of products, and each select box independently downloads all the product names, it quickly becomes unreasonably slow. So I turned to using ModelAdmin.filter_horizontal as suggested here, which used a single instance of a different widget, where you have a list of all Products and another list of related Products and you can add\remove products in the later from the former. This solved the slowness, but it still doesn't show the relevant Product fields, and it ain't linkable. So, what should I do? tweak views? override ModelForms? I Googled around and couldn't find any example of such code...

    Read the article

  • Math on Django Templates

    - by Leandro Abilio
    Here's another question about Django. I have this code: views.py cursor = connections['cdr'].cursor() calls = cursor.execute("SELECT * FROM cdr where calldate > '%s'" %(start_date)) result = [SQLRow(cursor, r) for r in cursor.fetchall()] return render_to_response("cdr_user.html", {'calls':result }, context_instance=RequestContext(request)) I use a MySQL query like that because the database is not part of a django project. My cdr table has a field called duration, I need to divide that by 60 and multiply the result by a float number like 0.16. Is there a way to multiply this values using the template tags? If not, is there a good way to do it in my views? My template is like this: {% for call in calls %} <tr class="{% cycle 'odd' 'even' %}"><h3> <td valign="middle" align="center"><h3>{{ call.calldate }}</h3></td> <td valign="middle" align="center"><h3>{{ call.disposition }}</h3></td> <td valign="middle" align="center"><h3>{{ call.dst }}</h3></td> <td valign="middle" align="center"><h3>{{ call.billsec }}</h3></td> <td valign="middle" align="center">{{ (call.billsec/60)*0.16 }}</td></h3> </tr> {% endfor %} The last is where I need to show the value, I know the "(call.billsec/60)*0.16" is impossible to be done there. I wrote it just to represent what I need to show.

    Read the article

  • Django ModelForm is giving me a validation error that doesn't make sense

    - by River Tam
    I've got a ModelForm based on a Picture. class Picture(models.Model): name = models.CharField(max_length=100) pub_date = models.DateTimeField('date published') tags = models.ManyToManyField('Tag', blank=True) content = models.ImageField(upload_to='instaton') def __unicode__(self): return self.name class PictureForm(forms.ModelForm): class Meta: model = Picture exclude = ('pub_date','tags') That's the model and the ModelForm, of course. def submit(request): if request.method == 'POST': # if the form has been submitted form = PictureForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/django/instaton') else: form = PictureForm() # blank form return render_to_response('instaton/submit.html', {'form': form}, context_instance=RequestContext(request)) That's the view (which is being correctly linked to by urls.py) Right now, I do nothing when the form submits. I just check to make sure it's valid. If it is, I forward to the main page of the app. <form action="/django/instaton/submit/" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value"Submit" /> </form> And there's my template (in the correct location). When I try to actually fill out the form and just validate it, even if I do so correctly, it sends me back to the form and says "This field is required" between Name and Content. I assume it's referring to Content, but I'm not sure. What's my problem? Is there a better way to do this?

    Read the article

  • Benchmarking ORM associations

    - by barerd
    I am trying to benchmark two cases of self referential many to many as described in datamapper associations. Both cases consist of an Item clss, which may require many other items. In both cases, I required the ruby benchmark library and source file, created two items and benchmarked require/unrequie functions as below: Benchmark.bmbm do |x| x.report("require:") { item_1.require_item item_2, 10 } x.report("unrequire:") { item_1.unrequire_item item_2 } end To be clear, both functions are datamapper add/modify functions like: componentMaps.create :component_id => item.id, :quantity => quantity componentMaps.all(:component_id => item.id).destroy! and links_to_components.create :component_id => item.id, :quantity => quantity links_to_components.all(:component_id => item.id).destroy! The results are variable and in the range of 0.018001 to 0.022001 for require function in both cases, and 0.006 to 0.01 for unrequire function in both cases. This made me suspicious about the correctness of my test method. Edit I went ahead and compared a "get by primary key case" to a "finding first matching record case" by: (1..10000).each do |i| Item.create :name => "item_#{i}" end Benchmark.bmbm do |x| x.report("Get") { item = Item.get 9712 } x.report("First") { item = Item.first :name => "item_9712" } end where the results were very different like 0 sec compared to 0.0312, as expected. This suggests that the benchmarking works. I wonder whether I benchmarked the two types of associations correctly, and whether a difference between 0.018 and 0.022 sec significant?

    Read the article

  • django views question

    - by Hulk
    In my django views i have the following def create(request): query=header.objects.filter(id=a)[0] a=query.criteria_set.all() logging.debug(a.details) I get an error saying 'QuerySet' object has no attribute 'details' in the debug statement .What is this error and what should be the correct statemnt to query this.And the model corresponding to this is as follows where as the models has the following: class header(models.Model): title = models.CharField(max_length = 255) created_by = models.CharField(max_length = 255) def __unicode__(self): return self.id() class criteria(models.Model): details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() Thanks..

    Read the article

  • Django url parameters

    - by Hulk
    How to pass two paramters in urls in django <script> url=/toolbox/display/" + id + "2"; window.location=url; </script> Also how is this handeled in urls.py (r'^display/(?P<rid>\d+)/(?P<param>\d+)/$', 'table_display'), In views, def table_display(request,rid,param): print param //This should print 2

    Read the article

  • Django forms "not" using forms from models

    - by zubinmehta
    I have a form generated from various models and the various values filled go and sit in some other table. Hence, in this case I haven't used the inbuilt Django forms(i.e. I am not creating forms from models ). Now the data which is posted from the self made form is handled by view1 which should clean the data accordingly. How do I go about it and use the various functions clean and define validation errors (and preferably not do validation logic in the view itself!)

    Read the article

  • Extended Django base-class with multiple instances

    - by Gijs
    I'm modeling a simple movie database using Django. models.py defines a base model Person. I extend Person into Actor and Director, which works as I imagined. Persons must be unique. When (in the Admin) I create an instance of Actor, and this person is also a Director, it won't save because of the unique = True. Any ideas how to solve this problem? (generic foreign keys?) Thx

    Read the article

  • Django: How to get current user in admin forms

    - by lazerscience
    In Django's ModelAdmin I need to display forms customized according to the permissions an user has. Is there a way of getting the current user object into the form class, so that i can customize the form in its __init__ method? I think saving the current request in a thread local would be a possibility but this would be my last resort think I'm thinking it is a bad design approach....

    Read the article

  • Django template-printing variables

    - by Hulk
    In django views def add(request): dict{} co_data = optarr dict.update({'co_data' : co_data}) logging.debug(co_data) return render_to_response('scheme/create.html',context_instance=RequestContext(request,{'dict': dict})) And data has the following string 1##2##3##4## And in the template when i say {{co_data}} it doesnt display the values.Please point out whats wrong in the code. Thanks..

    Read the article

  • Django filter vs exclude

    - by Enrico
    Is there a difference between filter and exclude in django? If I have self.get_query_set().filter(modelField=x) and I want to add another criteria, is there a meaningful difference between to following two lines of code? self.get_query_set().filter(user__isnull=False, modelField=x) self.get_query_set().filter(modelField=x).exclude(user__isnull=True) is one considered better practice or are they the same in both function and performance?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >