Categories
Uncategorized

Misc Django I – forms

Custom form errors

If you want to validate something in the view, and return with a custom error message in the same form, you can use the “Form.add_error(fieldname, errorstring)” method. And then, of course, return to the previous template.

class MyView(View): 
    def get(self, request): 
        data = form.cleaned_data
        if len(res) > 0:
            form.add_error( 'login', "Diese Personalnummer existiert bereits!")
        return render(request, 'my_template.html', {'form': form})

Dynamic choice fields in forms

You want a form which fills its choice field from the database? And if the database changes, if you reload the page, the form should change as well? Of course! Django got you covered.

class UserForm(forms.Form): 
    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs) 
        self.fields['site'] = forms.ModelChoiceField( label="Site", queryset=Site.objects.all().order_by('name'), ) 
        for field in ('department', 'office', 'phone'):
            self.fields.move_to_end(field)

    login = forms.CharField(label="Login")
    email = forms.EmailField(label="Email")
    site = None # this is set in __init__() :)
    department = forms.CharField(label="Department")
    office = forms.CharField(label="Office")
    phone = forms.CharField(label="Phone")

… now, why the “for field in (‘department’ …)” line you ask?

Simple. The fields dict is an OrderedDict. If you replace a field it is appended to the end again. So in the form the “Site” input box would be displayed last, although it makes more sense to display it where it is in the original definition.

Using “.move_to_end()” you can re-adjust this. If someone knows a better method … feel free to tell me.

(Sources: here)

Categories
Uncategorized

Django, psql & “permission denied” on migrate

I got this error:

psycopg2.ProgrammingError: permission denied for relation django_migrations

… when I wanted to do a “python manage.py migrate”. This post had the solution. In short: You have to change the owner of the tables to the one specified in the Django configuration.

This is how my script looks:

#!/usr/bin/env bash
echo "ALTER TABLE public.django_admin_log OWNER TO <new_owner>;" | psql -U <current_owner> <database>
# ...

 

Categories
Uncategorized

Microsoft Code and Typescript

So being on the enterJS conference I wanted to get started with JavaScript. And TypeScript seems really promising. And once again I stumbled over the DIW pattern – Download, Install, Weird error messages.

So, here’s my take on how to get started.

I wanted …

  • ┬áto try node-hid to see my USB HID devices, using TypeScript, Microsoft Visual Studio Code, and Node.js.

So here’s how to get it to work:

mkdir my_project_dir
cd my_project_dir
brew install node            # I'm on Mac ;)
npm install -g typescript    # install globally
npm install node-hid         # install locally

Fire up Code, and “open” the project directory “my_project_dir”.

Press “CMD-SHIFT-P” (probably CTRL-SHIFT on non-OSX machines) and search for “Configure task runner”. Here you use this configuration:

{
  "version": "0.1.0",
  "command": "tsc",
  "isShellCommand": true,
  "showOutput": "silent",
  "args": [],
  "problemMatcher": "$tsc"
}

Then create a new file called “test.ts”, with the following content:

// typescript does not know "require".
// you have to convince it it "will exist at runtime".
// http://stackoverflow.com/a/12742371/902327
declare function require(name:string);
var HID = require('node-hid');
var devices = HID.devices();
console.log(devices);

Now if you press “CMD-SHIFT-B” this should compile and create a file called “test.js”.

I don’t know (yet) how to run it from within Code, so on the command line I can test it by doing …

$ node test.js
 { vendorId: 1452,
    productId: 589,
    path: 'USB_05ac_024d_fa120000',
    serialNumber: '',
    manufacturer: 'Apple Inc.',
    product: 'Apple Internal Keyboard / Trackpad',
    release: 521,
    interface: -1 },
  { vendorId: 0,
    productId: 0,
    path: '',
    serialNumber: '',
    manufacturer: '',
    product: 'Apple Mikey HID Driver',
    release: 0,
    interface: -1 },
  { vendorId: 1452,
    productId: 589,
    path: 'USB_05ac_024d_fa120000',
    serialNumber: '',
    manufacturer: 'Apple Inc.',
    product: 'Apple Internal Keyboard / Trackpad',
    release: 521,
    interface: -1 },
  { vendorId: 1452,
    productId: 589,
    path: 'USB_05ac_024d_fa120000',
    serialNumber: '',
    manufacturer: 'Apple Inc.',
    product: 'Apple Internal Keyboard / Trackpad',
    release: 521,
    interface: -1 },
  { vendorId: 1452,
    productId: 589,
    path: 'USB_05ac_024d_fa120000',
    serialNumber: '',
    manufacturer: 'Apple Inc.',
    product: 'Apple Internal Keyboard / Trackpad',
    release: 521,
    interface: -1 } ]

Article Sources:

Microsoft Visual Studio Help
Stackoverflow