Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Ubuntu 16.04/ Specifying python version
Long story short.... When my Django project was on my computer(and not live on internet), I could specify which python version to use(I have both python2.7 and python3.6) like... python3 manage.py runserver This was convenient because python 3 doesn't trigger unicode key errors when I try to run a string in different language, like korean. However now I have my website live on the internet using ubuntu 16.04 and it automatically uses python 2.7 which DOES trigger an unicode error. Does anyone have a way to specify which python version to use on ubuntu 16.04? -
How to acees django request object in logging filter
I am trying to update of the django module: https://github.com/miohtama/django-requestlogging/blob/master/django_requestlogging/logging_filters.py How to access the request object as it's none class RequestFilter(object): def __init__(self, request=None): self.request = request # @staticmethod def filter(self, record): request = self.request record.request_method = getattr(request, 'method', '-') record.path_info = getattr(request, 'path_info', '-') user = getattr(request, 'user', None) if user and not user.is_anonymous(): record.username = user.username else: record.username = '-' META = getattr(request, 'META', {}) record.remote_addr = META.get('REMOTE_ADDR', '-') record.server_protocol = META.get('SERVER_PROTOCOL', '-') record.http_user_agent = META.get('HTTP_USER_AGENT', '-') return True -
Flask API Error
I am trying to build simple web application using flask. Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application. <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> </div> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Page 1</a></li> <li><a href="#">Page 2</a></li> <li><a href="#">Page 3</a></li> </ul> -
Connect to databases dynamically in Django
I'm new to Django. My project database architecture is like Having 'Auth_DB' contains all the users login details. Once user logged in, then in need to fetch the details from the other DB. Here i have databases for each user individually, like: user_0001 user_0002 user_0003 user_0004 user_0005 Can any one please help how can i achieve this. Thanks in Advance. -
Django rest framework inheriting a class from Serializer and making it abstract
I'm using Python 3.6 with Django 1.11.9 and rest_framework 3.6.2. I want to inherit from serializers.Serializer to make a SharingSerializer class, that I want to be abstract, because I want to inherit from the latter to implement some ArticleSharingSerializer, ImageSharingSerializer,... and so on. What I've tried so far: from abc import ABCMeta, abstractmethod from rest_framework import serializers ... class SharingSerializer(serializers.Serializer, metaclass=ABCMeta): course = serializers.PrimaryKeyRelatedField(queryset=Course.objects.all()) students = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), many=True) @abstractmethod def validate(self, data): # Doing validation stuff with "course" and "students" fields ... return data class ArticleSharingSerializer(SharingSerializer): articles = serializers.PrimaryKeyRelatedField(queryset=Article.objects.all(), many=True) def validate(self, data): data = super().validate(data) # Doing validation stuff with "articles" and self.context["request"].user ... return data But when trying to "runserver", I get the following error: File ".../school/serializers.py", line 11, in <module> class SharingSerializer(serializers.Serializer, metaclass=ABCMeta): TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Do you know how I can successfully achieve what I'm trying to achieve? -
How to pass parameter from view to template in django?
I want to pass value of variable from django view to template. view: def countsnippet(request): checkins = Attendee.objects.filter(checkin=True).count() return render( request, 'search/countsnippet.html', {'inft': checkins} ) Template snippet: <div class="row" > {% block content %} <p>INFT : {% 'inft' %}</p> {% endblock %} </div> I want to pass checkins value to template, but using above approach is giving me error. -
button of popup doesn't function
I have a button that show a popup.. I need to know which buttons is clicked after the popup is closed. The button in html with the popup to show : <p class="stop_inv"> <span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Stop<p> The popup in the same html: <div class="modal fade" id="confirm-stop-automated-popup" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog" style="width:370px;" role="document"> <div class="modal-content"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <form class="form-horizontal" method="post" id="stop_automated"> <div class="modal-body"> <div class="row"> <h1 class="center" style="font-size:100%;"> Do you wish to close them immediately ? </h1> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" name="ok" data-dismiss="modal" id="confirm-stop-button">Ok</button> <button type="button" class="btn btn-primary" data-dismiss="modal" id="cancel-delete-button">Cancel</button> </div> </form> </div> </div> </div> My function in javascript:(the popup is shown but the problem i can't know which button from the popup is clicked $('.automated-orders-list .stop').on('click', function(){ $('#confirm-stop-automated-popup').modal('show'); e.preventDefault(); return;}); The second javascript for popup to know which button is clicked doesn't work: $('#confirm-stop-automated-popup .modal-footer button').on('click', function(event){ var $button = $(event.target); // The clicked button $(this).closest('.modal').one('hidden.bs.modal', function() { // Fire if the button element console.log('The button that closed the modal is: ', $button); }); }); -
django http Error 401 for css and picture on pdf
I used django and weasyprint to make an application which print a pdf file with picture and css file which design my pdf file. A log in django give me this Failed to load stylesheet at http://IP_ADDR/static/css/default.css : HTTPError: HTTP Error 401: Failed to load image at "http://IP_ADDR/static/image/picture_50x48.png" (HTTPError: HTTP Error 401: ) -
Posting data to a Django model via external python script
I have a python script that is printing data to a .csv every one minute. I want to instead save this data to a Django database over the internet. I have a basic Django based site running by following some tutorials. But I can only post data on my database by submitting online forms. I would like to do this automatically (from python script), then view the posted data. Would the best method be: Instead of printing the data, have the python program write mydata to a url. The url would be mywebsite.com/dataPost/mydata In Django mysite directory: mysite/urls.py would forward this url to datapost/urls.py dataPost/urls.py would point to dataPost/views.py dataPost/views.py would point to dataPost/models.py where mydata would be saved to database. Assuming this is a valid high level plan, can someone give me a rough idea of what the syntax would look like? Anything will help. -
Django2.0 sending and receiving message frame-work
I am new at Django. What framework I can use to send or receive a message from one user to another. What is the framework that is easy to implement? -
Django Viewflow - Return Handler Response
Following is my flow:- class APLWorkflow(Flow): start = ( flow.StartFunction(function1) .Next(this.request_quotes) ) request_quotes = ( flow.Handler(function2) .Next(this.move_package) ) move_package = ( flow.Handler(function3) .Next(this.shipment_create) ) shipment_create = ( flow.Function(function4) .Next(this.end) ) end = flow.End() Following are my util functions:- def function1(): return 1 def function2(): return 2 def function3(): return 3 def function4(): return 4 The problem is when I start the flow, it runs perfectly well. However, the response returned is that of start node, not the last executed node. Following is my code:- activation.prepare() response = APLWorkFLow.start.run(**some_kwargs) activation.done() # stops the flow at `move_package`. print(response) # prints 1, not 3. How do I return the response of the last executed node, in this Handler (move_package)? -
Django throws a 302 error when I try to redirect a user after password change
I have a view that handles the password change for a user @csrf_exempt def change_password(request): if request.method == "POST": user_request = json.loads(request.body.decode('utf-8')) try: u = User.objects.get(username=user_request.get("user")) u.set_password(user_request.get("password")) u.save() except Exception as e: print(e) return HttpResponse("Failure") return HttpResponseRedirect('/') This does change the password for the user since next time if I have to login, I have to supply the new password.But it doesn't redirect the user immediately to the home page (which in turn will redirect to login page since the user is logged out). I have a similar view for login given below @csrf_exempt def login_view(request): if request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/') else: return render(request, "login.html") else: return render(request, "login.html") But it does redirect the user to the home page if the authentication is successful. Then why doesn't any redirection happens when the user changes their password?I instead get a 302 status code. -
How to configure settings in Django when realative reference of static files don't contain a 'static'?
I'm a newbee to html/js/css. Now I have a big frontend that use realative reference of static files that don't contain a 'static' prefix. However Django need a STATIC_URL definition in settings.py, default is "/static/". Then the real request url is "/demo/faces/male/16.jpg", but the url django expected is "/static/demo/faces/male/16.jpg" It's really a big frontend maintained by other guys, I don't want to modify it. Is there a method to remove the 'static' requirement? -
Django Templates and Angular 6 when Django DEBUG=False: SyntaxError: expected expression, got '<'
I am building a webapp with Django and Angular 6. There fore I have created a index.html template which gets the DEBUG variable injected. Depending if the django server is running in debug-mode or not I want to load the angular development files or the production files. If i set the DEBUG variable to False I get the following errors: SyntaxError: expected expression, got '<'[Weitere Informationen] runtime.a66f828dca56eeb90e02.js:2 SyntaxError: expected expression, got '<'[Weitere Informationen] polyfills.2f4a59095805af02bd79.js:2 SyntaxError: expected expression, got '<'[Weitere Informationen] main.7c10c5d5bf77c58a5084.js:2 When I switch the angular files like in code snippet 3) and set DEBUG=TRUE everything works as expected. Again setting DEBUG=False leads to the errors, but this time for the angular development files: SyntaxError: expected expression, got '<'[Weitere Informationen] runtime.js:2 SyntaxError: expected expression, got '<'[Weitere Informationen] polyfills.js:2 SyntaxError: expected expression, got '<'[Weitere Informationen] styles.js:2 SyntaxError: expected expression, got '<'[Weitere Informationen] vendor.js:2 SyntaxError: expected expression, got '<'[Weitere Informationen] main.js:2 1) The view: class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['debug'] = DEBUG return context @method_decorator(ensure_csrf_cookie) def dispatch(self, *args, **kwargs): return super(IndexView, self).dispatch(*args, **kwargs) 2) The Template: {% load staticfiles %} <!doctype html> <html lang="de" style="height: 100%;"> <head> <meta charset="utf-8"> <title>Frontend</title> <base href="/"> <meta name="viewport" content="width=device-width, … -
How do I code my views.py such that the form data gets stored in my database(/admin)? Using Django (v2)
This is a project that user/employee requests for a leave and the admin can see it. models.py from django.db import models from django.contrib.auth.models import User CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave')) class Leave(models.Model): name = models.CharField(max_length = 50) employee_ID = models.CharField(max_length = 20) department = models.CharField(max_length = 15) designation = models.CharField(max_length = 15) type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None) from_date = models.DateField() to_date = models.DateField() reporting_manager = models.CharField(max_length = 50, default = None) reason = models.CharField(max_length= 180) def __str__(self): return self.name forms.py from django import forms from lrequests import models CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave')) class LeaveRequestForm(forms.ModelForm): class Meta: fields = ("name", "employee_ID", "department", "designation", "type_of_leave", "from_date", "to_date", "reporting_manager", "reason") model = models.Leave admin.py from django.contrib import admin from . import models, forms class LeaveAdmin(admin.ModelAdmin): form = forms.LeaveRequestForm admin.site.register(models.Leave, LeaveAdmin) In the views.py file I'm not sure how to code to store data in the database. So that the admin can see the data that's acquired from the forms. views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import LeaveRequestForm from django.views.generic import TemplateView def leaveRequest(request): form_class = LeaveRequestForm return render(request, "request_form.html", {'form' : form_class}) -
Can i call the get method in django class based views from the post method
In my django app's views.py i have a class based view Profile(View) wich has two methods get(self, request) and post(self, request). So when a post request is send to this view, when the input passes a test, i want to go invoke the get() method whoch will return the template with updated data. Is it possible? -
django through lighttpd + mod_proxy + gunicorn: X-Sendfile returns empty responses
I'm using Django behind Gunicorn and lighttpd. As of Gunicorn documentation, I configured Lighttpd to act as reverse proxy towards Gunicorn: $SERVER["socket"] == "0.0.0.0:80" { server.document-root = "/home/user/app" server.errorlog = "/var/log/lighttpd/app-error.log" accesslog.filename = "/var/log/lighttpd/app-access.log" $HTTP["url"] !~ "^/static/" { proxy.server = ( "" => ( ( "host" => "127.0.0.1", "port" => 8888, "allow-x-send-file" => "enable" ) ) ) } } So far so good, everything works and even static files are served correctly. Now I'm trying to use the header X-Sendfile. In my Django code: response['Content-Type'] = 'application/force-download' response['Content-Disposition'] = f'attachment; filename={smart_str(send_name)}' response['X-Sendfile'] = '/tmp/big-file.txt' /tmp/big-file.txt exists and is accessible by the Lighttpd process. Every time I try to serve a file this way, the browser gets an empty response; no payload and Content-Length: 0. I find nowhere any error from Lighttpd (I think the Django + Gunicorn part is fine) about what's going wrong. What can I do? Where's my mistake? Thanks. -
django queryset using modified field value
I have: StoreProduct Model: store_id = ForeignKey(Store) product_id = ForignKey(MasterProduct) created_date = DateTime(auto) (product received date) created_date is assumed as manufacturing date + 10 days and MasterProduct: id = pk expires_in = IntegerField() expires_in = expiry date - manufactuing date expiry and manufacturing dates aren't saved. Now I want to retrieve records which will expire in next 30 days. i.e. I want to retrieve records as: select * from storeproduct where (created_date - 10 + product_id__expires_in) >= today I was wondering of using django.db F but don't know its use case. I am doing: store_products = StoreProduct.objects\ .filter(store_id=store_id, created_date__gte=(F('created_date')- timedelta(days=10)+ timedelta(F('master_product__expire_in_days')))) As field is date time, can't use F inside timedelta. -
Django: In-memory database then store to file
I am importing about 5 million records into a database. The import is part of my Django application. Futhermore, the records are highly relational, where each record is processed into 10+ tables. All writing to disk slows down this process quite a bit. Is it possible to first import the records into an in-memory database, and then write this database to disk once the import completed? I considered the bulk_insert method but I suppose that this does not function well with highly relational data. Is that correct? Thanks! -
Django; form wihtout submit button cause 404 error
I'm creating a project using Django. I'm creating a form without submit button. I'm not familiar with js at all but when I look up how to do it, some answers say like this <script> document.getElementById("search-form").submit(); </script> but in this way, the page is automatically loaded right after I entered this page and caused 404 error. html is like this <form action="GET" action="{% url 'blog:search_entry' %}" id="search-form"> <input type="text" name="q" placeholder="Search for posts..."> </form> views.py is like this def search_entry(request): query = request.GET.get('q') entries = Entry.objects.filter( Q(title__icontains=query) | Q(description__icontains=query) ) return render(request, 'blog/search_entry.html', {'entries': entries}) How am I wrong with it? -
How to dynamically update form data in django
I am new to django and I am trying to create a review system, whereby each team member reviews all the other members within their team.return Here is my models.py file: from django.db import models from django.contrib.auth.models import User class Team(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Trait(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reviewer_id') reviewee = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reviewee_id') trait = models.ForeignKey(Trait, on_delete=models.CASCADE) trait_score = models.IntegerField()` return This is my views.py file: from django.shortcuts import render, redirect from review.forms import ReviewForm from django.http import HttpResponse from django.contrib.auth.models import User from accounts.models import UserProfile def positivity_review(request): if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): form.save() return redirect('/review/relationships') else: form = ReviewForm() users = UserProfile.objects.filter(review_team=1) args = {'form': form, 'team_members': users} return render(request, 'review/positivity.html', args)` return This is my forms.py file: from django import forms from django.forms.widgets import NumberInput from review.models import Team, Review class RangeInput(NumberInput): input_type = 'range' class ReviewForm(forms.ModelForm): trait_score = forms.IntegerField(widget=RangeInput, min_value=0, max_value=100, label='') class Meta: model = Review fields = ( 'trait_score', )` return This is the HTML file: {% extends 'base.html' %} {% block head %} <title>Review</title> {% endblock %} {% block content %} <br> <h1>Review</h1> … -
login on user registration via facebook
What is the best way to register user via facebook? Current logic is that user logs in on mobile app with facebook then back-end receives accessToken and makes request to facebook api and gets all info about user. Then user will be created with data from facebook if he doesn't exist and calls login() func. After this mobile client get in response user's auth_token and bool value whether he is new user. If he is a new user mobile client will make request to facebook and then display form with data from facebook which can be changed. Then client calls method update-user and updates user info. -
Django - How to create an admin / dashboard site (like adminLTE)
I need to create an admin site where admin/staff users can control users, can check orders, see dashboard with graphs, etc. I want to keep default admin site separate, since it's too powerful and a bit confusing for non-IT users. django-adminlte2 can be a good solution as it provides ready-to-use adminLTE templates using Bootstrap v3. I wanted to know if there are other valid alternatives? -
Django & Heroku: Best practice database setup
I am currently looking into Heroku to host my Django application. As I previously had issues with website availability I want to build it the 'right way'. My setup: staging & production pipeline. Each application in this pipeline has its own database. I know read into this documentation article here and understood a good setup would be that way: Staging application: - Should be connected with a follower database of our production application. Production application: - Lead database - Additional one more follower database on 'hot-standby' in case the lead database has issues The way I described it, would you say that's stable & 'best practice' setup? Thank you. -
Custom date format parsing in python
I am trying to the parse dates of the format '2016-04-15T12:24:20.707Z' in Python, tried strptime, doesn't work and I also tried django parse_datetime but it only returns none as the value