Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-SessionId: Why i get same session id upon opening 2 tabs in chrome for same url (127.0.0.1:8000?
I am new to django (or web development). I see same session id for two instances for my test project, is there any way to get unique id every time user opens that url? I am not using any user login here. views.py: def index(request): print(request.session.session_key) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'$', views.index,name='index'), ] Output on server: Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. q4ynuuj7hbugoxcn7to0izr39nip4of6 <QueryDict: {}> [31/Dec/2017 13:29:49] "GET / HTTP/1.1" 200 8224 q4ynuuj7hbugoxcn7to0izr39nip4of6 <QueryDict: {}> [31/Dec/2017 13:29:54] "GET / HTTP/1.1" 200 8224 -
The submitted data was not a file. Check the encoding type on the form?
I have a serializer called ProjectSerializer. It has a file field. The view is: class ProjectCreate(CreateAPIView): serializer_class = ProjectSerializer When I post data from html form in django rest framework, it works the file gets uploaded. But when I use the raw data as json and send data by using url of the file content the error arises: { "project_question_content_url": [ "The submitted data was not a file. Check the encoding type on the form." ] } The problem is I am using jquery to provide the url ..But before sending the url from jquery I tested in the api. It gives the error while providing the url . -
How to do performance optimization while serializing lots of GeoDjango geometry fields?
I'm developing a GeoDjango app which use the provided WorldBorder model in the tutorial. I also created my own Region model which is tied to WorldBorder. So a WorldBorder/Country can have multiple Regions which has borders (MultiPolygon field) in it too. I made the API for it using DRF but it's so slow, it takes 16 seconds to load all WorldBorder and Regions in GeoJSON format. The returned JSON size is 10MB though. Is that reasonable? I even change the serializer to serpy which is way much faster than the DRF GIS serializer but only offers 10% performance improvement. Turns out after profiling, most of the time is spent in the GIS functions to convert data type in the database to list of coordinates instead of WKT. If I use WKT, the serialization is much faster (1.7s compared to 11.7s, the WKT is only for WorldBorder MultiPolygon, everything else is still in GeoJson) I also tried to compress the MultiPolygon using ST_SimplifyVW with low tolerance (0.005) to preserve the accuracies, which brings down the JSON size to 1.7 MB. This makes the total load to 3.5s. Of course I can still find which is the best tolerance to balance accuracy … -
Django authenticate method not working
I am trying to use the default Django from django.contrib.auth authenticate() method to authenticate if the user exists. I am doing this right after the user registers. The user registers and their username, email, and password is inputted into the database, but when I call authenticate(username=username, password=password) it is returning None for some reason. The password is being stored as a hash and it is worth to note that I am using my own custom User model, but inheriting from django.contrib.auth User model. Here's my view: class RegisterView(SuccessMessageMixin, View): form_class = RegisterForm template_name = 'oauth/auth_form.html' success_message = "You have successfully created an account!" # Display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # Do not save to table yet username = form.cleaned_data['username'] password = form.cleaned_data['password'] try: validate_password(password, user) except ValidationError as e: form.add_error('password', e) # to be displayed with the field's errors return render(request, self.template_name, {'form': form}) user.set_password(password) user.save() # Let's try to login the user user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('http://google.com') return render(request, self.template_name, {'form': form}) Why is it that the authenticate method is not … -
Django where is the many to one picker widget?
For each row of table A, I want to be able to add one or more rows from table B. The Django admin has an example, the user permissions picker -- I attach a screen shot. Each user can have any number of permissions. The permissions start on the left. When you add one, it moves to the right. You can move them back and forth. That is what I want for two of my own models. How do I get this widget? -
I deleted a css static file but my website still reads it?
I have a static css file called blog.css, and I load it in my base.html template like this: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/blog.css' %}"> But when I wanted to change something in that css, the changes doesn't appear. Due to my confusion, I tried to test some things. renaming blog.css to blog2.css The weird part is, when I make changes to blog2.css, and called it in the base.html, my changes work, such as changing the background color, and etc. but when I make changes to blog.css, nothing happens. So, I tried to DELETE blog.css, but still called it in the base.html. everything still works when I first made that file. I'm supposed to be expecting a broken designed HTML page and a 404 in the console because the blog.css in the static folder cannot be found. It's like the blog.css is a ghost or something that is still here in my folder somewhere.. or am I missing something? I also tried restarting the runserver command, refreshing the page countless times, and even restarting my computer. I'm quite new to Django and I'm trying my best to understand it, and any help given is appreciated. Thank … -
How to use JavaScript with Django?
I would like to pass data from a View to a javascript file. I tried the way I thought would work, I added: script src="{% static 'javascript.js' %}"> To the bottom of my HTML document, and loaded static files but when I went to write var a = {{ c }}; it did not work. How should I approach this? -
Django restrict data that can be given to model field
I have the following model in django: class Cast(TimeStampedModel): user = models.ForeignKey(User, unique=True) count = models.PositiveIntegerField(default=1) kind = models.CharField(max_length = 7) def __str__(self): return(f"{self.kind} || {self.count} || {self.modified.strftime('%x')}") But I want the 'kind' field to only take one of the following values: up, down, strange, charm, top, or bottom. How can I enforce this in the database or can this only be enforced in the views when taking in data? -
Django password validation not working
I am using my own custom User model, but I'm inheriting off of django.contrib.auth User model. I have a username, email, and password field. I don't explicitly add the password field because it gets added by default by the inheritance. When I try to create a superuser through the command line, the normal default Django password validation is working correctly. However, when I have a sign up form, it is not. Email and username validation are working properly when I click submit, but there is no password validation. I can enter whatever I want and it would accept the password. Here's my forms.py class RegisterForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'})) email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'})) password = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'})) Here's my view: class RegisterView(SuccessMessageMixin, View): form_class = RegisterForm template_name = 'oauth/auth_form.html' success_message = "You have successfully created an account!" # Display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # Do not save to table yet username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() # Let's try to login the user user = … -
Django: The SECRET_KEY setting must not be empty. after importing views to settings.py
I am trying to add the following to LOGIN_REDIRECT_URL within the settings file base.py LOGIN_REDIRECT_URL = reverse_lazy('users:summary', kwargs={'username': request.user.username}) In order to satisfy the kwargs arguement I need to import users.views and users.models inorder to pull the kwarg. (I could be wrong) To do this I added the following three lines to my base.py settings file. from django.core.urlresolvers import reverse_lazy from vicki.users import views from vicki.users.models import User Here is the LOGIN section of my base.py file: from django.core.urlresolvers import reverse_lazy from vicki.users import views from vicki.users.models import User ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True) ACCOUNT_ADAPTER = 'vicki.users.adapters.AccountAdapter' SOCIALACCOUNT_ADAPTER = 'vicki.users.adapters.SocialAccountAdapter' # Custom user app defaults # Select the correct user model AUTH_USER_MODEL = 'users.User' LOGIN_REDIRECT_URL = reverse_lazy('users:summary', kwargs={'username': request.user.username}) LOGIN_URL = 'account_login' # SLUGLIFIER AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify' ISSUE: Once i add the imports at the top and attempt to run the server using: docker-compose -f local.yml run django python manage.py runserver the terminal returns the following error: Postgres is up - continuing... Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 58, in execute super(Command, self).execute(*args, **options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 69, in handle if … -
How to use formatvalue filter for field in form template?
In Django templates we use the filter on value fields. Such as {{value | formatvalue}} I want to generate my form dynamically like blow example. {% for field in form %} {{ field }} {% endfor %} As you know field attribute will be generated as html element. Is there a way to add filter to field value? Thanks in advance. -
What is a good stack for QuoteOfTheDay.com?
I'm trying build a simple website which will just show a random inspirational quote when users visit it. It will have its own database of quotes on the back-end. Which technology stack would be suitable for implementing this website in a fast and efficient way? XAMPP? MEAN? DJANGO? Thanks! -
How to connect to Google Cloud SQL Proxy from Django?
I have happily managed to run Google SQL Proxy on port 5432. I was trying to follow the tutorial https://cloud.google.com/python/django/flexible-environment but I do not know how to setup the settings.py file. There is a mixture of terms which is very confusing for me: Google App Engine default authentication login / password from gcloud Google App Engine service authentication login / password from gcloud Project instance name Database password Database instance name Database connection name Database login / password I would be happy if there was anybody who could make a clear picture what do they mean and how to make this example working. -
Can't authenticate users in Django app
I'm trying to make a website using Django, and I have several views that require logins. However, I can't figure out how to authenticate users. I'm extremely new to web development (this is my first project), so please ask follow-up questions if I am not being clear. Here is some code that might provide context: Excerpt from rushsite/rush/views.py: from django.http import HttpResponseRedirect from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required def login_user(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 HttpResponseRedirect('list') else: return render(request, "registration/login.html") else: return render(request, "registration/login.html") My login.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <div class="container"> <div class="top"> <h1 id="title" class="hidden"><span id="logo">Delta Sig<span> Recruitment</span></span></h1> </div> <div class="login-box animated fadeInUp"> <div class="box-header"> <h2>Log In</h2> </div> <form method="post"> {% csrf_token %} <label for="username">Username</label> <br/> <input type="text" id="username"> <br/> <label for="password">Password</label> <br/> <input type="password" id="password"> <br/> <button type="submit">Sign In</button> <br/> <br/> {% if request.META.HTTP_REFERER == "http://127.0.0.1:8000/login/" %} Incorrect username or password. {% endif %} </form> </div> </div> </body> Excerpt from rushsite/rush/models.py: from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator class Brother(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name … -
Error importing module - ImproperlyConfigured: WSGI application
I created a Django project with an app named auth originally, but ran into some errors and changed it to authentication. Later, when trying to runserver I found out I couldn't because of the error: django.core.exceptions.ImproperlyConfigured: WSGI application 'coolwebsite.wsgi.application' could not be loaded; Error importing module: 'No module named 'django.contrib.authentication'' So I looked online and it turned out I shouldn't be naming apps with the same names as Django's app structure. I changed authentication to oauth and I'm still receiving the same error: django.core.exceptions.ImproperlyConfigured: WSGI application 'coolwebsite.wsgi.application' could not be loaded; Error importing module: 'No module named 'django.contrib.oauth'' I changed the app name to birds, but still I would get the same error. I don't understand why I am still receiving this error. The full error is: Traceback (most recent call last): File "C:\python3.6.3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\python3.6.3\lib\site-packages\django\core\management\commands\runserver.py", line 147, in inner_run handler = self.get_handler(*args, **options) File "C:\python3.6.3\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 28, in get_handler handler = super(Command, self).get_handler(*args, **options) File "C:\python3.6.3\lib\site-packages\django\core\management\commands\runserver.py", line 68, in get_handler return get_internal_wsgi_application() File "C:\python3.6.3\lib\site-packages\django\core\servers\basehttp.py", line 57, in get_internal_wsgi_application sys.exc_info()[2]) File "C:\python3.6.3\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\python3.6.3\lib\site-packages\django\core\servers\basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "C:\python3.6.3\lib\site-packages\django\utils\module_loading.py", line 20, in import_string module = … -
Variables and attributes may not begin with underscores django template
Creating private filter solution works fine for this case {{ value|private:'_id' }} but for this case {% url 'value.show' value|private='_id' %} it doesn't work is there any way around this problem -
Django 2.0 and DRF 3.7.7 routers
I'm using Django 2.0 and DRF 3.7.7(novice with both) and trying to add URL patterns in app_config/urls.py: router = routers.DefaultRouter() router.register(r'^submit_free_account', SubmitFreeAccount, 'SubmitFreeAccount') app_name = 'app_config' #the weird code urlpatterns = [ path('getSourcesNodes', GetSourcesNodes.post, name='GetSourcesNodes'), path('getAppsNodes', GetAppsNodes.post, name='GetAppsNodes'), ] urlpatterns += router.urls And in main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('config/', include('app_config.urls', namespace='app_config')), ] So when I trying to request config/submit_free_account I have 404 errors with strange URL patterns tried by Django: config/ ^$ [name='api-root'] config/ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] How to add router URL patterns correctly in Django 2.0? -
Check members attribute using for loop
Guys I have a question that I guess simple but I do not know how to do it: In my app each project is link to a team that has several and each member need to answer a survey that is store in my data base inside "Response" I would like to show a jumbotron in my page only if all users have a Response in the data base. I tried : <div class="container paddingtop80 marginbottom30"> {% for member in project.team_id.members.all %} {% if member.response_set.count > 0 %} <div class="jumbotron greenback"> <h4>Welcome to the Project test "{{ project.name }}" Detail page</h4> </div> {% else %} <div class="jumbotron greenback"> <h4>Welcome to the Project "{{ project.name }}" Detail page</h4> </div> {%endif%} {% endfor %} <div class="container paddingtop80 marginbottom30"> {% for member in project.team_id.members.all %} {% if member.response_set.count > 0 %} <div class="jumbotron greenback"> <h4>Welcome to the Project test "{{ project.name }}" Detail page</h4> </div> {% else %} <div class="jumbotron greenback"> <h4>Welcome to the Project "{{ project.name }}" Detail page</h4> </div> {%endif%} {% endfor %} </div> the problem is that like you can see now my jumbotron is printed 3 times since I have 3 members. How can I check for the 3 … -
how to create the django-models for this sqlite database
I have 4 tables in the sqlite database. I need to create django models for these. enter image description here Mysql: -- Globals -- SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; -- SET FOREIGN_KEY_CHECKS=0; -- Table 'Tafseer' DROP TABLE IF EXISTS Tafseer; CREATE TABLE Tafseer ( id INTEGER NULL AUTO_INCREMENT DEFAULT NULL, tafseer MEDIUMTEXT NULL DEFAULT NULL, sura_id_Sura INTEGER NOT NULL, ayah_id_Ayahs INTEGER NOT NULL, nametafseer_id_NameTafseer INTEGER NOT NULL, PRIMARY KEY (id) ); -- Table 'Sura' DROP TABLE IF EXISTS Sura; CREATE TABLE Sura ( id INTEGER NULL AUTO_INCREMENT DEFAULT NULL, sura_id INTEGER NOT NULL, sura VARCHAR NOT NULL, PRIMARY KEY (sura_id, id) ); -- Table 'Ayahs' DROP TABLE IF EXISTS Ayahs; CREATE TABLE Ayahs ( id INTEGER NULL AUTO_INCREMENT DEFAULT NULL, ayah_id INTEGER NOT NULL, ayah VARCHAR NOT NULL, sura_id_Sura INTEGER NOT NULL, PRIMARY KEY (ayah_id, id) ); -- Table 'NameTafseer' DROP TABLE IF EXISTS NameTafseer; CREATE TABLE NameTafseer ( id INTEGER NULL AUTO_INCREMENT DEFAULT NULL, nametafseer_id INTEGER NOT NULL, nametafseer VARCHAR NOT NULL, PRIMARY KEY (id, nametafseer_id) ); -- Foreign Keys ALTER TABLE Tafseer ADD FOREIGN KEY (sura_id_Sura) REFERENCES Sura (sura_id); ALTER TABLE Tafseer ADD FOREIGN KEY (ayah_id_Ayahs) REFERENCES Ayahs (ayah_id); ALTER TABLE Tafseer ADD FOREIGN KEY (nametafseer_id_NameTafseer) REFERENCES NameTafseer (nametafseer_id); ALTER TABLE … -
How to Trigger Browser Refresh when Django Static Files Change
I'm building a Django/React app and trying to automatically refresh the page whenever static files change (e.g. webpack bundle that's generated whenever React code is updated). I've tried the following packages: python-livereload, django-livereload, and django-livereload-server. None worked. And, they don't appear to be actively maintained. Any thoughts/suggestions would be greatly appreciated. -
Application error in heroku after using amazon rds database
So I am attempting to deploy a Django application onto heroku using amazon aws for storing static and media files and amazon rds as the database. When pushing to deployment the pages that do not have a model associated with them are fine while the pages with them show an application crash with heroku. I then figured it was because I had already had objects in my database before setting up rds and s3 so I deleted my heroku postgresql database (nothing of importance was in there) but still no luck. Here is relevant code below settings.py: """ Django settings for plaid_blog project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxxxxxxxxxxx' # SECURITY WARNING: don't run with debug turned on in production! #DEBUG = TRUE DEBUG = False #ALLOWED_HOSTS = [] ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] # Application definition … -
Unable to send Activation Email with Djoser in Django Rest Framework
am trying to send activation email when a user get registered . when post request is called the content of email is shown in console but it is not send to user email. Django setting : EMAIL_USE_TLS=True EMAIL_HOST='smtp.gmail.com' EMAIL_HOST_USER=<my_username@gmail.com> EMAIL_HOST_PASSWORD=<my_password> EMAIL_PORT=587 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DJOSER = { 'SET_PASSWORD_RETYPE' : True, 'LOGOUT_ON_PASSWORD_CHANGE' : True, 'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND' : True, 'PASSWORD_RESET_CONFIRM_URL':'#/password/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': {}, } P.S : SMTP is enabled on gmail account using https://www.codingforentrepreneurs.com/blog/use-gmail-for-email-in-django/ Console output after post request -
fiedls E300 dan E307
class OrderItem(models.Model): order = models.ForeignKey('Order', related_name='items') product = models.ForeignKey('Product', related_name='order_items') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) help message error fields E300 and fields E307 , output -
Django Upload Image in specific folder without FileField or ImageField and MEDIAROOT
My App needs to upload diferent profile images in diferen folders inside the static folder. One more thing, I'm not using models, I just want to take the picture I choose in html input file and copy to the specific folder. Here is my folder tree. Where I want to save the uploaded image is in MYPROJECTFOLDER/static/profile// that's where I don't want to use MEDIA_ROOT, becouse in media root I can't create a specific folder to each user. (I don't know if this is correct, if there is a way to create a specific folder to each user in the /media/ folder without using ImageField or FileField, please tell me). Here is my folder tree: MYPROJECTFOLDER | |------myproject | |------ __init__.py | |------ settings.py | |------ urls.py | |------ wsgi.py | |------myapp | |------ __init__.py | |------ admin.py | |------ apps.py | |------ forms.py | |------ models.py | |------ tests.py | |------ urls.py | |------ views.py | |------static | |-------css | |----- bootstrap.css | |----- mystyles.css | |-------fonts | |-------images | |-------js | |----- myscripts.js | |-------profile | |------folder_user1 | |------ uploadedpicture.jpg #Here is where I want to upload | |------folder_user2 | |------folder_user3 | |-------resources | |------templates | |-------myapp | … -
Dockerized Django can't connect to MySQL
Using this tutorial https://semaphoreci.com/community/tutorials/dockerizing-a-python-django-web-application, I'm dockering my Django application in a VirtualBox using docker-machine. Everything has gone splendidly until I go to my browser and my application says that it's having issues with MySQL. Then i found this documentation for dockerizing an instance of mysql https://github.com/mysql/mysql-docker which I followed, creating the image in the same development VirtualBox that I created. The error I was originally getting was Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' My Django DATABASES looked like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'root', 'HOST': 'localhost', 'PORT': '' } } I then changed the host to 127.0.0.1 and even tried specifying the port as 3306 and I got a new error which was (2003, "Can't connect to MySQL server on '127.0.0.1' (111)") I also went in to MySQL workbench and changed the connection of my Local instance to be 127.0.0.1:3306 and that hasn't helped. The commands that I'm running are eval "$(docker-image env development)" ---> supposedly does THESE things: export DOCKER_TLS_VERIFY="1" export DOCKER_HOST="tcp://123.456.78.910:1112" export DOCKER_CERT_PATH="/Users/me/.docker/machine/machines/development" export DOCKER_MACHINE_NAME="development" Then, now that i'm in my virtualbox, I run: docker run -it -p 8000:8000 <docker image name> ---> forwards exposed port 8000 to port …