Search Results

Search found 8719 results on 349 pages for 'django views'.

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

  • 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 QuerySet filter + order_by + limit

    - by handsofaten
    So I have a Django app that processes test results, and I'm trying to find the median score for a certain assessment. I would think that this would work: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) median_exam = Exam.objects.filter(assessment=assessment.id).order_by('score')[median:1] median_score = median_exam.score But it always returns an empty list. I can get the result I want with this: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) exams = Exam.objects.filter(assessment=assessment.id).order_by('score') median_score = median_exam[median].score I would just prefer not to have to query the entire set of exams. I thought about just writing a raw MySQL query that looks something like: SELECT score FROM assess_exam WHERE assessment_id = 5 ORDER BY score LIMIT 690,1 But if possible, I'd like to stay within Django's ORM. Mostly, it's just bothering me that I can't seem to use order_by with a filter and a limit. Any ideas?

    Read the article

  • In plain English, what are Django generic views?

    - by allyourcode
    The first two paragraphs of this page explain that generic views are supposed to make my life easier, less monotonous, and make me more attractive to women (I made up that last one): http://docs.djangoproject.com/en/dev/topics/generic-views/#topics-generic-views I'm all for improving my life, but what do generic views actually do? It seems like lots of buzzwords are being thrown around, which confuse more than they explain. Are generic views similar to scaffolding in Ruby on Rails? The last bullet point in the intro seems to indicate this. Is that an accurate statement?

    Read the article

  • Drupal Views api, add simple argument handler

    - by LanguaFlash
    Background: I have a complex search form that stores the query and it's hash in a cache. Once the cache is set, I redirect to something like /searchresults/e6c86fadc7e4b7a2d068932efc9cc358 where that big long string on the end is the md5 hash of my query. I need to make a new argument for views to know what the hash is good for. The reason for all this hastle is because my original search form is way to complex and has way to many arguments to consider putting them all into the path and expecting to do the filtering with the normal views arguments. Now for my question. I have been reading views 2 documentation but not figuring out how to accomplish this custom argument. It doesn't seem to me like this should be as hard as it seems to me like it must be. Leaving aside any knowledge of the veiws api, it would seem that all I need is a callback function that will take the argument from the path as it's only argument and return a list of node id's to filter to. Can anyone point me to a solution or give me some example code? Thanks for your help! You guys are great. PS. I am pretty sure that my design is the best I can come up with, lets don't get off my question and into cross checking my design logic if we can help it.

    Read the article

  • How to test custom template tags in Django?

    - by Mark Lavin
    I'm adding a set of template tags to a Django application and I'm not sure how to test them. I've used them in my templates and they seem to be working but I was looking for something more formal. The main logic is done in the models/model managers and has been tested. The tags simply retrieve data and store it in a context variable such as {% views_for_object widget as views %} """ Retrieves the number of views and stores them in a context variable. """ # or {% most_viewed_for_model main.model_name as viewed_models %} """ Retrieves the ViewTrackers for the most viewed instances of the given model. """ So my question is do you typically test your template tags and if you do how do you do it?

    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

  • Django Class Views and Reverse Urls

    - by kalhartt
    I have a good many class based views that use reverse(name, args) to find urls and pass this to templates. However, the problem is class based views must be instantiated before urlpatterns can be defined. This means the class is instantiated while urlpatterns is empty leading to reverse throwing errors. I've been working around this by passing lambda: reverse(name, args) to my templates but surely there is a better solution. As a simple example the following fails with exception: ImproperlyConfigured at xxxx The included urlconf mysite.urls doesn't have any patterns in it mysite.urls from mysite.views import MyClassView urlpatterns = patterns('', url(r'^$' MyClassView.as_view(), name='home') ) views.py class MyClassView(View): def get(self, request): home_url = reverse('home') return render_to_response('home.html', {'home_url':home_url}, context_instance=RequestContext(request)) home.html <p><a href={{ home_url }}>Home</a></p> I'm currently working around the problem by forcing reverse to run on template rendering by changing views.py to class MyClassView(View): def get(self, request): home_url = lambda: reverse('home') return render_to_response('home.html', {'home_url':home_url}, context_instance=RequestContext(request)) and it works, but this is really ugly and surely there is a better way. So is there a way to use reverse in class based views but avoid the cyclic dependency of urlpatterns requiring view requiring reverse requiring urlpatterns...

    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

  • 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

  • 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

  • How to disable Middleware and Request Context in some views.

    - by xRobot
    I am creating a chat like facebook chat... so in views.py of my Chat Application, I need to retrieve only the last messages every 3-4 seconds with ajax poll ( the latency is not a problem for me ). If I can disable some Middlewares and some Request Context in this view, the response will be faster... no ? My question is: Is there a way to disable some Middlewares and some Request Context in some views ?

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