spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » DJANGO » Page 1
Django model - changing options in a choices field and migrate
After you change your fields you should run: $ python manage.py makemigrations your_app_label $ python manage.py migrate (This work for Django 1.7 where South are included into Django package) In case of Django 1.6: pip install South -python manage.py schemamigration your_app_name --initial -python manage.py migrate your_app_name make change to your model manage.py schemamigration your_app_

Categories : Django

How to create field name in django models with hyphen?
You can set or refer to the name of the column in your relational database from the model with the db_column argument: call-limit = models.IntegerField(default=1, db_column='call-limit', verbose_name='call-limit') But the model name in your Python code must be a valid Python identifier, so cannot contain the hyphen. Why not use call_limit instead? See the docs

Categories : Django

Add javascript to django admin site
Try a couple of things: MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') (function ($) { $(document).ready(function ($) { $("h1").css("background-color","red"); }); })(django.jQuery);

Categories : Django

Dynamic Flatpage per Model instance
take a look at the flatpage model. It has a textfield for its content. https://github.com/django/django/blob/master/django/contrib/flatpages/models.py In your code, you can store any content and store it in the textfield. ( I will store it as json string ) Then in your template, you can parse that string into json and use it. Depending on your front end editor, you should can always parse t

Categories : Django

Django rest framework disable field update after condition
I think Advanced serializers will do what you want. Just create your custom serializer and in your view, check the value of checkfield. If it's true, pass it the text argument so it enables the field in the serializer. Btw, since you only need one fixed extra field to be removed or added, instead of passing the fields argument as in the example, you can pass it something like enable_text=checkfi

Categories : Django

How to add custom JS to Django model admin
You can rewrite django/contrib/templates/admin/change_form.html {% extends "/admin/change_form.html" %} {% block extrahead %}{{ block.super }} <script type="text/javascript" src="..."></script> {% endblock %}

Categories : Django

Django 1.5.5 to django 1.7 migrate error
better late than never ;-) see https://code.djangoproject.com/ticket/22526, look for check() method in your server model and change name

Categories : Django

Django stops working with RuntimeError: populate() isn't reentrant
It's not a response but a reflexion. When you upgrade to django 1.7 and you have a 500 error and reload your page, Apache says "pupulate() isn't reentrant". I think it's when you load your page, Apache load all the modules you need for your app and when the error is handle it doesn't unload module. So, when you reload your page, apache load again theses modules but it's already loaded. So, apach

Categories : Django

accessing model manager methods in datamigration
Looks like this is not possible. From the South documentation: You can do a lot more with this inside a data migration; any model can be available to you. The only caveat is that you won’t have access to any custom methods or managers on your models, as they’re not preserved as part of the freezing process (there’s no way to do this generally); you’ll have to copy any code you

Categories : Django

Django Query find most recent item in past or future
Closest in the future: next = Product.objects.filter(categories__name='Subscription').filter(name__gt=date.today()).order_by("name")[0] Closest in the past: current = Product.objects.filter(categories__name='Subscription').filter(name__lt=date.today()).order_by("-name")[0] See https://docs.djangoproject.com/en/dev/ref/models/querysets/#field-lookups Note that you don't need the all() before

Categories : Django

Implement token based auth using tastypie apikeyauthentication
I don't know any built in functionality into tastypie that lets you do it (which I assume will require some scheduled task), but I think you can use the following answer to limit the api key by time, and generate a new one if needed: Tastypie auto log out hope this helps.

Categories : Django

django - check which fields have only null values
If I've understood you correctly, first case is - fetch only that objects, in which every field is Null: qs.filter(**{'{0}__isnull'.format(field.name): True for field in self.model._meta.fields}) And second case - fetch only that objects, in which at least one field is not Null: from django.db.models import Q qs.filter(reduce(lambda res, x: res | x, map(Q, [('{0}__isnull'.format(field.name),

Categories : Django

Authenticate a user on a GET API end point
Why do you pass auth details in the URL? You have a Basic Auth section in POSTMAN, where you can put you login credentials. POSTMAN will then set the correct headers for you. Remember to set BasicAuthentication as your auth class in DRF view or settings.

Categories : Django

How to filter between two databases?
I made this: f1 = MyModel.objects.using('old').all() pids = [p.id for p in f1] f2 = MyModel.objects.exclude(id__in=pids).filter() But I don't know if it is good.

Categories : Django

django photologue on webfaction
keep in mind tmp/ is a directory .. This directory contains mostly files that are required temporarily Access your dedicated server using terminal and access the folder using cd /tmp . After using touch to create new file >touch PHOTOLOGUE_NO_PILLOW

Categories : Django

Is there a way to force an immidiate HttpResponse from a class based FormView method (eg. get_initial)?
The view's dispatch method is what returns an HttpResponse. You could always raise an exception that won't be handled elsewhere and catch it there. It should just bubble up until it gets there. Ex. #place where you want to raise exception if condition.is_not_met: raise WoahException #views.py class MyFormView(views.FormView): def dispatch(self, request, *args, **kwargs): try:

Categories : Django

Django, Custom Managers affect save method?
To make admin page work with a different manager, you can implement get_queryset method on your ModelAdmin class. class StoryAdmin(ModelAdmin): def get_queryset(self, request): return self.model.full_set.get_queryset()

Categories : Django

400 Error on certain routes (Django + gunicorn + nginx)
You are missing a semicolon after the server_name directive. Error 400 with nginx is usually related to a configuration error causing incomplete or wrong data being passed to the application. This hypothesis is reinforced by your statement that under apache it works fine. You should thus run gunicorn with a high log level (--log-level debug) and see what it gets passed by the web server. See the

Categories : Django

Contributing to Django
Here take a look at this from the Django Docs. It talks about how to start contributing. And here is the contributing.rst file from the Django github

Categories : Django

accessing uncleaned form data in form.py in django using clean() method
If you use ModelForm, then you should directly get the object which is related by the foreignkey. So what you can do in cleaned data is: def clean(self): p_key= self.cleaned_data['private_key'] institute= self.cleaned_data['institute'] if p_key == institute.private_key : return super().clean() else: raise ValidationError('Invalid key') If you are using Form, then

Categories : Django

Add datetime object without timezone
settings.py CONST USE_TZ USE_TZ Default: False A boolean that specifies if datetimes will be timezone-aware by default or not. If this is set to True, Django will use timezone-aware datetimes internally. Otherwise, Django will use naive datetimes in local time. The default settings.py file created by django-admin.py startproject includes USE_TZ = True for convenience. So, you can c

Categories : Django

django social auth facebook login
Try python-social-auth and have a look at this tutorial. I dont like posting the whole code.. http://www.artandlogic.com/blog/2014/04/tutorial-adding-facebooktwittergoogle-authentication-to-a-django-application/ Enjoy...

Categories : Django

django-rest-framework: serializer from DATA don't update model ID
By default, the id field that is automatically generated by Django REST Framework is read-only. Because of this, the id will always be none and it will try to create a new Category if there isn't already one attached. You can override this by adding you own id field to the serializer that is not read-only. class CategoryCreationSerializer(serializers.ModelSerializer): id = serializers.Intege

Categories : Django

Django admin objects permissions
django-moderation looks interesting, I haven't used it. There's not a lot of activity in the project, but it's active. I think it will suit the use-case you have in mind. I considered django-guardian recently for a project and rejected it in favour of extending tastypie's authorizations. I think my use case was a bit different, I needed to maintain constraints on foreign key relationships that

Categories : Django

Clould9's Django out of the box: Admin page CSRF :443 error
I have opened a ticket for this issue with the cloud9 support @eff M. They are great guys out there and great IDE as well with great support. Meanwhile try this workaround for the time being: access your admin page with http://mysite.c9.io/admin/login/?next=/admin/ and not with https://mysite.c9.io/admin/login/?next=/admin/ and see if you can login. it worked well on my side.

Categories : Django

Django Model Latest Foreign Key Record
You can use latest(): Snippets.objects.filter(user=request.user).latest('revision__created_at')

Categories : Django

Django 1.7.1 Makemigrations fails when using lambda as default for attribute
The migrations documentation addresses this: Migrations are just Python files containing the old definitions of your models - thus, to write them, Django must take the current state of your models and serialize them out into a file. While Django can serialize most things, there are some things that we just can’t serialize out into a valid Python representation.... Django can serialize t

Categories : Django

One Django Project, Multiple Settings.py
you dont need to set two AUTH_USER_MODEL = 'myapp.MyUser' 's or two settings for this purpose which probabyly would work but this is not the level this logic belongs to. (settings is already in deployment level e.g. running multiple websites on the same codebase and same databse etc etc...) what I would recommend is something simple: # settings.py AUTH_USER_MODEL = 'yourapp.CustomUser' # youra

Categories : Django

Django ImageField widget to add thumbnail with clearable checkbox
I solved my problem recoding the AdminImageWidget as following: from django.utils.safestring import mark_safe from django.utils.html import escape, conditional_escape from django.utils.encoding import force_unicode from django.forms.widgets import ClearableFileInput, Input, CheckboxInput class AdminImageWidget(ClearableFileInput): def render(self, name, value, attrs=None): substitut

Categories : Django

Detect empty formset in template
I just found the answer by myself... It works with formset.forms: {% if formset.forms %} {{ formset }} {% else %} <p>Nothing to show</p> {% endif %}

Categories : Django

Error NoReverseMatch on Reverse Django URL
The regex appears incorrect for matching the argument 'test'. If we take a look at the regex (/w{2}/|/), It appears to be capturing two groups which are separated by an 'OR' (|) operator. The first group is /w{2}/. This is only going to match '/' followed by w only 2 times followed by '/'. The second group is only matching '/'. 'test' doesn't match either one of these cases so it raises an ex

Categories : Django

Get Featured Image from different Model
businessimage_set is an attribute of a Business instance, but you're trying to access it as an attribute of a queryset (i.e. list of businesses). If your goal is just to be able to access the images for each business in a template, you can leave out images entirely. Instead your template would have: {% for image in business.businessimage_set.all %} (Though look into prefetch_related for efficie

Categories : Django

How to serve static files with django that has hardcoded relative paths on Heroku/OpenShift/etc?
Storing static/media files on Heroku's servers is problematic and discouraged. There are workarounds but it's easier to use an alternative to host these. Plus, when a dyno is respun the files on Heroku will be erased. Instead, use a web service to store your files. These files are collected via collectstatic (which runs each time you push to Heroku), this is expected behavior. For both ease of u

Categories : Django

session.get_expiry_age() never decreases
Yes, this is the intended behaviour. See this ticket: https://code.djangoproject.com/ticket/18458 You can use get_expiry_date() instead and calculate it from there.

Categories : Django

Django pre_delete model method executing unexpectedly
Specify sender of signal in @receiver definition: @receiver(pre_delete, sender=Item) def copy_item_details(sender, instance, **kwargs): """ :param sender: :param instance: :param kwargs: :return: """ #Some code NOTE: Signals should be placed in signals.py not in model. According to Django docs: "Strictly speaking, signal handling and registration code can live

Categories : Django

align field on django-crispy forms horizontally to centre of page?
The crispy forms documentation shows how to do horizontal forms for bootstrap, perhaps that will help. http://django-crispy-forms.readthedocs.org/en/latest/crispy_tag_forms.html?highlight=horizontal#bootstrap3-horizontal-forms

Categories : Django

Django - allow url only to be accessed from a specific page
You can use the referer header (request.META['HTTP_REFERER'])to determine which page the user came from. Your view can read this header and deny access if it doesn't exist / redirect back to your terms page. For something a bit more reliable, if you're already using session data, you can store a flag in the session upon the user clicking the "agree" button on the terms page. Perhaps that does a f

Categories : Django

Custom queryset after POST request in TastyPie
You should use GET only to get data HTTP convention. All the methods are meant for some purpose to keep it simple and specific. It always helps in debugging logs. If you still want to use POST to get some data. You can use below example. class ModelResource(Resource): class Meta: resource_name = 'api' detail_allowed_methods = ['post'] authorization = Authorization()

Categories : Django

django: Could not import settings.py
Usually the No module named exception doesn't contain a path, but a module name (with dots). Try to figure out why you get a path, check your DJANGO_SETTINGS_MODULE environment var.

Categories : Django


Recently Add
Django, using two databases with the same project
Django model - changing options in a choices field and migrate
How to create field name in django models with hyphen?
Add javascript to django admin site
Dynamic Flatpage per Model instance
Django rest framework disable field update after condition
How to add custom JS to Django model admin
Django 1.5.5 to django 1.7 migrate error
Django stops working with RuntimeError: populate() isn't reentrant
accessing model manager methods in datamigration
Django Query find most recent item in past or future
Implement token based auth using tastypie apikeyauthentication
django - check which fields have only null values
Authenticate a user on a GET API end point
How to filter between two databases?
django photologue on webfaction
Is there a way to force an immidiate HttpResponse from a class based FormView method (eg. get_initial)?
Django, Custom Managers affect save method?
400 Error on certain routes (Django + gunicorn + nginx)
Contributing to Django
accessing uncleaned form data in form.py in django using clean() method
Add datetime object without timezone
django social auth facebook login
django-rest-framework: serializer from DATA don't update model ID
Django admin objects permissions
Clould9's Django out of the box: Admin page CSRF :443 error
Django Model Latest Foreign Key Record
Django 1.7.1 Makemigrations fails when using lambda as default for attribute
One Django Project, Multiple Settings.py
Django ImageField widget to add thumbnail with clearable checkbox
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.