August 9, 2011 0

Using Javascript/Jquery Regex with match groups

By in Nothing, SysAdmin

I’m building custom syntax/markup for an editor I am building. The particular markup would look something like this:

%[--- This is part of the /etc/apache2/sites-available/example.com ---]%

And I want to turn it into

<div class="filerule">This is part of the /etc/apache2/sites-available/example.com</div>

So first I need to match: %[--- This is part of the /etc/apache2/sites-available/example.com ---]%
And then I need to match: This is part of the /etc/apache2/sites-available/example.com

The regex pattern would look like:

pattern = new RegExp('\\%\\[---(.+?)---\\]\\%','gi');

This entire pattern matches the whole line and the paranthesis define a match “group.” When looking for this pattern you will find two matches one for the line ( %[--- This is part of the /etc/apache2/sites-available/example.com ---]%) and one for the text (This is part of the /etc/apache2/sites-available/example.com).

You reference these matches by $1, …,$n where n is the number of that group.

The entire line would be $0 where as the text being matched would be $1.

Javascript:

$(document).ready(function() {

        function CreateFileRulers(){
        var raw_text = $("#raw_text").text();
        pattern = new RegExp('\\%\\[---(.+?)---\\]\\%','gi');
        raw_text = raw_text.replace(pattern,"
--- $1 ---
"); $("#raw_text").html(raw_text); } CreateFileRulers(); });

html:

<div id="raw_text">
%[--- This is part of the /etc/apache2/sites-available/example.com ---]%
</div>

After document ready the html:

<div id="raw_text">
<div class="filerule"--- This is part of the /etc/apache2/sites-available/example.com ---</div>
</div>
August 3, 2011 2

Jquery UI Autocomplete 1.8 with Django Views

By in Uncategorized

I have a model named “Show” and it has a ForeignKey to a model named “Venue.” When users add a “Show” I wanted an autocomplete(d) field venue.

This solution uses:

  • jquery-1.6.1.min.js
  • jquery-ui.min.js

models.py

class Venue(models.Model):
        name = models.CharField(max_length=255, blank=False, null=False, help_text="Name of the venue")

class Show(models.Model):
        date = models.DateTimeField(blank=False, null=False)
        venue = models.ForeignKey(Venue)
        headliner = models.ForeignKey(Artist, related_name="Headliner")

urls.py

(r'venue_lookup/$','projname.appname.views.venue_lookup'),

views.py

def venue_lookup(request):
   venues = Venue.objects.filter(name__istartswith=request.REQUEST['term'])
   results = []
   for venue in venues:
      venue_dict = {'id':venue.id, 'label':venue.name, 'value':venue.name}
      results.append(venue_dict)
   return HttpResponse(simplejson.dumps(results),mimetype='application/json')

Template:

<html>
<head>
<script type="text/javascript" src="/media/jquery-1.6.2.js"></script>
<script type="text/javascript" src="/media/jquery-ui.js"></script>
<script>
        $( "#id_venue" ).autocomplete({
           source: "/venue_lookup/",
           selectFirst:true,
           minLength:2
        });

</script>
</head>
<body>
<form method="post" action="/shows/new">
        <p><label for="id_venue">Venue</label>
        <input type="text" id="id_venue" name="venue" /></p>
	<input type="submit" value="done" />
</form>

</body>
</html>
July 22, 2011 2

Indexing Multi-value fields from django-tagging in Haystack

By in Fun, SysAdmin

Enabling tagging on models is easy when you use django-tagging. However, I also have a search feature which is powered by Haystack and Whoosh. I wanted to be able to search for objects by the tags that are associated with them. You need to use the following in your haystack SearchIndex model:

tags = indexes.MultiValueField(indexed=True, stored=True)

Full Example

myproject/myapp/models.py

from django.db import models,
from tagging.fields import TagField
class Template(models.Model):
        name = models.CharField(max_length=100)
        pub_date = models.DateTimeField(editable=False, blank=True)
        description = models.TextField(blank=True)
        slug = models.SlugField(unique=True,editable=False,blank=True,null=True)
        tags = TagField()

myproject/myapp/search_indexes.py

import datetime
from haystack import indexes
from generator.models import Template

class TemplateIndex(indexes.RealTimeSearchIndex):
    text = indexes.CharField(document=True, use_template=True)
    name = indexes.CharField(model_attr='name')
    description = indexes.CharField(model_attr='description')
    pub_date = indexes.DateTimeField(model_attr='pub_date')
    tags = indexes.MultiValueField(indexed=True, stored=True)

    def get_model(self):
        return Template

    def index_queryset(self):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())
July 20, 2011 0

django-registration Require a unique email address for registration

By in Fun, SysAdmin

Everyone uses django-registration for… registration… however.. you may get this error:

TypeError at /accounts/register/

register() takes at least 2 non-keyword arguments (1 given)

Here’s what your urls.py should look like for the /accounts/register/ url:

urls.py

from django.conf.urls.defaults import *
from registration.forms import RegistrationFormUniqueEmail

urlpatterns = patterns('',
     (r'^accounts/register/', 'registration.views.register', {'form_class':RegistrationFormUniqueEmail,'backend':'registration.backends.default.DefaultBackend' }),
)
July 20, 2011 0

Unique Slugs for Django Objects

By in Fun, SysAdmin

I’m working on a new project and decided to use slugs to access object information.  The built-in in “slugify” does not generate unique slugs for objects, but I found a solution. Overriding the save method allows us to check to see if there are any other objects which have the same slug such as “how-to-make-a-table” and if there are we append a number to it such as “how-to-make-a-table-2.” Below is a real-world example of a model “Project” which has pretty typical fields in it and the code to generate a unique slug.

file: /myproject/myapp/models.py

from django.contrib.auth.models import User
from sorl.thumbnail import ImageField
import datetime
import re

class Project(models.Model):
        title = models.CharField(max_length=255,blank=True)
        description = models.TextField(blank=True)
        photo = ImageField(upload_to=get_project_upload_path, blank=True, null=True)
        author = models.ForeignKey(User, editable=False,blank=True, null=True)
        pub_date = models.DateTimeField(editable=False, blank=True)
        slug = models.SlugField(unique=True,blank=True)

        def save(self, *args, **kwargs):
		#set pub_date as right now
                self.pub_date=datetime.datetime.now()

		#As long as this object does NOT have a slug
                if not self.slug:
                   from django.template.defaultfilters import slugify

		   #Take the title and replace spaces with hypens, make lowercase
                   potential_slug = slugify(self.title)
                   self.slug = potential_slug

                   while True:
                      try:
			 #try to save the object
                         super(Project, self).save(*args, **kwargs)

		      #if this slug already exists we get an error
                      except IntegrityError:
			 #match the slug or look for a trailing number
                         match_obj = re.match(r'^(.*)-(\d+)$', self.slug)

			 #if we find a match
                         if match_obj:
			    #take the found number and increment it by 1
                            next_int = int(match_obj.group(2)) + 1
                            self.slug = match_obj.group(1) + "-" + str(next_int)
                         else:
			    #There are no matches for -# so create one with -2
                            self.slug += '-2'
		      #different error than IntegrityError
                      else:
                         break

        def __unicode__(self):
                return self.title