Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Nginx with gunicorn media files protection
Please do not downvote as this question does not have tried code. I am new to programming. So far have a built a big project on local machine. It will automate business workings. However now issue is, while deploying the app to server, Media files are not protected. I mean how to allow media files to be downloaded by logged in users only. As of now anyone with a link can download the file. In short question is: How to allow media files (user uploaded files) to be downloaded only by logged in users in NGINX? Google is not of much help here, need a working example with code. -
How to receive array in post data python
I'm trying to send array as a parameter to the api which is using python and django framework. Here's my client side code that is being used to access the api: $.ajax( type: 'POST', url: 'http://example.com/api/users', data: {ids:[1,2,3,4,5],type:'info'}, complete: function(response) { console.log(response); } ); Here's the view where I'm trying to access the request parameters get_users(request): print(request.POST.get('ids')) and when I try to access ids parameter, It gives None. If anyone has faced the same problem, please help me. -
Using different Authentication Backend based on url in Django single project
I use ModelBackend to authenticate regular user and LDAPBackend from admin panel. No regular user sould access admin panel and no admin user should access regular user interface. Currently I am following this steps to ensure it: [For admin authentication] Before login, first test if the username belong to regular user[query from database]. If yes, raise permission denied. Else proceed with authenticate and login function Doing the opposite for regular user authentication. Now the problem in this process is, I have to query user database each time, when an user tries to login. Is there any better and simple way to do it. It will be much simpler if authenticate function took additional modelbackend parameter. -
Django: 'NoneType' object has no attribute 'user'
I am using Django User model for one of the select field. However i am not able to pass only users linked to a commmon organisation/company. I have a onetoone profile linking for each user. This one to onetoone model is again linked to organisation model. Now need a form where select field should have users linked to organisation model. Here is my form.py: class taskaddform(forms.ModelForm): def __init__(self,user, *args, **kwargs): self.user = kwargs.pop('user', None) self.request = kwargs.pop('request', None) super(taskaddform, self).__init__(*args, **kwargs) self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity) class Meta: model=tasktable fields=('task','assigned_to','discription','documents',) views.py: @login_required def taskadd(request): if request.method=='POST': form=taskaddform(request.POST,request.FILES,request.user) if form.is_valid(): new_form=form.save(commit=False) new_form.created_by=request.user new_form.company=request.user.company.entity new_form.save() return HttpResponseRedirect(reverse('taskadd'),messages.add_message(request, messages.SUCCESS,'Task added succesfully.')) else: form=taskaddform(request.user) return render(request,'taskadd.html',{'form':form}) Error Log: Request Method: GET Request URL: http://127.0.0.1:8000/task/taskadd/ Django Version: 1.10 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'user' traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/task/taskadd/ Django Version: 1.10 Python Version: 2.7.10 Installed Applications: ('invoice', 'support', 'task', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'widget_tweaks') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: 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 _legacy_get_response 249. response = self._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 = … -
Django Rest Framework Serializer Model Custom Method with parameters
is it possible for a serializer field to have a source of a model custom method with parameters? Something like models.py class Sample(models.Model): name = models.CharField(max_length=100, default=None) def sample_method(self, param): if param == 'x': return 1 elif param == 'y': return 0 serializers.py class SampleSerializer(serializers.ModelSerializer): x = # serializer field that returns sample_method custom method with a parameter of 'x' y = # serializer field that returns sample_method custom method with a parameter of 'y' class Meta: model = Sample fields = ('x', 'y') It should return in the a response of something similar to: {'x': 1, 'y': 0} -
Django error impor models.py with root directory
Import the module root directory from root_d.api.models import APIkey Get this result ImportError: No module named api.models File init.py created in the root directory and in the application directory It is not clear why this problem occurs -
django how to access current requested user in custom method in admin
i have written a custom method in one of my admin.py file as follow, class OfferHeaderModelAdmin(admin.ModelAdmin): ................................ ................................ def cancel_offer_view(self, request, offer_id): user = request.user cancel_offer.user = request.user OfferService().offer_cancellation_by_admin(offer_id=offer_id, user=user) return HttpResponseRedirect( '/admin/offers/offerheader/') where i am trying to access the current logged in user where the user instance is referred to one of my other model Customer, in fact i have created that user from a user defined customer object manager namely create_superuser, everything is fine when i create a super user using that customer object manager, that is, the super user is creating and successfully storing in the Customer model,no problem with that. then i logged in into the django admin using that super user and when i try to access the current user using the following method namely cancel_offer_view, it raise `Cannot assign "(<SimpleLazyObject: <Customer: sup@sup.com>>,)": "OfferHeader.cancelled_by" must be a "Customer" instance.` don't confused with the OfferHeader.cancelled_by part from the error message,i have a cancelled_by attribute in my OfferHeader model ,here cancelled_by has a foreign key relationship with Customer model,where i am trying to save the current logged in admin user using one of the service method in my above custom admin method, if you have a closer … -
Django DateRangeField issue
I have a problem with DateRangeField inserting to database using Forms. model.py from django.contrib.postgres.fields import DateRangeField from django.db import models class Event(models.Model): name = models.CharField(max_length=200) datefromto = DateRangeField() forms.py class Event_form(forms.ModelForm): class Meta: model = Event fields = ('name','datefromto') views.py data = { "name" : "Test Name", "datefromto" : (date_from,date_to) } form = Event_form(data) if form.is_valid(): form.save() else: print(form.errors) When I call the form.is_valid() it returns "datefromto is required". Django 1.9,Python 2.7 and Postgre 9.3.14. -
How to control looping with Django and Java
I am trying to use the Django template to loop over a set of records, but stop one short, and then process the last one differentley. So lets say I have 50 records - I would want to loop over 1 to 49 and then stop, and then process the 50th outside the loop. I am trying to create [[date, var2],[date, var2],..[date, var2]*]; I am using: data.addRows([ {% for data in mydata %} [{{data.date}},{{data.var2}}], {% endfor %} ]); My aim is to NOT include the comma (indicated by the *) but to keep the required form. Any help would be appreciated. Thanks. -
I can't update mysql database using django?
class Person(models.Model): SHIRT_SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) name = models.CharField(max_length = 60) shirt_size = models.CharField(max_length=1) this is the new code I want use.However, it raise the error UnKnown column 'first_name' in person first_name is the previous variable I used in class Person. My django person is 1.10 and I have tried drop the schema and restart the server. -
Combine tags with filters
Code: {% firstof m.caption m.altcaption|slice:":37" %} I want to choose the first of those 2 variables, then slide to 37 characters. Any ideas? -
Django won't create a table
I have two different databases in django. Initially, I had a table called cdr in my secondary database. I decided to get rid of the second database and just add the cdr table to the first database. I deleted references (all of them, I think) to the secondary database in the settings file and throughout my app. I deleted all of the migration files and ran make migrations fresh. The table that used to be in the secondary database is not created when I run migrate even though it doesn't exist on my postgres database. I simply cannot for the life of me understand why the makemigrations function will create the migration file for the table when I add it back in to the model definition and I have verified that it is in the migration file. When I run migrate, it tells me there are no migrations to apply. Why is this so. I have confirmed that I have managed=True. I have confirmed that the model is not on my postgres database by logging into the first database and running \dt. Why does Django still think that this table still exists such that it is telling me no migrations … -
Django include tag
We are using django with python. I am facing a problem with include tag. I want to include a header in all modules of application. In application templates directory contains all the html files with subfolders of modules. In any sub-module if I am creating header html and including this tag in base.html then it is working. But if I place the header html in parent directory, its not working for any sub-modules. I even tried {% include "../header.html" %} in html with django template, but no luck. Include tag. The project structure fo my application, in which root directory I have templates, static, handlers folder. Inside templates I have sub1 and sub2 folders. In sub1 I have base.html and in templates parent directory base.html, header.html, index.html. See below- Root ----templates ----------Sub1 -----------------base.html ----------Sub2 ----------base.html ----------header.html ----------index.html ----static ----handlers -
Accessing Django server from AngularJs App: Easy authentication solution?
I've been looking everywhere but can't seem to find an answer that has been helpful. I have written an angular app that is trying to pull data from a django RESTful backend that was written by my company. I have a username and password, but I'm not sure how to write the get request to provide the authentication credentials to the backend. I'm also confused about what exactly I'm supposed to provide in the header. What I want I'm looking for a fix to write in the angular app itself. I'm trying to write the angular app as separate as possible from the django backend. I have already enabled cross origin resource sharing. This will be a band aid fix just to display data from the backend. It does not need to be permanent by any means. So far I have tried: app.factory('mySamples', ['$http', function($http) { return $http.get('website/api/foo', { headers: {'username':"foo", 'password': 'bar'} }).success(function(data) { return data; }).error(function(err) { return err; }); }; app.factory('mySamples', ['$http', function($http) { return $http({method: 'GET', url: 'website/api/samples/', headers: { 'user': 'foo', 'auth':'bar'} }); }; The second factory I wrote returns METHOD: OPTIONS in the networks inspector under returned header. Does anybody have a quick fix … -
Why is Django cms sitemap url not matching in all browsers?
Using the testing server http://127.0.0.1:8000/en/sitemap.xml correctly returns an XML sitemap in Firefox but in Chrome I get a 404. Why is this? All other pages' urls route OK in Chrome but this is what I get for the site map: Using the URLconf defined in mycms.urls, Django tried these URL patterns, in this order: ^media/(?P<path>.*)$ ^static\/(?P<path>.*)$ ^en/ ^admin/ ^en/ ^sitemap\.xml$ ^en/ ^select2/ ^en/ ^ ^cms_wizard/ ^en/ ^ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] ^en/ ^ ^$ [name='pages-root'] ^en/ ^ ^forms/submit/$ [name='djangocms_forms_submissions'] The current URL, /en/sitemap.xml/, didn't match any of these. My urls.py is admin.autodiscover() urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), # NOQA url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^select2/', include('django_select2.urls')), # url(r'^polls/', include('polls.urls', namespace='polls')), url(r'^', include('cms.urls')), url(r'^', include('djangocms_forms.urls')), ) # This is only needed when using runserver. if settings.DEBUG: urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', # NOQA {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) + staticfiles_urlpatterns() + urlpatterns # NOQA Safari tries to format it, but seems to GET the sitemap OK. It looks fine in Firefox: <urlset> <url> <loc>http://example.com/en/</loc> <lastmod>2016-11-22</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> <url> <loc>http://example.com/en/aboutus/</loc> <lastmod>2016-11-22</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> <url> ... </urlset> -
How to serve static files at other urls than the django static directory
I have a developer documentation site generated by mkdocs that I would like to serve through django. I tried the following in my urls.py file: url(r'^docs/wiki/', serve, {'document_root': base.DOCS_ROOT, 'path': 'index.html'}), url(r'^docs/wiki/(?P<path>.*)$', serve, {'document_root': base.DOCS_ROOT}), where base.DOCS_ROOT = 'backend/docs/wiki/site'. The second url is meant to catch all asset (css/js) files references from the index.html file. However, all files matching that pattern. Say /docs/wiki/css/theme.css just redirect to index.html leading to no assets being applied. How can I fix this? -
Django keep history of changes in one field in a JSONField
I have a model that looks like this: class Order(models.Model): ORDER_STATES = ( ('PAYMENT_IN_PROCCESS', _(u'payment_in_process')), ('PAYMENT_REJECTED', _(u'payment_rejected')), ('PAYMENT_ACCEPTED', _(u'payment_accepted')), ) state = models.CharField(max_length=150, blank=True, choices=ORDER_STATES, default='PAYMENT_IN_PROCCESS', db_index=True) history = JSONField(default=[], null=True, blank=True) .... def __init__(self, *args, **kwargs): super(Order, self).__init__(*args, **kwargs) self.__actual_state = self.state # important to keep self.history def save(self, *args, **kwargs): print("self.__actual_state: %s" % self.__actual_state) print("self.state: %s" % self.state) if self.state != self.__actual_state: # The state changed, change history actual_history = self.history print("actual_history: %s" % actual_history) new_history = actual_history.append({"state": self.state, "date": datetime.today()}) print("new_history: %s" % new_history) self.history = new_history super(Order, self).save(*args, **kwargs) All I'm trying to do is append the new state (if it changed) to the data kept in the history JSONField. However, new_history prints None I don't know why. -
Python Runserver error
Image of Errors on CMD the repository for this is https://github.com/ehauner/food-tournament. I'm using windows so I installed everything and I get this error, is there someway I could fix this problem on Windows, apparently it works fine on MAC, I used miniconda to install numpy and panda. Django and python 3.5 are also installed with system environment variable paths. Help would be appreciated. Thanks. -
How to log Python warnings in a Django log file?
I have a Django application that I am migrating from v1.8 to v1.10. In the process of doing this work, I ran my application via: python -Wall manage.py runserver Doing so causes a number of Python warnings to appear in my console. I'd like to have these warnings show up in my Django application log, so I can examine them later. I thought my application's log handler would catch these warnings, but it doesn't. The log handler looks like the following (as taken from settings.py): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'WARNING', 'class': 'logging.FileHandler', 'filename': 'myapp.log', 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'propagate': True, 'level': 'WARNING', }, 'myapp': { 'handlers': ['file'], 'level': 'WARNING', }, } } How can I capture Python warnings (with -Wall) in my Django log for examination later? -
Batch file to run local Angular2 and Django servers
I have a Django Angular2 project. I'm trying to create a batch file to make it easy to run my local django server and NPM. How can I open a new console in Batch? For example I want to open a console and simply run the command python myproject/manage.py runserver. And then I want to open another console and run the command npm start. How can I run npm start' in another directory? For example; the batch file is in./and I want it to start in./angular2-project`. -
Django Migrations Partially Complete
I am using Django 1.9.7 and MySQL. I have a migration file with multiple operations. migrations.RemoveField( model_name='team', name='country', ), migrations.AddField( model_name='team', name='description', field=models.CharField(blank=True, max_length=200, null=True), ), migrations.AlterField( model_name='team', name='iso_country', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='sys_models.Country', verbose_name='Country'), ), Now I was under the impression, that if one of these statements failed, the entire migration would rollback as part of a larger transaction. Is that correct? I am not seeing this behaviour, rather, I am seeing that it is possible for some DDL statements to succeed during a migration while another fails. Also, I thought the order would be applied top down, is that correct? I am not necessarily seeing this behaviour in Django migrations. -
Changes not saving in django admin changelist view
I have a model with a manytomany relationship with another. I followed the example at https://gist.github.com/jdklub/9261959 to make the manytomany field editable from the changelist view. However, when I make changes only the changes to the manytomany field are actually being saved. admin.py class HostChangeList(ChangeList): def __init__(self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin): super(HostChangeList, self).__init__(request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin) self.list_display = ('action_checkbox', 'name', 'ip', 'fagroup', 'description', 'customer_facing', 'monitored', 'puppet', 'sso') self.list_editable = ['fagroup', 'description', 'customer_facing', 'monitored', 'puppet', 'sso'] self.list_display_links = ['name'] class HostForm(forms.ModelForm): fagroup = forms.ModelMultipleChoiceField(queryset=FAgroup.objects.all(),widget=forms.SelectMultiple(attrs={'size': '10'}),required=False) description = forms.CharField(required=False) customer_facing = forms.NullBooleanField() monitored = forms.NullBooleanField() puppet = forms.NullBooleanField() sso = forms.NullBooleanField() class HostAdmin(admin.ModelAdmin): def get_changelist(self, request, **kwargs): return HostChangeList def get_changelist_form(self, request, **kwargs): return HostForm models.py class Host(models.Model): name = models.CharField(max_length=200) ip = models.GenericIPAddressField(default='0.0.0.0') fagroup = models.ManyToManyField(FAgroup) description = models.TextField(default=None, blank=True, null=True) customer_facing = models.NullBooleanField(default=False, null=False) monitored = models.NullBooleanField(default=False, null=True) puppet = models.NullBooleanField(default=False, null=True) sso = models.NullBooleanField(default=False, null=True) def __str__(self): return self.name def display_fagroups(self): return ', '.join([ group.name for group in self.fagroup.all() ]) class FAgroup(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name I've even tried removing all references to the manytomany field from the ModelForm and … -
Stripe event when subscription ends
I'm setting up Stripe on my django rest application to manage monthly subscriptions. In Stripe doc, we can read: https://stripe.com/docs/subscriptions/tutorial#sync-with-your-site If a customer was subscribed to a monthly plan, you would initially set this timestamp value (i.e., active_until) to one month from now. When the customer logs in, you’d verify the login credentials and check the active_until timestamp to confirm that it’s still in the future, and therefore an active account. According to that, to know if a user account is valid (if the subscription is active), we have to check if this date is future. My problem is that in my application, if the user subscribe to the Stripe plan, it will add a specific group (django group model) to the list of the user's groups. The groups are used to manage the permissions. What I want is to remove the group from the user when the subscription ends (i.e the user has not paid the renewal). I can't find such a event in the Stripe doc. There are only events when the subscription is updated (i.e the user has paid the renewal). Is there a way to catch an event from Stripe which can help me to manage … -
How to convert responsive website build with django to android app?
I have developed a website with python django. It has a mobile friendly or responsive template. I want to convert it into android app. I have heard of Phonegap but I think it works on web apps build with PHP. is there any package or library that converts the web app build with django into an android app?? I don't want to start coding from scratch for the app. PLEASE HELP. -
Formset: form for every day in month
Consider following simplified model: class Person(models.Model): name = models.CharField(max_length=64) class PreferredFood(models.Model): person = models.ForeignKey(Person) date = models.DateField() comments = models.CharField(max_length=128) number_deserts = models.PositiveSmallIntegerField() I would like to display a form (I assume through a formset) which is listing one form entry for each day in a given month. In my forms I'm doing something like: class PreferredFoodForm(ModelForm): class Meta: model = PreferredFood fields = ['date', 'comments', 'number_deserts'] PreferredFoodFormSet = inlineformset_factory(Person, PreferredFood, form=PreferredFoodForm) But this renders, as expected, just three rows. What's the best way to get one row per day in the month (usually 30 or 31), while displaying the actual day?