Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Same Test fails sometimes and sometimes is successful
I created a Test for my own Admin LogEntry Message. So sometimes this Test is successful and sometimes it fails. I can't understand why. Do you see the mistake here? I use this code to test my app: python3 manage.py test Here is the TestCase: class AdminLogTests(TestCase): @classmethod def setUpTestData(cls): cls.admin_user = ProfileUser.objects.create( email='test_admin@test.de', first_name='Admin', family_name='Testadmin', is_active=True, is_superuser=True) cls.admin_user.set_password('testtest') cls.admin_user.save() def setUp(self): self.client = Client() def test_log_admin_create_user(self): self.client.login(email='test_admin@test.de', password='testtest') response = self.client.post('/admin/addressbook/profileuser/add/', { 'address': 'Herr', 'first_name': 'Max', 'family_name': 'Meiser', 'email': 'test1@test.test', 'password1': 'testtest', 'password2': 'testtest', }) test1_user = ProfileUser.objects.get(email='test1@test.test') response = LogEntry.objects.filter( action_flag=1, object_id=test1_user.pk) print(response) response = self.client.get('/admin/addressbook/profileuser/{}/history/'.format(test1_user.pk)) self.assertContains(response, 'Admin Testadmin added Max Meiser') test1_user.delete() And here the error: FAIL: test_log_admin_create_user (addressbook.tests.AdminLogTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/addressbook/tests.py", line 180, in test_log_admin_create_user self.assertContains(response, 'Admin Testadmin added Max Meiser') File "/usr/local/lib/python3.5/dist-packages/django/test/testcases.py", line 382, in assertContains self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr) AssertionError: False is not true : Couldn't find 'Admin Testadmin added Max Meiser' in response -
Update object attribute with one click in django
I have a simple model which had three attributes A B & C While creating the object i have kep the value of attibute to be 'null true' So the model object is being displayed in my template and i want to put a simple link below the object which will pass on the current time value to the objects attribute whenever clicked. just like a stop watch. How can i do it? -
Django-Activity-Stream: How can I generate a json feed of my posts?
I have a blog-type website, and I want to generate json feed of the activity stream of my latest posts. Can you give me an example of how it's done? I need to be able to go to /feed/posts/, and see my latest posts in activity-stream json format. -
Python Social Auth to differentiate between login/signup cancel
I'm using python-social-auth to allow users to connect through social networks. Everything is working fine until the moment the user cancels the login/signup process in the middle. I'm using SocialAuthExceptionMiddleware to catch the AuthCanceled exception and I got it but there is no info about the original URL (or the starting URL where the user started the login/signup process) which does not allow me to identify if the user is coming from the login page or signup page. I've been trying to add more parameters to be passed to the /accounts/complete/facebook/ endpoint but unsuccessfully so far. The starting URLs can be http://myhost.com/login/ and http://myhost.com/signup/ and that's what I want to get in the middleware. Thank you -
Django Rest - UniqueTogetherValidator without the need to send all the fields selected in the validator
I do apologize if this is a duplicate, but I couldn't find a solution on SO. The problem I am working on comments for a blog post. Current requirements assume that one person can comment a specific blog post only once. I want to perform UniqueTogether validation in a serializer at the latest moment possible - attempting to save it onto DB and catching an exception would be the best for me, I think, but this is not an absolute necessity. In this case, the fields that should be unique together are: user - post author post - the post itself The thing is - I don't want the user to send data for those fields in JSON, as I can get the author from the currently logged-in user, and post from the primary key passed in the URL. I understand that UniqueTogetherValidator turns the used fields into required fields, which makes matters a bit difficult. If I'm correct, UniqueTogetherValidator performs validation check on the data that has arrived with the request, which is the difficulty I've just mentioned. Below you'll find my code. This is the serializer: class PostCommentSerializer(serializers.ModelSerializer): submit_date = utils_serializers.LocalTZDateTimeField(read_only=True) user = BasicUserSerializer(read_only=True, required=False) post = PostSerializer(read_only=True, … -
Python - Update (edit) form not showing
I have been reading the django documentation, googling for days where none have the same problem as me. It seems that method "member_edit" in "Views.py" does not return any data and therefor can not show me the form. Hopefully, some of you can spot where I went wrong. Appreciate all the help I can get! Models.py class Member(models.Model): member_no = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) email = models.CharField(max_length=50, null=True, blank=True) reg_date = models.DateTimeField(null=True, blank=True) class Meta: db_table = 'Member' Forms.py class RegForm(forms.ModelForm): first_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=30, required=True) last_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=30, required=True) email = forms.CharField( widget=forms.EmailInput(attrs={'class': 'form-control'}), required=True, max_length=75) reg_date = forms.DateField(widget=DateWidget(usel10n=True,bootstrap_version=3)) class Meta: model = Member exclude = ['last_login', 'date_joined'] fields = ['first_name', 'last_name', 'email', 'reg_date', ] Views.py def member_edit(request, member_no): member = Member.objects.get(member_no=member_no) if request.method == 'POST': form = RegForm(request.POST or None, instance=member) if form.is_valid(): member.first_name = form.request.POST['first_name'] member.last_name = form.request.POST['last_name'] member.email = form.request.POST['email'] member.reg_date = form.request.POST['reg_date'] member.save() return redirect('member_overview') return render(request, 'member/member_signup.html') urls.py urlpatterns = [ url(r'^member_edit/(?P<member_no>\d+)$', views.member_edit, name='member_edit') ] member_edit.html {% block body %} <h1 class="logo"><a href="{% url 'member_overview' %}">Members</a></h1> <div class="signup"> <h2>{% trans 'Update member' %}</h2> <form action="{% url 'member_edit' member.member_no %}" method="post" role="form"> {% … -
supervisorctl always reports error: ERROR (no such file)
I deploy my django project with uwsgi、supervisor and nginx. but I have write my program like above in the /etc/supervisord.conf. [program:JZAssist] command=-E uwsgi --ini /home/work/xxxx/uwsgi.ini directory=/home/work/xxxx startsecs=0 stopwaitsecs=0 autostart=true autorestart=true and my uwsgi.ini content is: [uwsgi] socket = :8000 chdir = /home/work/xxxx module = xxxx.wsgi master = true processes = 4 vacuum = true xxxx is my project name. I run supervisorctl -c /etc/supervisord.conf restart all in the cmd. And it shows xxxx: ERROR (no such file) I don't know why it will report error like that.I can run my django project with runserver.so what the file is missing? -
Is there any reason to use big frameworks like ROR or Django while more and more logics move to client side?
When I started to write for web I started with writing REST interfaces on D/C# and some web-frameworks like Vue.js for browser side. And now when I turn back I can't understand did I missed something or not trend is changed and it's time for micro-server frameworks mainly uses for REST API generation? I ask because it's seems that now all logics move from server side to client side. And for example validation is not doing in JS. Is there any profits not in learning Django or ROR now? For which tasks they are good for now? -
How to create models for a specific database in django ?
Whenever a model is created.. it is created in the default database . How can we specify in which database the model should should be created. I looked at custom routers in django documentation but could not understand it. Can anyone provide example with the code. -
python-social-auth Twitter login returns Authenitcation Failed
I'm trying to use python-social-auth to register and login users through Google, Facebook and Twitter (initially). Google and Facebook are working but with Twitter I'm getting the following error: AuthFailed at /login/twitter/ Authentication failed: ('bad handshake:SysCallError(0, None)',) Here's the traceback: Traceback: File "/var/www/ian/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/var/www/ian/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/var/www/ian/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/ian/env/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/var/www/ian/env/lib/python2.7/site-packages/social_django/utils.py" in wrapper 50. return func(request, backend, *args, **kwargs) File "/var/www/ian/env/lib/python2.7/site-packages/social_django/views.py" in auth 19. return do_auth(request.backend, redirect_name=REDIRECT_FIELD_NAME) File "/var/www/ian/env/lib/python2.7/site-packages/social_core/actions.py" in do_auth 27. return backend.start() File "/var/www/ian/env/lib/python2.7/site-packages/social_core/backends/base.py" in start 34. return self.strategy.redirect(self.auth_url()) File "/var/www/ian/env/lib/python2.7/site-packages/social_core/backends/oauth.py" in auth_url 166. token = self.set_unauthorized_token() File "/var/www/ian/env/lib/python2.7/site-packages/social_core/backends/oauth.py" in set_unauthorized_token 222. token = self.unauthorized_token() File "/var/www/ian/env/lib/python2.7/site-packages/social_core/backends/oauth.py" in unauthorized_token 246. method=self.REQUEST_TOKEN_METHOD File "/var/www/ian/env/lib/python2.7/site-packages/social_core/backends/base.py" in request 222. raise AuthFailed(self, str(err)) Exception Type: AuthFailed at /login/twitter/ Exception Value: Authentication failed: ('bad handshake: SysCallError(0, None)',) My HTML link is through: <a href="{% url 'social:begin' 'twitter' %}" class="btn btn-block btn-social btn-twitter"><span class="fa fa-twitter"></span>Sign in with Twitter</a> My urls.py is: url(r'', include('social_django.urls', namespace='social')), And my settings.py has the following changes: INSTALLED_APPS = [ ... 'social_django', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Interactive shell in Django
I would like to get an interactive shell with the code, but I don't even know if such thing exits. Could anyone be able to help me at this point? -
Django-Leaflet: displaying multiple points via query and foreignkey relationship
I want to be able to display all of the items on the map shown in my query. Currently only getting one marker to display via the for loop. Is there a way to do this? Would iterating through the query in JavaScript work to add each marker? The model design needs to stay the same. Any thoughts/ideas extremely appreciated!! Map Script <script> {% for item in latest %} var collection = {{ item.location|geojsonfeature|safe }}; function onEachFeature(feature, layer) { layer.bindPopup(feature.properties.station_name.toString()); } function mapInit(map, options) { map.setView([38.46, -106.9], 10); map.locate({setView: true, maxZoom: 15}); L.geoJson(collection).addTo(map); } {% endfor %} </script> View Query: latest = Measurement.objects.order_by('-id')[10] Models class Location(gismodels.Model): station_name = models.CharField(max_length=150) site_name = models.CharField(max_length=150) flood_stage = models.FloatField(null=True, blank=True) geom = gismodels.PointField() objects = gismodels.GeoManager() class Measurement(models.Model): station = models.CharField(max_length=10) stage_feet = models.FloatField(null=True, blank=True) location = models.ForeignKey(Location, on_delete=models.CASCADE) -
export to CSV on Django
I would like to add this script on a Django portal. I've already created a template for this page. So, only tr_id going to change dynamically. In this script tr_test_cases.tr_id = '210217A' <a href="{% url 'testing:export_csv' tr_details.tr_id %}">Export CSV</a> When users click the above link, I would like export file with related tr_id. How can I create a view for this script? Any helps would be appreciated. import csv import MySQLdb import sec #Security details # Decoding and defining username and password for DB connection. username = sec.decode(sec.user) password = sec.decode(sec.password) db = MySQLdb.connect(host="sample.com", user=username, passwd=password, db="django_db") cursor = db.cursor() # Query to obtain all TR results required for Cisco cursor.execute( "SELECT results_stb_id, results_stbs.stb_id, stb_inv.mac_add, " "test_functionality.test_functionality_code, test_cases.test_case_no, " "SCRIPT.option_name AS script_result, POST.option_name AS post_result, " "results_tests.started, results_tests.stopped, results_tests.test_duration, builds.baseline, " "builds.build_type, stb_hw_info.stb_type, defects.defect_name, parser_output, log_url, " "script_health_score, post_health_score FROM results_stbs " "JOIN tr_test_cases " "ON tr_test_cases.tr_test_case_id=results_stbs.tr_test_case_id " "JOIN test_cases " "ON test_cases.test_case_id=tr_test_cases.test_case_id " "JOIN test_functionality " "ON test_functionality.test_functionality_id=test_cases.test_functionality_id " "LEFT JOIN stb_inv " "ON results_stbs.stb_id=stb_inv.stb_id " "LEFT JOIN result_options AS SCRIPT " "ON results_stbs.script_result=SCRIPT.result_option_id " "LEFT JOIN result_options AS POST " "ON results_stbs.post_result=POST.result_option_id " "JOIN results_tests " "ON results_stbs.results_test_id=results_tests.results_test_id " "JOIN builds " "ON builds.build_id=results_stbs.build_id " "JOIN stb_hw_info_ids " … -
cannot upload image to django
I need to upload an image to django server with django rest framework. I tried to post the image using httpie and I am getting this error. http 400 no image was submitted. serializers.py from rest_framework import serializers from myapp.models import * class PhotoSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None,use_url=True) class Meta: model = MyPhoto fields = ('id', 'image') models.py from django.db import models class MyPhoto(models.Model): image = models.ImageField(upload_to='photos/', max_length=254) views.py from rest_framework.views import APIView from myapp.models import * from myapp.serializers import PhotoSerializer from rest_framework import status from rest_framework.response import Response from rest_framework.parsers import FormParser, MultiPartParser class PhotoList(APIView): parser_classes = (FormParser, MultiPartParser) def get(self, request, format=None): photo = MyPhoto.objects.all() serializer = PhotoSerializer(photo, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) def post(self, request, format=None): serializer = PhotoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have set MEDIA_ROOT and MEDIA_URL. Please help. Thanks in advance. -
Except doesnt work in django
I have 2 html page in django project. One consist: <title>{% block title %}{% endblock %} &ndash; Blog</title> and <div class="container"> {% block content %} {% endblock %} </div><!-- /.container --> Another html file have next: {% extends 'blog/base.html' %} {% block title %} Home {% endblock %} {% block content %} <p>bla bla </p> {% endblock %} So question in next: file in browser i cant see any from seconds document? Looks like extends doenst working. Screenshot: http://prntscr.com/ecuxto -
How to pass arguments to custom save method of django model?
This should be easy and there is another question on SO that addresses the issue ( passing an argument to a custom save() method ) but that solution isn't working for me. In my view I have form.save('test string') and in the corresponding model I have def save(self, test, *args, **kwargs): x = test ... super(MyModel, self).save(*args, **kwargs) But I keep getting save() missing 1 required positional argument: 'test' I have tried form.save(test='test string') but that results in save() got an unexpected keyword argument 'test'. Finally, I changed the method signature to def save(self, *args, **kwargs) and then in the view tried form.save({'test': 'test string'}) there is no error but nothing appears in the kwargs. I'm using django 1.10 if that matters. Please help and thank you! -
python-social-auth with django Facebook error
I'm trying to use python-social-auth for authentication and I'm running into some problems with Facebook and Twitter (Google is working). For Facebook I am getting an HTML page stating: The www.facebook.com page isn’t working Here's my template link: <a href="{% url 'social:begin' 'facebook'%}?next={{ index }}" class="btn btn-social-icon btn-facebook"><span class="fa fa-facebook"></span></a> Here's my url.py: url('', include('social_django.urls', namespace='social')), And some info from settings.py INSTALLED_APPS = [ ... 'social_django', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_FACEBOOK_APP_KEY = 'my app key' SOCIAL_AUTH_FACEBOOK_APP_SECRET = 'my app secret' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_APP_NAMESPACE = 'my name spance' -
bootstrap form duplicated content
I have page structure on desktop like this: <form> ___________________________________________________ | | | [] checkbox | | <div></div> | | <div></div> | |_________________________________________________| </form> On mobile i want to have like this : <form> ____________________ | | | <div></div> | | <div></div> | | []checkbox | |__________________| </form> tried to play with .visible-sm .hidden-lg and etc. but problem is that checkbox is same (cloned - same name, id, class) and when submiting form they ar confusing all the logic. If first ir checked but second not, in post i still get that it's checked. What should i do in this case ? Checkeboxes are toggles (bootstrapetoggle.com) -
How does front-end and back-end communicate with each other? (Python)
I have decent grasp on HTML, CSS and JavaScript, as well as Python (and a very limited understanding of Django). I’ve gotten basic web apps up and running solely using Python & Django, but I don’t understand how that can be used to work directly with the front-end. I.e. If I have a fully functional single page website with HTML, CSS & JavaScript, and I want a Python script to run and return a value when a button is clicked, how do I communicate that Python script with the front-end? How / where is the Python script actually hosted? How is the returned value added to the front-end for the user to see? I've read through a number of resources, but can’t seem to get a clear guide on how it works. From my understanding of what I’ve read, it can be done through AJAX or POST/GET/DELETE methods, but I don’t have any previous experience with them. It’s killing me trying to find an answer (that I can understand) to this, so even though it’s probably beginner stuff I would be hugely grateful if someone can point me in the right direction. -
How can I make authenticated request to django view from external html using ajax
I am using django 1.10, I have following html pages register.html, login.html, home.html Html pages are deployed on different application server. I am using Custom user model, I can able to register and store details into database. Also able to authenticate and login into app and get redirected to home page. Problem : I have sample view named as, test @login_required def test(request): l=[] l.append('x') l.append('y') return JsonResponse({"records": l}) so after login, when I directly access url as, localhost:8000/app/test then I am able to get data in browser. But after login, within same session, when I am calling same url from home.html, I am not able to authenticate and receive data. In browser console it will become as, http://127.0.0.1:8000/accounts/login/?next=/app/test/ There were some posts which refers solution as @ajax_required, as I am new to django, I didn't find any post in detail. Can anyone please explain or suggest solution with sample example. Thanks in advance. -
Passing information to modal in for loop
Im attempting to change the way that my table currently works. Right now the table is created by looping through all of the samples passed to it through the context in views.py of my Django app, and that works fine. The change i want to make however is to create a modal when the delete sample button is clicked show the user a warning message before they delete it. The problem im running into is that the {{ sample.id }} in the modal is identifying the first sample in the table (seems to not be part of the for loop). Any help would be much appreciated! <table class="table table-themed sample-table"> <tr> <th>Status</th><th>Mh to Mh</th><th>Shot & Sec</th><th>Date Created</th><th>Manage</th> </tr> {% for sample in samples %} <tr> <td>{{ sample.status }}</td> <td>{{ sample.mh_to_mh }}</td> <td>{{ sample.shot_and_sec }}</td> <td>{{ sample.date_created }}</td> <td> <a class="btn btn-primary" href="{% url 'contracts:view_sample' sample.id %}">View Details</a> <a class="btn btn-danger btn-sm" href="{% url 'contracts:delete_sample' sample.id %}">Delete</a> <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal">Delete Modal</button> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Delete Sample</h4> </div> <div class="modal-body"> <p>Are you sure that you want to delete this … -
403 Forbidden and request.method showing GET in django
I am trying to send a form data to an app using AJAX. Javascript part: function submit_changes() { var all_data = [A_list, B_list,C_list] $.ajax({ type: "POST", url: "/my_url/", contentType: "application/json", //dataType: 'json', //data:JSON.stringify(all_data), data:{ csrfmiddlewaretoken: "{{ csrf_token }}", form:JSON.stringify(all_data), }, success: function() { alert('Data captured successfully'); //window.location.reload(); }, error: function(){ alert('Error in data capture') //window.location.reload(); } }); } urls.py has this urlpatterns=[url(r'^my_url/$',views.my_url_fn)] views.py def my_url_fn(request): print "*** request is ***",request if request.method == 'POST': print "request is POST" return Response(json.dumps(submit_changes(request))) elif request.method == 'GET': print "request is GET" return Response(json.dumps(get_already_present_data()),mimetype='application/json') else: print "neither post nor get" Form part from html code is: <div align="center"> <form name="myForm" onSubmit="return 0">{% csrf_token %} <input type="text" id="blah1" placeholder="Blah1&hellip;"> <!-- few more fields --> </form> </div> <div align='center'> <input id="submit_changes" type="button" align="middle" value="Submit Changes" onclick="submit_changes();" /> </div> I have loaded the javascript in html. I am getting 403 forbidden error and the request.method is printing GET. I have two things to ask : 1). Why is request.method GET when it is a POST request? 2). Why am I still getting 403 forbidden error even after giving csrf token? I have searched a lot and tried these: Adding @csrf_exempt above my view and importing it as … -
Django : HTML form action directing to view (or url?) with 2 arguments
Started learning django about a week ago and ran into a wall. Would really appreciate any enlightenment... models.py class data(models.Model): course = models.CharField(max_length = 250) def __str__(self): return self.course html Converted the objects in models.course to schlist <link rel="stylesheet" type="text/css" href="{% static '/chosen/chosen.css' %}" /> <form action={% views.process %} method="GET"> <div> <h4 style="font-family:verdana;">First Course: </h4> <select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7"> <option value=""></option> {% for item in schlist %} <option> {{ item }} </option> {% endfor %} </select> </div> </br> <div> <h4 style="font-family:verdana;">First Course:</h4> <select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7"> <option value=""></option> {% for item in schlist %} <option> {{ item }} </option> {% endfor %} </select> </div> </br> <input type="submit" value="Compare!" /> </form> urls.py (having my doubts if this works..) urlpatterns = [ url(r'^(\d+)/(\d+)$',views.process, name = 'process'), ] view.py def process(request,q1 ,q2): obj1= get_object_or_404(Schdata, course = q1) obj2= get_object_or_404(Schdata, course = q2) ........ Was wondering if it is possible for the form action to direct the action to (1) view.py or (2) url.py (and eventually to a view.py) with 2 arguments selected? If so how should the form action be? {{view ?}} or {{url ?}}. Am I missing out the definition of my arguments in my HTML? Directing to views.py: User … -
getting error 404 in django framework python
I am newbie in django and I try to build webapp by using django framework to upload image and show on web page. After somehow solving many errors form urls.py finally server run but at last again Page not found (404) error on web page. i upload all necessary code below. myproject/myproject/settings.py """ Django settings for myproject project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '2z$tk#wj&&pc(0ps4!7w_o_lm4h!3flwy+8%%s3k5pqars=ta&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ) MIDDLEWARE_CLASSES = ( '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', ) ROOT_URLCONF = 'myproject.urls' WSGI_APPLICATION = 'myproject.wsgi.application' Database https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': os.path.join(PROJECT_ROOT, 'database/database.sqlite3'), # Or path to database file if using sqlite3. 'USER': … -
Take account screen size to display Django website
I'm a bit lost with CSS handling in order to manage stylesheet about screen size. I'm developing a Django website project and I'm confronting to a very delicate situation. My project is developped on a very good screen (Retina screen) with a very high resolution. But, when I'm watching my project on a very bad screen resolution, some elements are not situated where it should be. I put for example part from a .css file corresponding to HTML base template : /* ############################################# */ /* CSS File about Home application properties */ /* ############################################# */ @import url("http://bootswatch.com/flatly/bootstrap.min.css"); /* If screen less than 1440px */ @media screen and (max-width: 1440px) { .navbar-right { /*padding-left: 250px;*/ position:absolute; right:2%; } } /* If screen bigger than 1440px */ @media screen and (min-width: 1450px) { .navbar-right { /*padding-left: 400px;*/ position:absolute; right:2%; } } /* Define background color from upper navbar */ .navbar-inverse { background-color: #007A5E !important; } /* DatasystemsEC tab */ .navbar-inverse .container-fluid .navbar-header .navbar-brand { color : white; } /* Tab properties from navbar */ .navbar .nav > li > a { color: white; } footer { text-align: center; margin-top: 35%; } How I can handle CSS stylesheet in order to adapt the …