Search Results

Search found 5507 results on 221 pages for 'django cms'.

Page 8/221 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | 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

  • Django-cms problem

    - by 47
    I'm setting up a website using django-cms and when I open up the add page view in the admin, I get this error: TemplateSyntaxError at /admin/cms/page/add/ Invalid block tag: 'csrf_token' What could be the problem? I'm using Django 1.1. BTW.

    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

  • Residential Care Homes website launched based on the Umbraco CMS

    - by Vizioz Limited
    This week we have launched a new website for a local company called Ascot Residential Homes. They run two homes for the elderly and for those who suffer with dementia. Before we built the site for Ascot Residential Homes they asked us to visit the homes to get a feeling about how special they are. If you are looking for a home for an elderly relative I would highly recommend having a look at their website and if you are in the area arranging to visit them.If you look on our site you will also find an Ascot Residential Homes case study in our Umbraco case studies section.

    Read the article

  • CMS DITA North America Conference / Agile Doc

    - by ultan o'broin
    I attended and presented, along with a colleague, at the Content Management Strategies DITA North America Conference 2010 in Santa Clara this week. It was touch and go whether I would make it across the Atlantic, but as usual the Irish always got through! Our presentation was about DITA and Writing Patterns, and there was three other presentations from Oracle folks too, all very well delivered and received. The interaction with other companies was superb, and the sparks of innovation that flew as a result left me with three use case ideas for UX investigation and implementation. My colleague had a similar experience. Well worth attending! One of the last sessions was about Authoring in an Agile environment, presented by Julio Vasquez. This was an excellent, common sense, and forthright no-nonsense delivery that made complete sense to me. I'd encourage you, if you are interested in the subject, to check out Julio's white paper on the subject too, available from the SDI website.

    Read the article

  • CMS for Blog site

    - by Yau Leung
    I would like to create a blog site with features like Engadget. The editor can upload blog and albums while users can comment. I know it's even easier to use blogspot but it's blocked in China. I have tried Joomla before. It seems a bit slow even after removing most of the modules and the memcache plugin doesn't help much either. Is there any other option? Do I need other plugins to run WordPress as blog?

    Read the article

  • PHP Fingerprinting CMS Versions by their meta tags [migrated]

    - by Mud
    Hey guys I'm having some issues with the speed of my script. I'm a novice I know so getting past that - what suggestions would you have to speed up my script? I was originally just reading in the index.php and then searching the <head> of the page for an array of strings. Then I read about the get_meta_tags and went that way. Then I had issues with some sites having 300 redirects in place so I used curl to check the URL existed and to speed up things but it's still taking 5 minutes or so to execute. <?php function url_exist($url){ $c=curl_init(); curl_setopt($c,CURLOPT_URL,$url); curl_setopt($c,CURLOPT_HEADER,1); curl_setopt($c,CURLOPT_NOBODY,1); curl_setopt($c,CURLOPT_RETURNTRANSFER,1); curl_setopt($c,CURLOPT_FRESH_CONNECT,1); if(!curl_exec($c)){ return false; }else{ return true; } curl_close($c); } function checkVersion($url){ $tags = get_meta_tags($url); if (is_array($tags) && array_key_exists('generator', $tags)) { $v = "<span style='background-color:#7BF55D;color:#A3A0A0'>".$tags['generator']."</span"; }else{ $v="<span style='background-color:#F55D67;color:#A3A0A0'>Metatag not found!</span>"; } return $v; } $row = 1; echo "<table>"; if (($handle = fopen("url.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); $row++; for ($c=0; $c < $num; $c++) { if(url_exist($data[$c])){ echo "<tr><td>".$data[$c]."</td><td>".checkVersion($data[$c])."</td></tr>"; sleep(2); }else{ echo "<tr><td>".$data[$c]."</td><td><td><span style='background-color:#F55D5D;color:#A3A0A0'>URL not valid!<span></td></tr>"; } } } fclose($handle); } echo "</table>"; ?>

    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

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