Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make my django site secure
I am developing a django website,and I know that django is a highly secure framework. But do i need to further install additional security packages to make my site more secure? If so, can you please give me some recommendations?thank you! -
Improve Nginx configuration file for Django and static home page
I have setup an Nginx server on an EC2 instance (running ubuntu 16.04). I also have two A value DNS entries, for @ and www, both pointing to the same IP. I only use one certificate for www.example.com, so I point the example.com to www.example.com in Nginx. I feel the website is sometimes slow. I think it has something to do with my Nginx config. Also, I want to make sure that the single certificate idea wouldn't cause any security warnings for clients (I tested it and it seems fine). I'm not awfully familiar with this DevOps kind of tasks, so just want to be sure that I'm not doing some noob mistakes, and that I can safely go with this setting into production. Thanks! Nginx config file: server { server_name www.example.com; access_log /var/log/nginx/example.com.log; error_log /var/log/nginx/example.com.error.log debug; root /home/ubuntu/example.com/homepage; # if the uri is not found, look for index.html, else pass everthing to gunicorn location / { try_files $uri $uri/index.html @gunicorn; } # Django media location /media { alias /home/ubuntu/example-django/public/media; # your Django project's media files } # Django static files location /static { alias /home/ubuntu/example-django/public/static; # your Django project's static files } location @gunicorn { proxy_pass http://0.0.0.0:8000; proxy_set_header Host … -
ImportError: No module named celery
I'm trying to get periodic tasks running with my Django project as per this tutorial. However, when trying to run the Celery worker with the command below: celery -A myproject worker -l info I get the following error: File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named celery I suspect it may be because my settings files (local.py and production.py) are not as per the standard Django file structure, they are nested one folder lower. ├── myproject │ ├── myproject │ │ ├── __init__.py │ │ ├── settings │ │ │ ├── __init__.py │ │ │ ├── base.py │ │ │ ├── celery.py │ │ │ ├── local.py │ │ │ ├── production.py │ ├── manage.py __init__.py # myproject/myproject/settings/__init__.py from __future__ import absolute_import, unicode_literals from .base import * try: from .local import * live = False except: live = True if live: from .production import * from .celery import app as celery_app celery.py # myproject/myproject/settings/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.local') app = Celery('myproject') # Using a string here means the worker don't have to serialize # the configuration object … -
Email reset not working once deployed to AWS
I'm having trouble setting up email reset on my django app. When run locally it works perfectly well and the email is sent. However once I deploy to aws elastic beanstalk, the email never seems to send but no error is given. Does anyone know why this may be the case and how to potentially solve it? -
Trying to deploy an app in Production getting this No module named 'django.urls' error
Django Version: 1.8 Python Version: 3.5.2 Getting this Error when i'm running this app on production, from Windows to Linux PC Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'dasboard') Traceback: File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 119. resolver_match = resolver.resolve(request.path_info) File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/django/core/urlresolvers.py" in resolve 366. for pattern in self.url_patterns: File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/django/core/urlresolvers.py" in url_patterns 402. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/django/core/urlresolvers.py" in urlconf_module 396. self._urlconf_module = import_module(self.urlconf_name) File "/home/ubuntu/var/www/django_env/lib/python3.5/importlib/__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "/home/ubuntu/var/www/mydashboard/mydashboard/urls.py" in <module> 3. from dasboard import views File "/home/ubuntu/var/www/mydashboard/dasboard/views.py" in <module> 6. from rest_framework.response import Response File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/rest_framework/response.py" in <module> 13. from rest_framework.serializers import Serializer File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/rest_framework/serializers.py" in <module> 30. from rest_framework.compat import postgres_fields, unicode_to_repr File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/rest_framework/compat.py" in <module> 26. from django.urls import ( **# noqa** Exception Type: ImportError at / Exception Value: No module named 'django.urls' I am not using Postgres simple sqlite db.. Please help! -
perpopulate data from database to django form
Hi i am trying to prepopulate the values from my database into the django form. I tried to pass the object instance from model.py i was not able to render the value, Is their a better way to render it. ??? Here is my code view.py class myview(TemplateView): def get(self,request): userinfo = UserInfo.object.get(id=1) form = UserForm(form) return render(request,'user.html',{'form':form}) template.html {{form.username}} {{form.address}} It throw me a error User object has no attribute 'get' Thanks in advance -
django group by count on distinct multiple fields
I'm trying to achieve the following SQL statement in Django: SELECT org_type, count(org_type) FROM ( SELECT DISTINCT ON (org_name, org_type) org_name, org_type FROM orgs ) t1 group by org_type I'm running the following, however I'm not getting the correct counts: orgs.objects.values('org_name','org_type').distinct().values('org_type').annotate(Count('org_type')) It looks like the above is the same as running: orgs.objects.all().values('org_type').annotate(count=Count('org_type') -
Login button won't fire
I'm using Django and AngularJS in a log in form. In this case, the username is in email format. My login form's button will only become un-disabled when the user enters a string formatted like an email address and a password of at least eight characters. But clicking the login button does nothing. Nothing fires. No POST request is made. forms.py: class LoginForm(AuthenticationForm): ''' Form to log in a user ''' error_messages= { "invalid_login": _("Incorrect %(username)s/password combo") } title= "Sign in" username= forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={"id":"id_login_username", "type":"email", "placeholder":"Email", "ng-model":"login.email"})) password= forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs={"placeholder":"Password", "ng-model":"login.pw", "ng-minlength":settings.MIN_PW_LENGTH})) urls.py: urlpatterns += [url("^login-register/$", views.login_register, name="login_register"),] views.py: def login_register(request, template="pages/login_register.html"): registration_form= RegisterForm() return render(request, template, {"registration_form":registration_form}) login_register.html: {% extends "base.html" %} {% load i18n mezzanine_tags staticfiles %} {% block meta_title %}{% trans "Register or log in" %}{% endblock %} {% block title %}{% trans "Register or log in" %}{% endblock %} {% block extra_head %} <meta name="robots" content="noindex"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> {% compress js %} <script src="{% static "js/login-register.js" %}"></script> {% endcompress %} {% endblock %} {% block main %} <form id="login-form" name="loginForm" method="post" ng-app="app" ng-controller="Ctrl"> {% csrf_token %} {% if login_form.non_field_errors %} <p class="text-danger" role="alert">{{ login_form.non_field_errors.as_text|cut:"* "|escape }}</p> {% endif %} {% for field in login_form %} <p>{{ … -
Custom User registration in django using django rest framework
I'm building a REST backend using django rest framework. Here's my modified User model in django, class User(AbstractBaseUser, PermissionsMixin): mobile = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=255, null=True) username = models.CharField(max_length=255, null=True) full_name = models.CharField(max_length=255, blank=True, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True) Now I wish to expose an endpoint that collects the following data as a POST request - mobile, email, username, full_name, password again. -A Normally to create objects I would use Serializers. But I've no idea how to go about this one. I've checked the following SO question, but it's tailormade for forms. Custom user registration in Django So in essence, I guess my questions is, how can I expose an endpoint to gather the data mentioned in -A above and create an User object from that in django. -
Django - Two fields' can have the same value only if their primary keys are not the same
Is there any built-in solution in Django for letting two field having the same value only if their primary keys are different. E.g. two children can have the same name only if their mother is NOT the same: class Child(models.Model): name = models.CharField(max_length=25, blank=False) mother = models.ForeignKey(Mother, on_delete=models.CASCADE, blank=False) class Mother(models.Model): name = models.CharField(max_length=25, blank=False) -
Django module to shorten css classes in production
I have a css class: .footer-react-btn{ color:#ddd; } But if I change .footer-react-btn to .a or .b, then I might save some bytes of text from being loaded. I want it to happen in my production. I will be writing the code in an understandable manner during my development. So, Is there any way I can do it in? I am new here. I need an explanation step by step. -
Getting traceback error on Django installation?
I am trying to get Django going with mySQL. I have started the app I can see all manage.py and other files. and in setting i changed: # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'app', 'USERNAME': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', } } I have installed mySQL separately, I have XAMPP I started it but when I run: python manage.py migrate I get the following errors: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
SQLite - Joining Tables using Django
I am not a coder by any means but I have to do a project for college and I am really stuck, any help would be greatly appreciated. I am using Django and SQLite. I want to join the auth_user table with an input table that I created. I have run the following SQL join which has given me the result I want.(Which is that every user has there own waist measurement) But my issue is I don't know how to implement this into Django? This is my SQL statement: Sql Please Help! -
Django checkbutton for todo
I'm pretty new to Django, so please make it newbie friendly :D. Its about a simple todo-list. I want every item to have three Buttons for deleting, editing or in this case checking. In the following code I wanna create a check-button which sets a boolean value to True. But instand of doing anything the code is just refreshing the side. No error-messages or further information in the command. So can you guys spot the mistake? Glad for your help. HTML: <form method="POST"> {% csrf_token %} <button id="done" type="POST" action="{% url 'complete' do.id%}"> <i class="fas fa-check"></i></button> <button id="edit"><i class="fas fa-edit"></i></button> <button id="delete" action="#" method="POST"><i class="fas fa-trash"></i></button> <a href="/todo/{{do.id}}">{{do.task_title}}</a> </form> </li> url: urlpatterns = [ # match list, url(r'^$', views.index, name='index'), url(r'^add/$', views.addTodo, name='add'), url(r'^(?P<pk>[0-9]+)/complete/$', views.completeTodo, name='complete'), .. ] view: def completeTodo(request, todo_id): if request.method =='POST': print('alive') todo = Task.objects.get(pk=todo_id) todo.complete = True todo.save() return redirect('index') Model: class Task(models.Model): task_title = models.CharField(max_length=50) task_explain = models.CharField(max_length=1500) complete = models.BooleanField(default=False) def get_absolute_url(self): return reverse('todo:detail', kwargs={'pk':self.pk}) def __str__(self): return self.task_title -
call a view in another app with additional url parameter or query string
in my explore/views.py I have: class A(APIView): def get(self,request,format=None): #process many query string options and other checkups here return JsonResponse(data,status=status) The view is called from several applications in the following way to avoid reptition. in my second app (second/views.py): from explore.views import A class Show(APIView): def get(self,request,partner_id,format=None): view=A.as_view() return view(request) It does work as expected. But now, I need to adjust something to A view based on partner_id. Is there a way to pass partner_id to explore/views.py A view in a manner that won't affect the current app significantly? The request have the option to pass query string and I am ok to passing partner id as query string. I already tried: explore/urls.py: url(r'^a/$', views.A.as_view(), name='a'), url(r'^a/(?P<partner_id>[0-9]+)/$', views.A.as_view(), name='a'), and adding partner_id=0 to the get method but it doesn't have an effect so far. -
Django testing, can't see anything in test database
I am running some tests in Django using from django.test import TestCase and subclassing that. My tests run, but when I step through them in debug mode, I want to check what is happening in MySQL. But I can't see anything in MySQL. (I am using a settings file that points to a local instance of MySQL for the tests). Logging into MySQL via the command line, or Pycharm I can see that he test_database gets created correctly (and torn down after the test have run. But when I query any tables they via the mysql client, they are empty. I can use the ORM to do CRUD operations on the database and they behave as expected (viewing the objects in PyCharms debugger). Why can't I see any data in MySQL? Are the tests wrapped in some transaction so that a different login won't see those changes? Is there a setting I need to change? -
React Native Fetch API - can't access son or body of response
Trying to call an API to my backend with Fetch, but I can't access the response body. There's a loot of different notation and syntax about this on the internet and I can't figure out how to do it properly. I've tried response.json() and responseJson, and stringyfying both. I don't get what I want which is the actual body of the response. It's meant to have a key/token that I then save. responseJson returns this: responseJson: {"_40":0,"_65":0,"_55":null,"_72":null} This is my function: export function LogIn(em, pass) { return (dispatch) => { console.log('LogIn called'); dispatch(logInIsLoading(true)); //from phone *fetch('http://192.168.1.18:8080/rest-auth/login/', { method: 'POST', headers: { // 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ 'email': em, 'password': pass, }) }).then((response) => { console.log("response " + JSON.stringify(response)); if (!response.ok) { console.log("ERROR: " + response.statusText); throw Error(response.statusText); } dispatch(logInIsLoading(false)); return response; }) .then((response) => { responseJson = response.json(); console.log("responseJson: " + JSON.stringify(response.json())); return responseJson }) .then((responseJson) => { AsyncStorage.multiSet([['key', responseJson.key], ['loggedIn', true]], () => { console.log(responseJson.key); dispatch(isLoggedIn(true)); dispatch(getKey(responseJson.key)); }); })* .catch(() => dispatch(logInHasErrored(true))); }; } -
python3 pip3 and django 2 confusion
I'm new to Python so please help me understand this: From Django's documentation: I need python 3+ to run Django 2+ and I need to check my version by running this: $ python -m django --version $ python --version Python 2.7.14 $ python -m django --version 1.11.10 However I've installed python3 and pip3 in order to install (or upgrade?) Django 2 so: $ python3 -m django --version 2.0.2 It seems to me that there are 2 python run parallely on my machine (Linux Ubuntu 17) so what I did was not upgrading Python, pip or Django but installing a newer version of them. Some answers on stackoverflow suggest that I should not use pip3 to upgrade Django. So how do I use python3 to test my app and work with Django 2? From Django's documentation, all commands for Django 2 use python, not python3. Should I assume they mean python3? -
Sidebar Navigation to Tabbed Navigation Transition - Django Newbie
I am new to Django and front-end design. I have tried several attempts to make the site navigation in sidebar for bigger screen then tabbed navigation for smaller screen. Here are the screenshots: Sidebar Navigation: enter image description here Tabbed Navigation (current): enter image description here Tabbed Navigation (desired): enter image description here And here's my last attempt using bootstrap 3.3.7: .sidebar-nav { margin-top: 20px; padding: 0; list-style: none; } .padding-small { padding-top: 15px; } .orange-background { background-color: #FFF3E0 !important; } <div class="container-fluid"> <div class="row"> <div class="orange-background col-sm-2"> {% block sidebar %} {% if user.is_authenticated %} <div class="padding-small">Hi, cipals15!</div> {% endif %} <ul class="sidebar-nav"> <li><a href="{% url 'index' %}">Home</a></li> <li><a href="{% url 'dorms' %}">All Dorms</a></li> <li><a href="{% url 'schools' %}">By School</a></li> <li><a href="{% url 'schools' %}">By Establishment</a></li> {% if user.is_authenticated %} <li><a href="{% url 'logout' %}?next={{request.path}}">Logout</a></li> {% else %} <li><a href="{% url 'login' %}?next={{request.path}}">Login</a></li> {% endif %} </ul> {% endblock %} </div> </div> -
Writable nested Django Serializer error
I have this issue: class UserProfiles(models.Model): user = models.OneToOneField(User) role_alt = models.CharField(max_length=256, null=False) class ProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfiles fields = ('role_alt', ) class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username', 'email', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) UserProfiles.objects.create(user=user, **profile_data) return user getting Error: Got AttributeError when attempting to get a value for field profile on serializer UserSerializer.The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'profile'. -
Can't text compare Django model field
I have a "Report" model set up in Django that represents a specific report uploaded to the site. This model has a ForeignKey relationship to a "UserTechnology" model which is a list of all the available ways an end user can access the uploaded reports. I am displaying these reports and some information about them on the index.html page. I'd like to switch the url passed to the where we link the report based on the "UserTechnology" value that the specific report has. The problem comes when trying to compare a report's UserTechnology value to anything. For example, if I just display {{ report.UserTechnology }} it works fine, with an example value of "FileManager". But if I try something like {% "file" in report.UserTechnology %} or {% report.UserTechnology == "FileManager %} it always returns False. I think the problem is that I'm not comparing what I think I'm comparing when dealing with ForeignKey relationships, but I'm not sure how to access the value of UserTechnology.Name for a specific report other than report.UserTechnology. models.py: class Report(models.Model): Name = models.CharField(max_length=200, default=None, null=True) LastUpdated = models.DateTimeField('date published', default=None, null=True) SharePointURL = models.CharField(max_length=500,default=None, null=True) FileManagerLocation = models.TextField(default=None, null=True) ReportText = models.CharField(max_length=400, default=None, null=True) ReportImage … -
Trying to access model in form by going through another model
I am not that good at queries, so I need some help. I have a Course model, and a TeacherData model. Each teacher has its own courses. But when a teacher makes an account I use a Teacher model. And if teacher_ID column from TeacherData doesn't match the one entered by the user, the account cannot be created. Now, in my form I need to show Courses for each teacher, so that a Lecture instance can be created. I was thinking to use teacher_ID as bridge connecting Teacher model with TeacherData model and then I would be able to show the courses that only a specific teacher has. This is what I tried: class LectureForm(forms.ModelForm): lecture_title = forms.CharField(max_length=100, required=True) course = forms.ModelChoiceField(initial=Course.objects.first(), queryset=Course.objects.filter( Q(teacher1__surname__in=[t.surname for t in TeacherData.objects.filter( Q(teacher_ID__iexact=[x.teacher_ID for x in Teacher.objects.all()]))]))) class Meta: model = Lecture fields = ('course', 'lecture_category', 'lecture_title', 'content') -
Conversion to python of C code
For use in a web backend (django) project, I am given the following C code snippet: /* architecture is x86_64, strings are ASCII */ /* example output: * 7KL753WG => 680403628 * 043NM2B6 => 517135930 * 7B6ISP72 => 058511020 */ char buf[33]; char* unlock(char *s) { char token[9]; char scrambled[9]; long long *ltoken; strncpy(token,s,9); ltoken=(long long *)token; *ltoken *= 610; *ltoken ^= 0x5A5A5A5A ; buf[32]='\0'; int i = snprintf(buf,32,"%lld",*ltoken); return buf+i-9; } In words: take an 8 char ascii string, use its bit pattern as a long, apply a couple of computations, take the last 9 digits of the result. For obvious reasons, I'd hate to shell out to call the binary, and would like to convert it to python 2.7. On the other hand, I have tried the obvious (struct.pack, struct.unpack) and the exotic (ctypes) with no joy. I assume ctypes is the way to go, but I have never used it so my attempts are basically poking at it with a stick. (And yes, I know that the algorithm itself is not pretty - luckily not something I wrote) TIA -
In Django, how do I add the contents of two fields and display the results in a third field?
I'm trying to learn Django and am finding it frustratingly difficult to do fairly basic things. I have the following form classes: from django import forms class InputForm(forms.Form): field1 = forms.FloatField(label="First field: ") field2 = forms.FloatField(label="Second field: ") class OutputForm(forms.Form): outfield = forms.FloatField(label="Result: ") And the following template: <form> {{ input_form.as_ul }} </form> <form action="#" method="get"> <input type="submit" class="btn" value="Submit" name="submit_button"> </form> <form> {{ output_form.as_ul }} </form> And finally, the following view: from django.shortcuts import render from .forms import InputForm, OutputForm def index(request): if request.GET.get('submit_button'): # ????? else: input_form = InputForm() output_form = OutputForm() return render(request, 'index.html', {'input_form': input_form, 'output_form': output_form}) All I want to happen is that when I hit the submit button, the values in first field and second field get added and displayed in the result field. I know from debug outputs that the ????? commented block is run when I press the button, but I have so far not been able to figure out what to do to actually access or alter the data in my fields. I don't care about keeping a record of these transactions so it feels like storing these in a database is tremendous overkill. What is the correct way to approach … -
Django migrations: how to conditionally switch between migration statements according to current DB backend?
I use Django with SQLite in my dev environment and postgreSQL in production. I know that having different DB backends for dev and prod is a tech debt, but this is the current state of affairs for now (not for long, hopefully). I would like to take advantage of the postgres JSONField in production while in dev keep using django-jsonfield. Is there a way to write a migration so that it can conditionally switch between the two types of field depending on which backend is currently being used?