Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError at / string indices must be integers
I am trying to make a custom made user creation form where user can type username,password and email to register in my site. but I am unable to debug this error. What kind of type error its referring to? I am using django 2.1 and postgresql 10.3 as db. forms.py from django import forms class SignUpForm(forms.Form): username = forms.CharField(max_length=20) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'password'})) password_confirmation = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'password confirmation'})) email = forms.EmailField() def clean(self): password = self.cleaned_data.get('password') password_confirmation = self.cleaned_data.get('password_confirmation') print(password) print(password_confirmation) if password != password_confirmation: raise forms.ValidationError('Password Must Match') return password urls.py from django.urls import path from .views import SignUpView urlpatterns = [ path('',SignUpView,name = 'signup') ] views.py from django.shortcuts import render from .forms import SignUpForm from django.contrib.auth.models import User from django.shortcuts import HttpResponse def SignUpView(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] user = User(request,username=username,email=email) user.set_password(password) user.save() return HttpResponse('User Created') else: form =SignUpForm() return render(request,'signup.html',{'form':form}) TraceBack Error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 2.0.5 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in … -
Why Python is adding unnecessary characters at the beginning of a file while overwriting it?
In a Django project I have created a .env file to store my application's secret credentials. And I am using console command to generating some of the credentials. Here is my initial .env file, SECRET_KEY=CHANGE_IT DB_CONNECTION=pgsql DB_HOST=127.0.0.1 DB_PORT=5432 DB_DATABASE=database_name DB_USERNAME=database_username DB_PASSWORD=database_password DB_SCHEMA=database_schema_name And here is my generate_secret console command to overwrite the SECRET_KEY with random string, import re import os from django.core.management import BaseCommand from django.core.management.utils import get_random_secret_key class Command(BaseCommand): help = '' def handle(self, *args, **options): env_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../.env')) self.set_secret_key(env_path, get_random_secret_key()) @staticmethod def set_secret_key(env_file_path, secret_key): fp = open(env_file_path, 'r+') current_env = fp.read() regex = r"(SECRET_KEY=.*?)\n" matches = re.findall(regex, current_env, re.MULTILINE) updated_env = current_env.replace(matches[0], 'SECRET_KEY={}'.format(secret_key)) fp.truncate(0) fp.write(updated_env) fp.close() The problem is when I am running the command, it overwrites the SECRET_KEY correctly but also adding bunch of wired characters at the start of the .env file. I running on Ubuntu 18.04 operating system. Here is the .env file after running the command, I am not sure why but I can not copy those wired characters, so I have attached the screenshot of it. -
django: See the result of a python script in my webpage
I am developing a website using django. I want to see the result of a python script in my webpage. And after some searching I realized subprocess popen can help me. I am very new to django so I searched for a complete code. I find these lines: output = None cmd = 'python ' + session["file_name"] p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) output = p.stdout.read() return jsonify(output.decode('utf-8')) from PythonBuddy opensource code. But it uses flask and I don't know what will be the replacement for it in django. Here is my view.py:(It doesn't work) output = None def home(request): p = subprocess.Popen(["python","adoptions/executer.py"], close_fds=True) std_out, std_error = p.communicate() return jsonify(output.decode('utf-8')) The python code in executer.py is a game, not something like a string to print, so many codes I found was useless. Can it be easier if I use ajax?? -
Turn of all notifications on your device using a website
I would like to create a django website that helps you focus better and one of the feature will be cutting all (or most) notification on the device you are using. I searched for this but nothing seems to be coming up. Perhaps it is impossible. However in the case it is possible, can someone tell me how I can manage to program such thing. I haven’t started the project and I have no code yet so you can write the code in however way you want. -
Key Error after multiple annotations with Django
I am trying to calculate some statistics for my models. To do that I create some annotations that will help me do this: # won won_statuses = ["Won", "Half Won", "Cash Out"] queryset = queryset.annotate(won=Case(When(status__name__in=won_statuses, then=1), default=0.0, output_field=DecimalField())) # lost lost_statuses = ["Lost", "Half Lost"] queryset = queryset.annotate(lost=Case(When(status__name__in=lost_statuses, then=1), default=0.0, output_field=DecimalField())) # lost_stake queryset = queryset.annotate(lost_stake=F("lost") * F("stake")) After that, I group the data by day, month or year and apply the annotation that will calculate the statistic: target_dict = {"profit": Sum("profit"), "stake": Sum("stake"), "returns": Sum("returns"), "yield": Sum("profit") / Sum("stake"), "roi": Sum("returns") / Sum("stake"), "hitrate": Avg("won"), "count": Count("id")} data = queryset.annotate(group_by=Trunc("timestamp", group_by, output_field=DateField())) \ .values("group_by") \ .annotate(total_value=target_dict[target]) \ .order_by("group_by") \ .values_list("group_by", "total_value") The issue is that every calculation that involves the custom annotations (won, lost, lost_stakes) shows me a Key Error: .annotate(total_value=Avg("won")) Everything that was a field from the model is calculated correctly. -
docker python official example bugs
i am learning docker,and i want to make up my python django docker images to run in my mac i create 3 files: 1: docker-compose version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db 2: Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ 3:requirements Django>=1.8,<2.0 psycopg2 then i run sudo docker-compose run web django-admin.py startproject composeexample . i create the official example files in my dir but when i run docker-compose i get an error and it was run failed web_1 | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fcafcf47510> web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run web_1 | autoreload.raise_last_exception() web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception web_1 | six.reraise(*_exception) web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/six.py", line 685, in reraise web_1 | raise value.with_traceback(tb) web_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 27, in setup web_1 | apps.populate(settings.INSTALLED_APPS) web_1 | File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", … -
Why isn't the paragraph tag working?
I'm using Django but for some reason the <h2> tag displays article.title with no problem but the <p> tag won't display anything - even simple text. {% extends 'base_layout.html' %} {% block content%} <h1>Articles List</h1> <div class="articles"> {% for article in articles %} <div class="article"> <h2><a href="{% url 'articles:detail' slug=article.slug %}">{{ article.title}}</a></h2> <p>TEST TEXT</p> <p>{{ article.date }}</p> </div> {% endfor %} </div> {% endblock %} the base_layout.html is {% load static from staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Carpe Nocturn</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> </head> <body> <header class="wrapper"> <h1><a href="{% url 'articles:list' %}"><img src="{% static 'logo.png' %}" alt="Carpe Nocturn" /></a></h1> </header> <div class="wrapper"> {% block content %} {% endblock %} </div> </body> </html> -
advantages of separated DB in docker?
case 1 : django+postgresql (container) case 2 : django(container)<-connect->postgresql(container) (these cases are on one server) What are the advantages of separating ? or performance? -
How can I access html in Django?
I want to make a href link can access sub.html of Django app. I wrote in index.html like <p class="button"><a href="{% static 'templates/sub.html'%}">Next</a></p> but when I put Next button,Page not found (404) Request URL:http://127.0.0.1:8000/static/templates/sub.html error happens. My app's structure is -app -index -templates -index.html -sub.html -urls.py -views.py -manage.py What is wrong in my codes?I rewrote <a href="{% static 'sub.html'%}"> but same error happens.How should I fix this? -
Unable to connect Aamzon RDS in production server but connect on local server
I am using Amazon Postgre RDS. When I connect this RDS in my local server it is working perfectly fine but when I push it on github and pull on my EC2 then I am getting following error: Traceback (most recent call last): File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run self.check_migrations() File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/home/ubuntu/myvenv/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/home/ubuntu/myvenv/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "myammaji.cbgocwwown9z.ap-south-1.rds.amazonaws.com" … -
Django with MongoDB OneToOneField and cannot set multiple null values
If I have a class model like this: class Person(models.Model): spouse = models.OneToOneField('self', on_delete=models.SET_NULL, null=True) And try to add two Persons with a null value on spouse, it says spouse is not unique because it's null Is this just because I'm using MongoDB? If so, what would be the best way to mitigate the unique value, but also allow multiple nulls? I'm using djongo as my driver. -
django datatable with Ajax
I am shifting from plain html datatable to datatable with ajax in django (because after loading large data, page with stretch and take time to fetch all data) here are my codes : model.py : class myModel(models.Model): date = models.CharField(max_length=8) rnc = models.CharField(max_length=8,primary_key=True) mo = models.CharField(max_length=100) parameterid = models.CharField(max_length=100) before_value = models.CharField(max_length=40) class Meta: db_table = "changed_para" def __unicode__(self): return self.data def __unicode__(self): return self.rnc def __unicode__(self): return self.mo def __unicode__(self): return self.parameterid def __unicode__(self): return self.before_value def natural_key(self): return self.my_natural_key urls.py urlpatterns = [ path('changed_para_json', views.changed_para_json, name='my_ajax_url'), ] views.py from django.http import HttpResponse from django.core import serializers from polls.models import myModel def changed_para_json(request): if request.POST.get("fetchdata"): Date=request.POST["Date"] RNC=request.POST["RNC"] MO=request.POST["MO"] parameterid=request.POST["parameterid"] else: Date='2018-07-20' RNC='RRRNCH02' MO='CORRMALGOSWITCH' parameterid='DRASWITCH_DRA_VOICE_SAVE_CE_SWITCH' current_time=datetime.date.today() para = myModel.objects.using('rnc_parameters').all() json = serializers.serialize('json', para) object_list = myModel.objects.using('rnc_parameters').all() #or any kind of queryset json = serializers.serialize('json', object_list) return HttpResponse(json, content_type='application/json') changed_para_json.html </form> <br> <table id="tableid_1" cellpadding="0" cellspacing="0" border="0"> <thead class="thead-inverse"> <tr> <th><font size="2">Date</th> <th><font size="2">RNC</th> <th><font size="2">MO</th> <th><font size="2">parameterid</th> <th><font size="2">value Before</th> </tr> </thead> <tbody> </tbody> </table> <br> <br> <script type="text/javascript" language="javascript" class="init"> $(document).ready(function() { $('#tableid_1').dataTable( { "processing": true, "ajax": { "processing": true, "url": "{% url 'my_ajax_url' %}", "dataSrc": "" }, "columns": [ { "data": "fields.date" }, { "data": "pk" }, { … -
django text field with options
Hello I want to know if it possible to make a text field with options like here in django the options up top to enter image and edit the text and how can I do it -
it's possible optimize the use of dictionaries in notification system?
I'm developing an improvement in a notification system using Django(with Celery), Postgresql and Python3. The system works as follows: Exist a Celery worker which receive all message of several microservices. When it received message then send a push notification and email notification. This was designed for reduce the load of each microservice and prevent any error in the communication. When a endpoint in a microservice need send a notification, it create a dictionary with next information: Name of template (Email notification) title data or field for email notification. message for push notification data or body for push notification users (Dictionary). For send a message to Celery Worker for send notification. The next is a fragment of dictionary which using: { 'messages':[{ 'type': 'CLIENT', 'message': .... },{ 'type': 'TECHNICAL', 'message': .... },{ 'type': 'ADMIN', 'message': .... } ], # message for push notification 'fields': {....}, # data or field for email notification. 'args': {.....}, # data or body for push notification 'users': [ { 'type': 'CLIENT', 'user': .... }, { 'type': 'TECHNICAL', 'user': .... } ] } But I have several questions for improvement the notification system: It's possible optimize the using of dictionary? Is there a way to improve this? … -
Django; How to organize similar functions and similar templates
I'm a beginner. I've been working on Django project. I'm feeling like I should organize similar functions and templates. I'm wondering if there's a preferable way to do it. For example, def my_entry(request): entry_list = Entry.objects.filter(user=request.user) return render(request, 'blog/list_entry.html', {'entry_list': entry_list}) def list_entry(request): entry_list = Entry.objects.order_by('created') return render(request, 'blog/list_entry.html', {'entry_list': entry_list}) These functions are similar so I want to organize them. I want to render them into the same template list_entry.html but I want to make them a bit different. (for example, if my_entry is called, the title of the page is My Entry and if list_entry is called, the title of the page is Entry or something like it. But I don't know the way to do it. Anyone who could give me tips? I want to know how to do it using FBV if possible not only CBV. -
how to update a particular field in django?
code for update the fields in django when am trying update a single field in django. It asking required field is required.so i want to update only single field -
UpdateView with my own made Custom_user_model in Django
I want to use email as authentication so i made change in default user and made a new custom one by AbstractUser but when i am making view to update the profile that is not giving me any query showing Page not found No User matches the given query. Here is sample codes **models.py** from django.db import models from django.contrib.auth.models import AbstractUser,BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.core.validators import MinValueValidator, MaxValueValidator from django.db.models.signals import pre_save from django.utils.text import slugify from django.urls import reverse from django.utils import timezone from .choices import branch_choices #from app_name.models import skills # Create your models here. class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) … -
Take advantage of Django Migration to save some data
I noticed that when you run Django Migration, some data is added to table auth_permission when a new model is created. Is there any way you can take advantage of migration process to do the same with your own models? I red Django Documentation about writing Migrations, but it only covers the creation of brand new migration processes, it doesn't say anything about using the default one for your own porpoises. -
Running a simple Python code on a Django created Website
So first of all, im pretty new to the world of programming. I started learning Python and i wrote a piece of code which takes some user input and outputs a url to an image. I want to integrate this to a website, so i started reading about Django and i managed to install and run a Django App. Now I am stuck at how to create this website which should simply take a user input, send it to my Python code, take the returned URL and display the image of that URL. Thanks!!! -
Unable to store generated stripe id when registering users
I need to save the stripe id generated when processing a subscription sign up. models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) email = models.EmailField(default='') stripe_id = models.CharField(max_length=50, default='0') views.py form = RegistrationForm(request.POST) if form.is_valid(): email= request.POST['stripeEmail'] source= request.POST['stripeToken'] user = form.save() customer = stripe.Customer.create( email=email, # plan = 'prod_CNva2YwamwS3D0', card = source #user.stripe_id, # card = form.cleaned_data['stripe_id'], ) user.refresh_from_db() # load the profile instance created by the signal user.email=email user.userprofile.stripe_id = customer.id user.save() I checked the SQL for user.userproflie.stripe_id and it only runs the SELECT and not the UPDATE. user.save() updates "auth_user" I tried changing it to user.userprofile.save() but it does not update the stripe_id field. I made sure that the customer.id is equal to the stripe id returned from stripe. Thank you. -
django-storages boto3 accessing file url of a private file
I'm trying to get the generated URL of a file in a test model I've created, and I'm trying to get the correct url of the file by: modelobject.file.url which does give me the correct url if the file is public, however if the file is private it does not automatically generate a signed url for me, how is this normally done with django-storages? Is the API supposed to automatically generate a signed url for private files? I am getting the expected Access Denied Page for 'none' signed urls currently, and need to get the signed 'volatile' link to the file. Thanks in advance -
Django include statement is behaving odd
The below code was working fine but recently it stated behaving odd on server. views.py context['data'] = [{'personal_email': 'personal_email@gmail.com', 'office_email': 'office_email@gmail.com'}] Template {% for i in data %} {{ i.personal_email }} {{ i.office_email }} {% include 'sample.html' with email=i.personal_email %} {% include 'sample.html' with email=i.office_email %} {% endfor %} I am unable to get office_email in sample.html file -
Django testing, issue with localised error messages
I am making the first steps with using Django localisation, and I have just faced the first difficulty. I am trying to test that something in models works as expected. For invalid input, a specific ValidationError should occur. The code in the test looks like this: try: p = ... p.full_clean() self.fail('Expected exception not raised') except ValidationError as e: dict_err = dict(e) self.assertIn('category', dict_err.keys()) self.assertEqual(len(dict_err.keys()), 1, 'Encountered more than one error') self.assertIn('blank', dict_err['category'][0]) As long as the site operates in English (LANGUAGE_CODE = 'en-uk'), the caught error looks like this: ValidationError({'category': ['This field cannot be blank.']}) To check that I've got exactly this ValidationError, I am searching for the work 'blank' in the error message (last line of the code above). It fails as soon as I switch the site to another language. E.g. for German it looks so: ValidationError({'category': ['Dieses Feld darf nicht leer sein.']}) Looking for 'blank' obviously fails the test. How could I check the error message? I expect, somewhere deep in Django, there should be a unique identifier of this message (so that Django knows how to translate). But I don't see any traces of it in the error value. I would expect something like self.assertIn(_(id), … -
Zappa + RDS Connection Issues
I'm hoping someone could help me out with some questions regarding VPC. I'm pretty new to AWS and I'm just trying to build a sample web app to get my feet wet with everything. I've been roughly following this guide to try and setup a basic project using Zappa + Django. I've gotten to the state where I'm configuring a VPC and trying to add a Postgres instance that Django/zappa can talk to. Per that article, I've setup up my network like this: Internet Gateway attached to VPC 4 Public subnets 4 Private subnets Lambda function in 2 of the private subnets RDS with subnet group in other 2 private subnets EC2 box in 1 public subnet that allows SSH from my local IP to forward port 5432 to RDS instance My issue comes when I try and run migrations on my local machine using "python manage.py makemigrations". I keep getting an error that says "Is the server running on host "zappadbinstance.xxxxx.rds.amazonaws.com" (192.168.x.xxx) and accepting TCP/IP connections on port 5432?". I'm not sure what step I'm missing. I followed this guide and this post to setup the bastion host, and I know it is working because I am able to … -
Django RSS feeds: Replace "Read More" with custom string?
I'm generating an RSS feed using the Django syndication feed framework. The items I am linking to, however, aren't articles per se. They are more like events. Attached is a picture of how a feed item currently looks when parsed: My problem here is with the "Read More" link. in my feed class below, the "Read More" anchor leads to URL of the object: def item_link(self, item): return reverse('player_page', args=[item.player_set.first().id]) How can I make the anchor text for this kind of link different? there's no mention of it in the Django docs.