Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku/Django only works when Debug=True
I have a Django 1.9.6 site deployed to Heroku. When DEBUG=False I was getting a server error (500). The logs contained no useful information, so I tried running it with DEBUG=True. Now it works fine. I think the issue may be tied to my scss file processing, which really confuses me and I was struggling with. I recently--among other things--added COMPRESS_OFFLINE = True to my settings files, and commenting that out seems to alleviate the problem (although then my scss files don't work). -
how to create a transfer box + filter in admin pages? django
I am not sure what it's called so I am calling it transfer box.... I have a few models in my project and there are some fields I want to have something like this so it would be way more to manage. Anyone know how this can be done? P.S. those fields might not be fields in THIS model only though, might be fields having relationship to other fields too. Thanks in advance. -
How do I convince Django I'm logged in?
I have a Django application and I want to allow users to log in via some API and allow them to use some API calls that are protected by login_required decorator: @csrf_exempt def login(request): if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(username=username, password=password) if user is not None: login(request, user) return HttpResponse(status=201) return HttpResponseBadRequest() @login_required def do_stuff(request): return HttpResponse(status=201) And this is how I try to log in and call do_stuff from python shell: >>> from urllib.parse import urlencode >>> from urllib.request import Request, urlopen >>> post = Request('http://127.0.0.1:8000/api/login', urlencode({'username': 'admin', 'password': 'admin'}).encode()) >>> post_resp = urlopen(post) So far so good. I get a response with sessionid and csrftoken cookies. Then I try to use the sessionid cookie to do stuff: >>> get = Request('http://127.0.0.1:8000/api/do-stuff') >>> get.add_header('Set-Cookie', 'csrftoken=...') # just copy paste of the response cookie >>> get_resp = urlopen(get) At this point login_required decorator thinks I'm an AnonimousUser and sends out a redirect to the login page. Browser works perfectly with this sessionid cookie, so I suppose I miss some headers, because they aren't numerous, just Host, User-Agent, and Set-Cookie. I'm deliberately trying to avoid using modules outside of Django and stdlib. … -
Django security middleware vs Whitenoise?
Are there any significant drawbacks of using django.middleware.security.SecurityMiddleware instead of whitenoise.middleware.WhiteNoiseMiddleware in terms of efficiency or security? I want to respond with static images and I'm deploying my django app to Heroku. -
Django - Sendgrid how to substitute tags using send_mail
I'm looking at the Sendgrid documentation and it writes that to send an email, this is enough: from django.core.mail import send_mail send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False) If I want to use Sendgrid templates, where do I declare the template I want to use? Also, there are substitution tags in Sendgrid's templates. How can I declare them in django? -
Django - Python - Multiple User Types With BooleanField In Custom User Model & OneToOne Relationships
I am building a web application that will enable two different types of users to log in, with each user group having access to different pages on the site. As the information collected is similar for each type of user, I am planning to use only one custom user model with two boolean fields for each user type. The model will be defined as follows: class My_Users(AbstractBaseUser): ... is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_typeA = models.BooleanField(default=False) is_typeB = models.BooleanField(default=False) ... I intend to use OneToOne fields based on user IDs in other models, for both typeA and typeB users. So for example, there could be: class Model1(models.Model): id = models.OneToOneField(TypeA, on_delete=models.CASCADE, primary_key=True,) ... class Model2(models.Model): id = models.OneToOneField(TypeB, on_delete=models.CASCADE, primary_key=True,) ... My question are the following: 1/ This will imply that some ids created in my user model will be typeA and some others will be typeB. Will this be a problem for the one to one reliationship? i.e. will it be a problem that the ids are not incremental (type A could be id 1, 3, 4, 5, etc... whilst type B could have ids 2, 6, 7, etc...) for the one-to-one relationship. 2/ Is this the best … -
Client denied by server configuration. Django app with mod_wsgi and apache 2.4
I can't configure apache 2.4 to run wsgi application on a clean Ubuntu 16.04 installation. I use Python 3.5 and mod_wsgi 3.5 (compiled manually for both my Python and Apache) I have successfully done this before a lot of times, this time I have no clue what is the problem. My app's config looks like this: <VirtualHost *:80> WSGIScriptAlias / /var/django/myapp/myapp/wsgi.py WSGIDaemonProcess myapp python-home=/var/.virtualenvs/myapp python-path=/var/django/myapp WSGIProcessGroup myapp ServerName mydomain.com ErrorLog /var/log/apache2/myapp_error.log alias /static /var/django/myapp/static/ <Directory "/var/django/myapp/static/"> Require all granted </Directory> <Directory "/var/django/myapp/myapp"> <Files "wsgi.py"> Require all granted </Files> </Directory> I always use the exact same configuration for all my Django projects, but now, every time I go to mydomain.com, I get the 403 Forbidden page. As you can see, I configured apache to log errors to myapp_error.log, but it logs to regular error.log instead: AH01630: client denied by server configuration: /var/www/html Also, I don't understand why it says /var/www/html. I deleted html folder and even commented out #<Directory /var/www/> # Options Indexes FollowSymLinks # AllowOverride None # Require all granted #</Directory> in Apache main config file, but I still get this messages. I checked some other config files like 000-default.conf but found nothing related to 'html' folder. I enabled LogLevel … -
Create Azure webjobs from Django/python web app
I have a Django app deployed on a Azure Web App, and I want to dynamically create webjobs. More precisely, when I save a Django model called Importer, I want to be able to create a new web job, made of 3 files: run.py : the Python webjob settings.job : the cron schedule config.ini : a config file for the webjob The content of the "settings.job" & "config.ini" comes from an admin form and is specific to the webjob. When I save my model, the code creates a new directory in App_Data\jobs\triggered{my job name} , and copies there the "run.py" from my app directory. This works. However, when I try to create a new text file called "settings.job" in the job directory and write the cron schedule in it, I got a server error. I tried many things, but the following basic test causes a failure: file = open('test.txt','w') file.write('this is a test') file.close() It seems that I don't have the right to write a file to the disk. How can that be solved? Also, I want to be able to modify the content of the config and settings.job files when I update the corresponding Django model. Thanks for your … -
GoDaddy Domain Name not keeping full URL path
I have a domain name from godaddy (example... newdomain.com) and I am trying to mask the public IP address of my Django web application in my server. The settings for my newdomain.com in GoDaddy is "Forward with Masking." The issue I am having is that every time I click the links in the web app the URL will always stay as newdomain.com. So for example in the webapp, I click a login button (which redirects to newdomain.com/login) the URL will always display as newdomain.com but the contents of newdomain.com/login will be displayed in the browser. Please let me know if you have any clues on how to fix this, thanks in advance! -
Django Templates: External link with variable
This link is an external site link, all solutions I found mention an internal link with static or variables In the HTML <a href="https://externalsite.com/page1/page2/assetId="/{{varID}}/">{{varName}}/a> It always comes up with a spaces around varID. I tried Trimming the variable. I tried escaping with /. This is what it looks like in browser inspect <a href="https://externalsite.com/page1/page2/assetId=" 1234 ">myAsset</a> this is what the url is when you click on it https://externalsite.com/page1/page2/assetId= -
local variable 'script1' referenced before assignment
Thank you in advance for you who could be able to help this. I spent many hours working on this error but can't figure it out. I am trying to use a form to grab a ticker and pass the ticker to a simple chart using bokeh and then deliver the result to views.py and display it on html. first of all I have the following code in my views.py. def pme(request): os.chdir(os.path.dirname(__file__)) result = None if request.method =='POST': form = InputForm(request.POST) if form.is_valid(): forms = form.save(commit=False) result = macd(forms.ticker) script1, div1 = components(result, CDN) else: form = Ticker() return render(request,'pme.html', {"form":form, "the_script1":script1, "the_div1":div1, }) For some reasons, script1 is referenced before? my macd(forms.ticker) simply returns p and it works fine by itself. Any help is appreciated. -
jQuery not loading on Heroku, contained in Django static file, installed using bower
I'm having trouble loading jQuery on my Django app on Heroku. Heroku is getting the path to the static directory right, but it's not installing jQuery into the static directory for some reason. Here's some context: I used npm to install bower, and bower to install jQuery into mysite/static/js, where it is on my local machine. I made a package.json: { "name": "mysite", "version": "1.0.0", "description": "blah", "main": "index.js", "repository": { "type": "git", "url": "git+https://github.com/username/mysite.git" }, "author": "Firstname Lastname", "license": "ISC", "bugs": { "url": "https://github.com/username/mysite/issues" }, "homepage": "https://github.com/username/mysite#readme", "engines": { "node": "6.9.5" }, "dependencies": { "bower": "^1.8.0" }, "scripts": { "start": "node index.js", "postinstall": "bower install" } } and a bower.json: { "name": "mysite", "dependencies": { "jquery": "^3.1" } } I followed the instructions on Heroku for static assets: Here I've linked my Heroku app to the Github where all the code is. I put mysite/static/js in my .gitignore file so that all the jQuery code isn't uploaded to Github. I expect that when I push, Heroku should get all that code and run npm install bower, then bower install, and get the jQuery file into the static directory. However, when I checked the logs on Heroku, it shows: 2017-02-15T18:41:14.351818+00:00 … -
How to get ckeditor to work in Django
I'm trying to get a blog up but I need ckeditor in Django admin to make posts. In this link https://github.com/django-ckeditor/django-ckeditor it gives the instructions for getting ckeditor on Django admin and I don't understand step 3 which says this: django-ckeditor uses jQuery in ckeditor-init.js file. You must set CKEDITOR_JQUERY_URL to a jQuery URL that will be used to load the library. If you have jQuery loaded from a different source just don't set [CKEDITOR_JQUERY_URL] and django-ckeditor will not try to load its own jQuery. If you find that CKEditor widgets don't appear in your Django admin site, then check that this variable is set correctly. Example: CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' Can somebody go into better detail of how to execute this step? What do I copy, paste, edit or configure in what file? I went on a limb and pasted the above URL in settings.py and moved on to step 4 which failed too. There aren't much other resources for how to do this. -
Invalid password format or unknown hashing algorithm Django Create View User
I'm using a create view to make users in the system but the admin keeps saying that there is an "Invalid password format or unknown hashing algorithm." for the user? I'm using the UserCreationForm provided by the framework from django.views.generic.edit import CreateView from django.contrib.auth.forms import UserCreationForm class UserCreate(CreateView): model = User form = UserCreationForm fields = ('username', 'first_name', 'last_name', 'password') template_name = 'exts/user_create.html' def get_success_url(self): # login the person self.object.backend = 'django.contrib.auth.backends.ModelBackend' auth_login(self.request, self.object) # now return the success url return '/' def get_form(self, form_class=None): form = super(CreateView, self).get_form(form_class) form.fields['password'].widget = forms.PasswordInput() return form -
Django Object has no attribute '__set' in legacy Database
I can't quite figure out how to work ou ManyToMany relationships in a legacy DB. models.py : class Trecho(models.Model): cod = models.BigIntegerField(primary_key=True) torres = models.ManyToManyField('Torre', through="Trecho_Com_Torre") class Meta: managed = False db_table = 'OPE_TRECHO' class Torre(models.Model): cod = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'OPE_TO' class Trecho_Com_Torre(models.Model): cod = models.BigIntegerField(primary_key=True) cod_trecho = models.ForeignKey('Trecho', on_delete=models.CASCADE, db_index=False, db_column='COD_TRECHO') cod_to = models.ForeignKey('Torre', on_delete=models.CASCADE, db_index=False, db_column='COD_TO') class Meta: managed = False db_table = 'OPE_TRECHO_COM_TO' The error is "Torre object has no attribute trecho__set", when I try to run the following query : t1 = Torre.objects.get(cod=1) trechos = t1.trecho__set.all() If I'm not mistaken, this would work if all these tables were managed by Django, but since they are legacy, how can I make this work? -
How to produce Json response with correct encoding using Django and Mssql (accents)
I'm using Python to connect to a SQL server 2014 database using pyodbc. I capture the lines to produce a dictionnary to then send the information through a http with Django using a JsonResponse obj. When I test it out my response has backslashes and numbers wherever accents are found. How can I encode the response correctly? Here is my code: database_odbc.py import pyodbc import json def connect(): conn = pyodbc.connect( r'DRIVER={ODBC Driver 13 for SQL Server};' r'SERVER=myserver;' r'DATABASE=mydatabase;' r'UID=sa;' r'PWD=secret') return conn.cursor() def get_data_v(cursor): cursor.execute('select * from data') columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results views.py from django.http import JsonResponse from .database_odbc import connect, get_data_v def dataView(request): payload = get_data_v(connect()) response = JsonResponse(payload, safe=False) response['contentType'] = 'application/json; charset=latin1' return JsonResponse(payload, safe=False) I have tried with and without the response['contentType'] header. Thank you. -
Django Message don't work
Am trying to set a success message after login using the django Message framework but the message never show up! I know lot of people asked before the same question, and their message doesnt show up because of their settings. I checked my settings many time every things seems good but it's still not working. Anyone know why ? maybe my render is not good ? my settings : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [#other dir, os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] my view: def connexion(request): error = False if request.method == "POST": form = loginForm(request.POST) if form.is_valid(): email = form.cleaned_data["email"] mdp = form.cleaned_data["mdp"] user = authenticate(email=email, password=mdp) if user: login(request, user) messages.success(request, 'Form submission successful') else: error = True else: form = loginForm() return render(request, 'login.html', locals()) my template login.html : <form id="loginform" name="loginform" method="POST" action="/welcome"> {% csrf_token %} {{ form.as_p }} <button>Valider</button> also when the user submit the form he go to an other templates : welcome.html (here where I want showing the message) … -
How does Django rename uploaded files?
Suppose I upload a file image.png from a web browser, a new file named image_aj642zm.png will appear in the upload directory on the server. What is the method that Django uses to rename the uploaded files? (i.e. where does the extra _aj642zm come from?) -
Validate Django Admin Inline Formset
I need to validate that an inline formset has a unique value. The idea is to be able to add a competition with a question and multiple answers. We can flag the correct answer using a checkbox, however I need to ensure that no more than one checkbox is ever selected or saved. I have tried validating with a clean() on the model side and also by extending BaseInlineFormSet, but then I seem to struggle to iterate over the formset and get any values. class Competition(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True, blank=False) content = models.TextField() terms = models.TextField() class Question(models.Model): competition = models.OneToOneField( Competition, on_delete=models.CASCADE, primary_key=True, ) question = models.CharField(max_length=255) class Answer(models.Model): question = models.ForeignKey(Question) answer = models.CharField(max_length=255) is_correct = models.BooleanField(default=False) -
Django-filter - custom Boolean filter
I can't figure out how to create a custom Boolean filter. The queryset consists of Product objects. Every Product object can have multiple Scan objects. The scan has a datetime field and valid field. class Scan(Model): datetime = DateTimeField() valid = BooleanField(default=True) I want to filter those Products which last scan has valid=True. Something like: def has_last_valid(product): return product.scans.latest('datetime').valid But can't figure out how to make it work in Django-filter. Tried: class ProductFilter(django_filters.FilterSet): last_scan_correct = django_filters.BooleanFilter(method='my_custom_filter') class Meta: model = Product fields = ['active','last_scan_correct'] def my_custom_filter(self, queryset, name, value): result = [] for p in queryset: if p.scans.latest('datetime').valid: result.append(p) return result This doens't seem to have effect. -
_filter_or_exclude() argument after ** must be a mapping, not function
model zone: class Zone(models.Model): id = models.AutoField(primary_key=True) city = models.ForeignKey(City, related_name="zone_key") name = models.CharField(max_length=200, unique=True, validators=[MinLengthValidator(5)]) model polygon: class Polygon(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) enabled = models.PositiveSmallIntegerField(default=1,choices=ENABLED_CHOICES) models specialPolygon: class SpecialPolygon(models.Model): def limit_polygon_choices(): return {'zone__id': polygon.zone_id} zone = models.ForeignKey(Zone) polygon = models.ForeignKey(Polygon, on_delete=models.CASCADE, limit_choices_to = limit_polygon_choices) I want to show only those polygons in the specialPolygon model which are present in that zone only. I have used limit_polygon_choices function but I am getting the error: _filter_or_exclude() argument after ** must be a mapping, not function Please help me solving this. Thanks -
Which grant type should I use
I have a REST api build with django rest framework which. I implemented token authentication using oauth-toolkit. Now I started developing angularJS app which will use that REST api. After that I also want to make an andoird app which will also use this REST api. I've been wondering which grant type should I use? The one that seems easy to use is Resource Owner Password Credentialsalong with public client type, since I can't really hide client secret. What is really the point of client ID? Anyone with browser developer tools can get the client ID, register and use my api impersonating as my web app. Client Credentials, this one does not authenticate the user so it's not usefull in my case. I'm not sure about implicit grant and authorization code How would I make my app/android app only two apps authrozied to use the REST api? Seems like this can't be done if users are allowed to register freely? -
Does a django migration failure modify the databse?
I need to know if getting an error while running python manage.py migrate means my database will remain in the same state it was before running the migrate command. I'm trying to implement migrations as part of a CI system and it would be good to know if I need to do some kind of rollback if the migrations fails. -
What is the best way to implement the State design pattern in Django model layer?
We have some Tasks and states, that a task might have. You may think of any task tracking app, aka redmine. States are constant and won't change in the future. The possibilities of transition from one state to another are also constant. class State(models.Model): STATE_NEW = 1 STATE_IN_PROGRESS = 2 STATE_POSTPONED = 3 STATE_DONE = 4 name = models.CharField( max_length=50, unique=True, ) class Task(models.Model): name = models.CharField(max_length=255, db_index=True) state = models.ForeignKey(State, default=State.STATE_NEW) What I want is to implement a state design pattern, not to have an ugly changeState method full of conditionals. What is the best way to achieve this in Django? -
CSRF token missing or incorrect django
I'm trying to send some data to a view using .ajax but I am getting the CSRF token missing or incorrect error. I have added the @ensure_csrf_cookie decorator to the view that renders the page to make sure that there is a csrf cookie. Javascript var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); function updateWaypoints(){ var routeArray =Array(), routeArray = control.getWaypoints(); routeArray.push({route_id:routeId}); console.log(routeArray); console.log(JSON.stringify(routeArray)); var newData = JSON.stringify(routeArray); $.ajax({ type: 'POST', url: '/routes/savemaproute/', data: newData, }); } the view function it is send to: @login_required def save_map_route(request): if request.user in route.owner_user.all(): if request.POST: recieved_json_data = request.POST['data'] route_id = request.POST['route_id'] route = get_object_or_404(Route, pk=route_id) route.map_waypoints = recieved_json_data route.save() return HttpResponseRedirect(reverse('route:details', args=(route_new.pk,))) urls.py urlpatterns =[ url(r'^$', views.index, name='index'), url(r'^savemaproute/$', views.save_map_route, name='save_map_route'), ]