Rectangle 27 2

for 1.6, using forms I had to specify the attributes of the textarea inside the charfield:

test1 = forms.CharField(max_length=400, widget=forms.Textarea( attrs={'rows':'2', 'cols': '10'}),  initial='', help_text=helptexts.helptxt['test'])

This does not work for TextField.

python - Resize fields in Django Admin - Stack Overflow

python django django-models django-admin
Rectangle 27 6

The answer to you question is proper configuration of settings and formats in Django project. Structure of example project:

.
|-- README.md
|-- demo.db
|-- demo_time_set
|   |-- __init__.py
|   |-- demo.db
|   |-- formats
|   |   |-- __init__.py
|   |   `-- en
|   |       |-- __init__.py
|   |       `-- formats.py
|   |-- settings.py
|   |-- urls.py
|   `-- wsgi.py
|-- manage.py
|-- requirments.txt
`-- some_app
    |-- __init__.py
    |-- admin.py
    `-- models.py

You can define it for multiple languages just by providing directory with appropriate name and formats.py inside. The example content of formats.py where all the MAGIC happens can look as follows:

# HERE FORMATING AS shown in:
# LIST: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'd-m-Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'd-m-Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'F j'
SHORT_DATE_FORMAT = 'm/d/Y'
SHORT_DATETIME_FORMAT = 'm/d/Y P'
FIRST_DAY_OF_WEEK = 1

# BUT here use the Python strftime format syntax,
# LIST: http://docs.python.org/library/datetime.html#strftime-strptime-behavior

DATE_INPUT_FORMATS = (
    '%d-%m-%Y',     # '21-03-2014'
)
TIME_INPUT_FORMATS = (
    '%H:%M:%S',     # '17:59:59'
    '%H:%M',        # '17:59'
)
DATETIME_INPUT_FORMATS = (
    '%d-%m-%Y %H:%M',     # '21-03-2014 17:59'
)

DECIMAL_SEPARATOR = u'.'
THOUSAND_SEPARATOR = u','
NUMBER_GROUPING = 3

Please notice two links in the comments, which will guide you to lists of proper configurations, which ARE DIFFERENT for DIFFERENT parts!

settings.py
FORMAT_MODULE_PATH = 'demo_time_set.formats'

Say I want to store the dates in UTC but display them in local time? I have my time zone set to UTC and my locale to en but it's not taking into account the formats defined in myapp/formats/en/formats.py... Something missing?

How to format DateTimeField in Django Admin to localtime? - Stack Over...

django django-admin django-timezone
Rectangle 27 5

RichTextField('contents')
RichTextUploadingField('contents')
from ckeditor_uploader.fields import RichTextUploadingField

python - How to use django-ckeditor to upload files and browser files ...

python django ckeditor django-ckeditor
Rectangle 27 1

You can easily do that in the form clean() method.

from django.shortcuts import get_object_or_404

class SkuForm(forms.Form):
    sku = forms.CharField(required=True)
    extra_field = forms.CharField(required=True)

    def clean(self):
        # If you're on Python 2.x, change super() to super(SkuForm, self)
        cleaned_data = super().clean()
        sku = cleaned_data['sku']
        obj = get_object_or_404(Product, sku_number=sku)
        # do sth with the Product

Sorry, I am not exactly sure (as of yet) what your answer suggests. The form submits successfully when pk of the Product model is entered. However, it still won't accept the sku_number raising a KeyError. Part of the problem might be, that def clean(self): doesn't return anything, but I did try returning return self.cleaned_data.

obj = get_object_or_404(Product, sku_number=sku);         self.cleaned_data['sku_number'] = obj.id

@SurajThapar Sorry mate, I updated the code snippet. Didn't remember it correctly last night.

python - How to use TextInput widget with ModelChoiceField in Django f...

python django forms
Rectangle 27 6

I'm new to this as well and have been studying up on the subject recently.

Here's a method I found using the python gdal pacakge (the osr package is included in gdal). The gdal package is pretty powerful, but the documentation could be better.

import osr

def transform_utm_to_wgs84(easting, northing, zone):
    utm_coordinate_system = osr.SpatialReference()
    utm_coordinate_system.SetWellKnownGeogCS("WGS84") # Set geographic coordinate system to handle lat/lon
    is_northern = northing > 0    
    utm_coordinate_system.SetUTM(zone, is_northern)

    wgs84_coordinate_system = utm_coordinate_system.CloneGeogCS() # Clone ONLY the geographic coordinate system 

    # create transform component
    utm_to_wgs84_transform = osr.CoordinateTransformation(utm_coordinate_system, wgs84_coordinate_system) # (<from>, <to>)
    return utm_to_wgs84_transform.TransformPoint(easting, northing, 0) # returns lon, lat, altitude

And here's the method for converting from a lat, lon in wgs84 (what most gps units report) to utm:

def transform_wgs84_to_utm(lon, lat):    
    def get_utm_zone(longitude):
        return (int(1+(longitude+180.0)/6.0))

    def is_northern(latitude):
        """
        Determines if given latitude is a northern for UTM
        """
        if (latitude < 0.0):
            return 0
        else:
            return 1

    utm_coordinate_system = osr.SpatialReference()
    utm_coordinate_system.SetWellKnownGeogCS("WGS84") # Set geographic coordinate system to handle lat/lon  
    utm_coordinate_system.SetUTM(get_utm_zone(lon), is_northern(lat))

    wgs84_coordinate_system = utm_coordinate_system.CloneGeogCS() # Clone ONLY the geographic coordinate system 

    # create transform component
    wgs84_to_utm_transform = osr.CoordinateTransformation(wgs84_coordinate_system, utm_coordinate_system) # (<from>, <to>)
    return wgs84_to_utm_transform.TransformPoint(lon, lat, 0) # returns easting, northing, altitude

I also found that if you've already got django/gdal installed and you know the EPSG code for the UTM zone you're working on, you can just use the Point() transform() method.

from django.contrib.gis.geos import Point
utm2epsg = {"54N": 3185, ...}
p = Point(lon, lat, srid=4326) # 4326 = WGS84 epsg code
p.transform(utm2epsg["54N"])

How to convert from UTM to LatLng in python or Javascript - Stack Over...

javascript python gis arcgis-js-api proj4js
Rectangle 27 2

Your current issue is that you are trying to change the app_label and db_table, which ends up changing the location of the model data within the database. By default, the database table is generated as [app_label]_[model_name] (backend_transportationrequest in your case), so when you modify both of these, South detects that the model has been removed and created again, even if this isn't actually the case.

The Django migrations framework introduced in 1.7 should have fixed this, so it detects that the model was moved (instead of deleted and created). You may need to fake a migration along the same lines as this with south, which can be done by modifying the two mgirations it generates to not actually delete and create the tables, but rename them.

Django does not currently allow you to easily do this, as the admin site expects that each application that is registered has a unique app_label. You may have luck playing with the label property of your AppConfig, but this is specifically not recommended and has been historically known to cause massive headaches.

One possibility may be to create a clone of your previous model, and only use it to register the app with the Django admin. You would need to create a proxy model with the custom app_label and db_table. If this didn't work (though it should), the other option would be to clone the model as a unmanaged model using the app_label and db_table.

python - How to move models in other section in django admin tool? - S...

python django django-admin
Rectangle 27 2

Try changing name of the view to include application and model names:

...
my_urls = patterns('', url(r'^settings/([A-Za-z0-9]*)',
                   self.admin_site.admin_view(self.settings), 
                   name="common_variable_settings"))
...
admin_urlname
@register.filter
def admin_urlname(value, arg):
    return 'admin:%s_%s_%s' % (value.app_label, value.module_name, arg)

So definitely You need to name Your view "appname_modulename_settings". Maybe then try changing regular expression to something like this:

r'^settings/([A-Za-z0-9]+/)?$'

Actually I tried this way but it didn't work. I think this is not the expected behaviour though.

python - How to reverse a custom admin url in Django 1.5? - Stack Over...

python django django-admin django-urls
Rectangle 27 5

You can do something like this

import traceback 
from django.http import HttpReponse

def view(request):
     try:
          #throw exception
     except:
         tb = traceback.format_exc()
         return HttpResponse(tb)
    # normal flow

How to catch any exception in python and print stack trace (DJANGO) - ...

python django
Rectangle 27 3

You need to read the very good documentation on Django forms.

At no point in your code are you passing the values of the POST request to the form. Also, you're not doing anything to get the date out of the form. So, not surprisingly, your code doesn't work.

mydate = now.date().isoformat()
if request.method == 'POST':
    form = DateRangeFrom(request.POST)
    if form.is_valid():
        mydate = form.cleaned_data('data_input')

Also, you need to set a name attribute for the field your HTML. Although since you've defined a form, you should be using that:

<form action = "" method="POST">{% csrf_token %}
    {{ form.data_input }}
    <input type="submit">
</form>

How to pass jquery datepicker from template to view in python Django? ...

jquery python mysql django datepicker
Rectangle 27 2

To display the ISBN you could make a custom field like this:

class BooksField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.isbn

There's a CheckboxSelectMultiple for the ManyToManyField but it doesn't display correctly on the admin, so you could also write some css to fix that.

You need to create a form for the model, and use that in your admin class:

class AuthorForm(forms.ModelForm):
    books = BooksField(Book.objects.all(), widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Author

    class Media:
        css = {
            'all': ('booksfield.css',)
        }

class AuthorAdmin(admin.ModelAdmin):
    form = AuthorForm

python - In Django Admin, I want to change how foreign keys are displa...

python django django-admin django-widget
Rectangle 27 3

An easy way it's printing in a script tag: script var value = {{ value|escapejs }}; /script Edited: If you need this var in a separated file you need make a view for render the js file. share|improve this answer edited Nov 15 '13 at 7:30 answered Nov 15 '13 at 7:11 Carlangueitor 377114

He wants it in his pre-existing scripts which are separately stored from the templates.

namespace.value = value || null;

No, no. Never couple JavaScript with Django template language. Makes the code really tightly coupled plus this way clutters the global namespace (window), which is something you really don't want.

@Carlangueitor - Firstly, Its not working, and yes as Ashish said, I want it in a separate JS file.

SyntaxError: invalid property id 	  var a = {{ value|escapejs}};

javascript - how to get a python variable in JS Django - Stack Overflo...

javascript python django
Rectangle 27 5

and then in the query which is calling the resource add

http://your.query/?postTime__lte=<SOME DATE>&postTime__gte=<SOME DATE>

You can also choose

filtering = {
   "postTime": ['lte',],
}

with a proper query.

@PiotKochaniski, this wasn't exactly what I was looking for however I did find a much easier solution. I'm going to post the answer below, hopefully you can check it out! Thanks for your help!

How to filter an object based on a DateTimeField range in Python (Djan...

python django datetime filtering tastypie
Rectangle 27 4

After spending hours fiddling with different solutions, I finally found one that works. What I did was, instead of doing the filtering from the queryset I did the filtering in object_get_list Here is my solution. Also make sure you have the proper imports as well

from datetime import datetime, timedelta

 RecentPosts(ModelResource):
 class Meta:
      queryset= Post.objects.all()
      resource_name = 'recent-posts'
      fields = ['id','postTime']
      authentication = BasicAuthentication()
      authorization =DjangoAuthorization()
      serializer = Serializer(formats=['json'])
      include_resource_uri = False
      filtering = {
                        'postTime': ALL,
                        'description': ALL,
      }
 get_object_list(self, request):
      return super(RecentPosts, self).get_object_list.filter(postTime__range=(datetime.now() - timedelta(days=3), datetime.now()))

This will return all objects created from the current date to all the objects from 3 days ago. Try this solution out and let me know if it works for you.

That's cool idea. I am only wondering if this is "idiomatic Django" (not that I care so much about such things ;)). People use also for that apply_filters (see for instance stackoverflow.com/questions/11436229/)

How to filter an object based on a DateTimeField range in Python (Djan...

python django datetime filtering tastypie
Rectangle 27 2

<input type="hidden" class="hidden" value="{{ value }}" />
var val = document.querySelector(".hidden").value;

or you can put it in any html element and query for the value.

a useful approach is to stick it on a data- attribute. usually when you want to do this the value is related to a particular DOM element anyway.

Apart from when using the data- attribute and you update it via jQuery (for example) then the original value is cached by jQuery so that's a bummer.

javascript - how to get a python variable in JS Django - Stack Overflo...

javascript python django
Rectangle 27 2

You can create a custom middleware class where you can catch all exceptions:

class ErrorMiddleware(object):
    def process_exception(self, request, exception):
        # send error
        return HttpResponse(...) # or None

and put it on first place to MIDDLEWARE_CLASSES tuple in settings.py.

Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the template response and response middleware will be applied, and the resulting response returned to the browser. Otherwise, default exception handling kicks in.

How to catch any exception in python and print stack trace (DJANGO) - ...

python django
Rectangle 27 1

raw_id_fields = ['books']

Check here: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin for instructions on creating a custom ModelAdmin class. I've thought about this a lot myself for my own Django project, and I think 1) would require modifying the admin template for viewing Author objects.

python - In Django Admin, I want to change how foreign keys are displa...

python django django-admin django-widget
Rectangle 27 1

data_input = forms.DateField(auto_now_add=True, widget=forms.DateInput(attrs={'class':'datepicker'}))

How to pass jquery datepicker from template to view in python Django? ...

jquery python mysql django datepicker
Rectangle 27 1

and you should also make a 500 error page at web server level (apache / nginx) just in case the framework doesn't work.

That way you can "catch" all errors and show a nice error message to the client.

How to catch any exception in python and print stack trace (DJANGO) - ...

python django
Rectangle 27 0

Use codecs.iterdecode() to decode the object on the fly:

from codecs import iterdecode

for line in iterdecode(filename, 'utf16'): yield line

Python/Django: How to convert utf-16 str bytes to unicode? - Stack Ove...

python django unicode encoding utf-16
Rectangle 27 0

To display the ISBN you could make a custom field like this:

class BooksField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.isbn

There's a CheckboxSelectMultiple for the ManyToManyField but it doesn't display correctly on the admin, so you could also write some css to fix that.

You need to create a form for the model, and use that in your admin class:

class AuthorForm(forms.ModelForm):
    books = BooksField(Book.objects.all(), widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Author

    class Media:
        css = {
            'all': ('booksfield.css',)
        }

class AuthorAdmin(admin.ModelAdmin):
    form = AuthorForm

python - In Django Admin, I want to change how foreign keys are displa...

python django django-admin django-widget