Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elastic Beanstalk is not seeing changes in DATABASES setting - Django
I've noticed this on a couple of occasions now, and am not sure what is going on. Context: deploying a Django app on Elastic Beanstalk with postgresql 9.5. Problem: when connecting to the database using the RDS environment variable, I accidentally look for "RDS_USER" rather than "RDS_USERNAME" in settings.py. This, naturally, throws a KeyError for "RDS_USER". However, if I change this to the proper value, commit the changes and re-deploy, it seems to not pick up the changes. I still get the same KeyError for "RDS_USER" when trying to run a migration. Has anyone else experienced this? Am I making a stupid mistake (distinct possibility)? settings.py: if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD' : os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT':os.environ['RDS_PORT'] } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '*****', 'USER':'*****', 'PASSWORD':'*****', 'HOST':'localhost', 'PORT':'' } } -
csrf cookie not set django rest
When working on REST browsable API the responses work fine but when I started working on postman to integrate with front end on the other side the respond become: { "detail": "CSRF Failed: CSRF cookie not set." } I tried everything to solve this error but nothing change, and checked every question here on CSRF token but still didn't work These are my codes: views.py: from django.shortcuts import render from django.http import JsonResponse from rest_framework.response import Response from rest_framework import status from User.serializers import UserDataSerializer, ImageSerializer from rest_framework.views import APIView from rest_framework import generics from User.models import UserData,Image from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from rest_framework.renderers import TemplateHTMLRenderer from django.views.decorators.csrf import csrf_exempt @csrf_exempt class Signup(APIView): def post(self, request, format = None): serializer = UserDataSerializer(data = request.data) if(serializer.is_valid()): user = User.objects.create_user( username = serializer.data['username'], first_name = serializer.data['first_name'], last_name = serializer.data['last_name'], email = serializer.data['email'], password = serializer.data['password'], ) #add the name because it is not with create_user method # user.name = serializer.data['name'] # user.save() login(request, user) print ("logged") text = {'valid' : True , 'errors' :"ur password"+serializer.data['password']} return JsonResponse(serializer.data) else: return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Login(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) … -
moving django static files to aws S3
In my Django app, I moved my static and media files to aws S3 bucket. Also, I deploy the app with elastic beanstalk. However, when I opened the admin page, it doesn't recognize static files. I am sure, static files uploaded to s3. I used following configurations; AWS_STORAGE_BUCKET_NAME = 'bucket_name' AWS_ACCESS_KEY_ID = 'xxxxxxxxxxxxxxxx' AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxxxxxxx' AWS_S3_CUSTOM_DOMAIN = '%s3-us-west-2.amazonaws.com' % AWS_STORAGE_BUCKET_NAME MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'appName.custom_storages.MediaStorage' STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'appname.custom_storages.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) //custom_storages.py from django.conf import settings from storages.backends.s3boto import S3BotoStorage class MediaStorage(S3BotoStorage): location = settings.MEDIAFILES_LOCATION class StaticStorage(S3BotoStorage): location = settings.STATICFILES_LOCATION -
Django Created By and Modified By in an Abstract Base Class
I want to create an Abstract Base Class that other models inherit to track some basic information (Created_Date, Mod_date, Created_by, Mod_by, etc) here is an example of what I would like: class MetaDataModel(models.Model): added_by = models.ForeignKey(settings.AUTH_USER_MODEL, ) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: abstract = True However, when I use this class in more than one other model I receive an error telling me: takeoffs.Takeoff.added_by: (fields.E304) Reverse accessor for 'Takeoff.added_by' clashes with reverse accessor for 'InputTakeoffItem.added_by'. HINT: Add or change a related_name argument to the definition for 'Takeoff.added_by' or 'InputTakeoffItem.added_by'. across all models it's implemented in. How can I create a ABC to track both who created and last modified an Item? -
KO: Error when parsing JSON
I'm creating my first REST-powered website. The backend is in Python (Django), and seems to be working fine. I'm trying to make the front-end get the comments for the posts, but its not working. function Comment(data) { this.body = ko.observable(data.responseText) } function Post(data) { this.title = ko.observable(data.title) this.body = ko.observable(data.body) var self = this; self.comments = ko.observableArray([]) self.comments(($.map(data.comments, function(link) { // Map the data from return $.getJSON(link, function(data) { return new Comment(data)}) //These requests }))) } function PostViewModel() { // Data var self = this; self.posts = ko.observableArray([]) // Get the posts and map them to a mappedData array. $.getJSON("/router/post/?format=json", function(allData) { var mappedData = $.map(allData, function(data) { return new Post(data)}) self.posts(mappedData) }) } ko.applyBindings(new PostViewModel()); Server data: [{ "title":"-->Title here<--", "body":"-->Body here<--", "comments":[ "http://127.0.0.1:8000/router/comment/6/?format=json", "http://127.0.0.1:8000/router/comment/7/?format=json", "http://127.0.0.1:8000/router/comment/8/?format=json", "http://127.0.0.1:8000/router/comment/9/?format=json"] }] where one of the links leeds to: {"body":"-->Body here<--"} <div class="col-lg-7" data-bind="foreach: { data: posts, as: 'posts' }"> <h3 data-bind="text: title"></h3> <p data-bind="text: body"> </p> <span data-bind="foreach: { data: comments(), as: 'comments' }"> <p data-bind="text: comments.body"></p> </span> </div> (There is a lot more HTML, but i removed the irrelevant parts) Everything is working fine, except from that the comments seem to be in the wrong format. The chrome console shows JSON … -
Set object-level permission with django-rest-framework
Trying to manage django-guardian object-level permissions with django-rest-framework the most cleanly and canon possible. I want to assign a read permission (module.view_object) of an object to to the user making the request when performing a POST. My class-based view: class ObjectList(ListCreateAPIView): queryset = Object.objects.all() serializer_class = ObjectSerializer filter_backends = (DjangoObjectPermissionsFilter,) # MyObjectPermissions inherit from DjangoObjectPermissions and just # add the 'view_model' permission permission_classes = (MyObjectPermissions,) def perform_create(self, serializer): serializer.save(owner=self.request.user) As described in the django-rest-framework documentation, I've overloaded perform_create in order to pass the user to the serializer. But how do I assign the permission (using guardian.shortcuts.assign_perm) in the serializer. Is there no other way but to override the save method to assign the permission manually? Isn't there some kind of standard mechanism to manage a common behavior as this one? -
How to calculate diff between two dates in django
I want to calculate days difference between current date and previous date. i am trying this code requiremntObj = CustomerLeads.objects.all() a = datetime.datetime.now().date() for i in requiremntObj: date1=i.posting_date diff = a-date1 print diff I got a error unsupported operand type(s) for -: 'datetime.date' and 'unicode' For current date i am getting datetime object and for date1 i am getting unicode. -
Formset initial choice field
I have a form (working correctly) which I want to pass to a Formset, but the tuples Im passing for the ChoiceFields are not rendered or have a error: This is the original form: class PO_Form(forms.Form): def __init__(self, baseItem_choices, color_choices, material_choices, sizeGroup_choices, *args, **kwargs): super(PO_Form, self).__init__(*args, **kwargs) self.fields['base_item'].choices = baseItem_choices self.fields['color_or_print'].choices = color_choices self.fields['material'].choices = material_choices self.fields['size_group'].choices = sizeGroup_choices base_item = forms.ChoiceField(choices=(), required=True) color_or_print = forms.ChoiceField(choices=(), required=True) material = forms.ChoiceField(choices=(), required=True) size_group = forms.ChoiceField(choices=(), required=True) this form ChoiceFields are populated from various lists of touples which I create in a view: form = PO_Form(baseItem_choices, color_choices, material_choices, sizeGroup_choices) How I make this work in a formset? I tried two approaches: 1: PO_FormSet = formset_factory(PO_Form(baseItem_choices, color_choices, material_choices, sizeGroup_choices), extra=2) I get this Error: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/carlospceballos/Dropbox (Personal)/django/projectos/WholeSale/ShowRoom/views.py" in PO_formset_populate 115. PO_FormSet = formset_factory(PO_Form(baseItem_choices, color_choices, material_choices, sizeGroup_choices), extra=2) File "/Library/Python/2.7/site-packages/django/forms/formsets.py" in formset_factory 449. return type(form.name + str('FormSet'), (formset,), attrs) Exception Type: AttributeError at /showroom/po_populate/3/ Exception Value: 'PO_Form' object has no attribute 'name' 2: I tried setting the initial values in the view: PO_FormSet = formset_factory(PO_Form(), extra=2) formset … -
celery exceptions creates .nfs0000* files
I have several celery tasks, that are operating on an nfs share over nfsv4 (netapp as backend). From time to time, I assume after an exception from a task is raised, .nfs0000* files appearing on the share and disapear only if I restart celery. I previously found this: Under linux/unix, if you remove a file that a currently running process still has open, the file isn't really removed. Once the process closes the file, the OS then removes the file handle and frees up the disk blocks. This process is complicated slightly when the file that is open and removed is on an NFS mounted filesystem. Since the process that has the file open is running on one machine (such as a workstation in your office or lab) and the files are on the file server, there has to be some way for the two machines to communicate information about this file. The way NFS does this is with the .nfsNNNN files. If you try to remove one of these file, and the file is still open, it will just reappear with a different number. So, in order to remove the file completely you must kill the process that has … -
django-allauth Redirect to Custom Page on Error
I have moved the django-allauth login/signup forms to a modal on a custom index page I created. Everything works if the login/signup forms are filled without error, except the issue now is that if the login fails, I am redirected to "/accounts/login/", and if signup fails, I am redirected to "/accounts/signup/". How can I override this behavior, so that I am always redirected back to 'ra_app:index'? settings.py LOGIN_URL = 'ra_app:index' LOGIN_REDIRECT_URL = 'ra_app:index' ACCOUNT_LOGIN_REDIRECT_URL = 'ra_app:index' ACCOUNT_LOGOUT_REDIRECT_URL = 'ra_app:index' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True # Used in conjunction with ACCOUNT_AUTHENTICATION_METHOD to ensure ability to login ACCOUNT_USERNAME_REQUIRED = False # Used in conjuction with ACCOUNT_AUTHENTICATION_METHOD to ensure ability to login ACCOUNT_LOGOUT_ON_GET = True # Logout without confirmation -
django DisallowedHost in the new version of django
Up until now I was using Django==1.9.6 in my vagrant machine inside a virtualenv. However I made a new virtual environment to test out the new django and installed the lates version of django (version 1.10.4). And didn't do anything, but just ran the server sudo python manage.py runserver 0.0.0.0:80 And when I tried to open the url, instead of Welcom to Django, I got an error: DisallowedHost at / Invalid HTTP_HOST header: 55.55.55.5 I have however corrected this by setting the ip of my vagrant machine (55.55.55.5) into the ALLOWED_HOST list. But, I just wanted to know whether this was implemented in the newer version of django or was this feature already in the previous versions of django but the error occured because of some bad configuration in my settings? Your help and guidance will be very much appreciated. Thank you. -
How to decorate admin actions in Django, action.__name__ used as dict key?
In order to avoid duplication, I decided to decorate some actions that I use within Django administration. The decorator is very simple - wraps the function, evaluates it, and in case of TransitionError shows the appropriate error message to the user. It also gets the short_description and applies it. def transition_action(short_description): def decorator(fn): def wrapped(modeladmin, request, queryset): try: return fn(modeladmin, request, queryset) except TransitionNotAllowed: message = _("Transition not allowed.") messages.error(request, message) wrapped.short_description = short_description return wrapped return decorator However, if that decorator is applied, then only the last action will be visible (from all where the decorator is applied). The reason is that the wrapped.__name__ will be used as key for actions dictionary (reference). Obviously, a way to workaround this behavior would be to set custom __name__, like that: wrapped.__name__ = short_description. I don't like this approach though, as it seems a bit hackish. Do you have some better approaches to apply decorations to actions? -
How to render html text from database inside a django template using template tags
I save a text into my database using django form, textarea widget and bootstrap wysiwyg, but when I try to render it into my template using just the variable name {{ text }}, I get rendered just the text with html tags like this: what I want to do is show the formatted text in html. -
'initial' is an invalid keyword argument for this function
i'm Getting this error "'initial' is an invalid keyword argument for this function", I'm trying to create an object by a createview, what is this error and why am I getting it ? urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^add/$', views.CriarTrabalhador.as_view(), name='add')] models.py from django.db import models # Create your models here. class Trabalhadores(models.Model): Nome = models.CharField('Name',max_length=100) Cpf = models.CharField(primary_key=True,max_length=11) Data = models.DateField('Data de Nascimento') def __str__(self): return self.Nome forms.py from django import forms from .models import Trabalhadores class TrabalhadoresForm(forms.ModelForm): class Meta: model = Trabalhadores fields = ["Nome","Cpf","Data"] views.py from django.shortcuts import render from django.views.generic.list import ListView from django.core.urlresolvers import reverse from .models import Trabalhadores from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView,CreateView from . import forms class CriarTrabalhador(CreateView): model = Trabalhadores form_class = forms.Trabalhadores template_name = 'mytemp/adicionartrabalhador.html' def get_success_url(self): return reverse('trabalhadores') -
How can I access Django model data when handling signals?
I am confused by the data I receive when handling pre-save and post-save signals in Django. Is there any generic way to obtain the model data in the callback function? As a workaround, I've created a model_data property for all my models, returning a dictionary with all fields. But I wonder if I am reinventing the wheel. class Album(models.Model): added_by = models.ForeignKey('auth.User', related_name="+", null=False, default=None) creation_timestamp = models.DateTimeField('when added', auto_now_add=True) modification_timestamp = models.DateTimeField('when modified', auto_now=True) description = models.TextField('description', default='', null=True) number = models.IntegerField( 'number', default=None, null=False, unique=True, validators=[MinValueValidator(1), MaxValueValidator(999)] ) def __str__(self): return str(self.number) @property def model_data(self): return { 'number': self.number, 'description': self.description, 'author': self.added_by.__str__() } ... @receiver(pre_save) def pre_save_callback(sender, instance, raw, using, update_fields, **kwargs): try: logger.debug( 'Pre-save called for %s, data: %s', sender, json.dumps(instance.model_data) ) except: pass -
Using @processor_for with a Form in Mezzanine
I've built a Form Page in the admin of my Mezzanine project, but I'd like to populate a couple of the fields automatically, depending on where the click to the form has come from: it's a "feedback" form and I'd like to automatically add the ID of the object that the user is providing feedback on to a hidden field in the form. I've copied the template code from mezzanine/forms/templates/pages/form.html to a custom template and it receives the dictionary I pass it from my view, but I can't work out to pass it my the form I want rendered. The @processor_for function receives request and page... but where's the form? What should I be passing tom -
Django non primary_key AutoField
We're migrating and making necessary changes to our Oracle database, one major change is that we're adding an UUIDField as primary_key to all models(hidden to the client), and(trying to add) a regular AutoField. We found that displaying the primary_key directly to our clients wasn't good design, but they also requested an ID field displayed to reference objects more easily, but Django limits this by not allowing AutoField to NOT be the primary_key Is there a workaround for this issue? -
Django get queryset as serialized
In Django, if you do the following: print(serializers.serialize(MyModel.objects.all())) It will nicely output a JSON string in this format: { {'pk' : 1, fields : {'fieldname1' : 'value1, 'fieldname2', 'value2'}, } This is usefull when you're dealing with a 'generic' application that would work with any model, not needing to know the pk field name or the list of non-hidden non-relational field names. For the question, how can I do this but keep it in Python, as a dictionary? I could json.loads the serializer output but that's just plain silly. Closest to what I'm trying to achieve is the .values() QuerySet method, but it doesn't list the pk field -
Trying to implement a passwordless authentication using Redis and random tokens
I want to implement a passwordless email based authentication (like in medium.com!), now I want to verify if this logic flow is secure or not: User submits his email Server generates a random token, sets to Redis a new value where the KEY is the token, the VALUE is the email or the corresponding user id, also make the key expires within an hour or some soon future value (within tens of minutes or hours), send a link including the token to the user email (i.e. example.com/login/token/{TOKEN}) User visits his inbox and press on that link Server checks for {TOKEN} key, if it exists, authenticate the user and redirect to homepage, if not redirect to some error page. Is this approach secure, is there something hidden I can't figure out yet? Also Note that this method authenticate the user with only GET methods. I use Django/Python, so if there is some package doing that, what is it? Also is it relevant and secure for new user registrations/password-change/other user checks? Is there impact in case of DDoS attacks like making my server spam random emails, consuming the server using having a big Redis memory consumption in short time? For token generation, … -
Relationship between two models Django/python
I got two models and I need to get data from one table(model) to another, my logic works but it takes a while (around 5 minutes) this is because Times Table has around 90,000 data lines. I will post my two models first and then the logic I use to relate and to se what I get from the Times table: Model 1: class otreport(models.Model): sales_order_shipset = models.CharField(max_length=30) wms = models.CharField(max_length=50) status = models.CharField(max_length=200) aging = models.DateField(null=True, blank=True) carrier = models.DateField(null=True, blank=True) add_date = models.DateTimeField(null=True, blank=True) asn_validation = models.DateTimeField(null=True, blank=True) docs_add_date = models.DateTimeField(null=True, blank=True) po_number = models.CharField(max_length=20, unique=True) Model 2: class Times(models.Model): external_order = models.CharField(max_length=20) planning_order = models.CharField(max_length=20) wms_order = models.CharField(max_length=40) customer_id = models.CharField(max_length=50) service_level = models.CharField(max_length=100) state = models.CharField(max_length=5) status_date = models.DateTimeField(null=True, blank=True) order_date = models.DateTimeField(null=True, blank=True) order_add_date = models.DateTimeField(null=True, blank=True) asn_sent_time = models.DateTimeField(null=True, blank=True) docs_received_time = models.DateTimeField(null=True, blank=True) docs_processing_time = models.CharField(max_length=100) This is my logic, what it happens (to do it faster I used a list to do not re read the sale po_numbers) and relate the external order with the sales order to get the info I want: def import_times(request): print "Import data from Times to OT" po_cache = list() for item in otreport.objects.all(): if item.po_number in … -
get related object but not via foreign key
I have the following models in my django app. class EndUser(models.Model): end_user_id = models.CharField class EndUserField(models.Model): name = models.CharField value = models.CharField user = models.ForeignKey("EndUser", null=False, verbose_name=_('end user')) An EndUser can have many EndUserFields. In some situations, if a certain EndUserField is queried, I would like to be able to fetch another field. I tried the following, but it does not work: ( EndUserField.objects .filter(name='x') .select_related('user') .prefetch_related( Prefetch( 'user__enduserfield_set', queryset=( EndUserField.objects .filter( name='y' ) ), to_attr='user_name' ) ) ) -
Terminate django runserver subprocess
I'm trying to to run django's server on a python script. Then run some Django logic to scrape some of my own generated html. However, I can't get the program to terminate after everything is done. I've tried sys.exit, process.terminate(), process.kill() but no luck. import subprocess process = subprocess.Popen(['python', 'django_run_server.py']) import time time.sleep(10) # scraping django HTML here # exit command here django_run_server.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "spellcheck_site.settings") from django.conf import settings from django.core.management import call_command from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # call_command('runserver', '127.0.0.1:8080') -
Get Django username to log signals
I am experimenting with logging in Django. I would like to log each occasion of users saving or modifying data. In my signal handler code, I have something like this: @receiver(post_save) def post_save_callback(sender, instance, created, raw, using, update_fields, **kwargs): logger.info( 'Post-save called for %s. Created? %r. update_fields: %s', sender, created, json.dumps(update_fields) ) I would also like to log the username of the user performing the data manipulation, basically—the currently logged in user. How can I get this username? -
How to create a multiplechoice form with models queryset?
The goal of this application is to let users select their favourite fonts using checkboxes and use the selected fonts somewhere else. The thing is that, all the fonts are entered through the Admin panel by the admin, so the form should be able to get it from there. This is what I thought doing : forms.py class ContactForm1(forms.ModelForm): choice = forms.MultipleChoiceField(choices=""" Get my models title as choice """, widget=forms.CheckboxSelectMultiple()) class Meta: model = ImageCheckView fields = ['title', 'choice'] ... models.py class ImageCheckView(models.Model): title = models.CharField(max_length=100, unique=True) ... What it will have to look like : (I want to keep the selected options so I can use it somewhere else.) How can I achieve the following ? -
How to Validate Django TimeField When Using jQuery TimePicker?
I have a Django form which contains a TimeField that I implement using the jquery.timepicker plugin. This plugin modifies an HTML text input control so that when it's clicked, it presents a pulldown list of times (e.g. 7:30pm, 8:00pm, 8:30pm, etc. with no space between the last digit and am/pm). The plugin works properly but Django won't validate the field when I select a time. It always says "Enter a valid time." when I submit the form. Here is my form and template: # timepicker.html <html> <head> <script src="js/jquery.timepicker.min.js"></script> <link rel="stylesheet" href="css/jquery.timepicker.css"> </head> <script> $(function() { $( "#id_start_time" ).timepicker(); }); </script> Time: <input type="text" name="start_time" id="id_start_time" value="" class="time"/> </html> # forms.py from django import forms class DateTimeForm(forms.Form): start_time = forms.TimeField(input_formats='%I:%M%p') Per other discussions on Stackoverflow regarding this issue, I also created a setting to tell Django what valid time formats look like using Pythons strftime() format directives: # settings.py TIME_INPUT_FORMATS = ('%H:%M', '%I:%M%p', ) I've looked at these four related SO questions 1, 2, 3, 4 and implemented the suggested solutions but my form still won't validate. How can I get this form to validate?