Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Smtp2go Username's account not allowed to send
I seem to be unable to send an email via my smtp server that is integrated with Django. I'm following this tutorial: https://github.com/smtp2go-oss/smtp2go-django/ Error keeps saying that the smtp's username is not allowed to send. I have checked my login password and username in settings.py and with my API key exported. So what am I doing wrong here? Performing system checks... System check identified no issues (0 silenced). December 12, 2018 - 07:36:23 Django version 2.1.3, using settings 'ChatBotWebApp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ERROR:smtp2go.core:['Message failed - Error: {\'weiyuxin100@gmail.com\': (550, b"that smtp username\'s account is not allowed to send")}'] INFO:smtp2go.core:Success? False INFO:smtp2go.core:Status Code: 200 INFO:smtp2go.core:Request ID: a2679416-fde0-11e8-b8ef-f23c917b36ad Would appreciate any help here, thanks! -
Displaying uploaded file name to python file from django form
I am fairly new to using Django. I successfully upload file and store in one folder in project .Now I want to display uploaded file name in one of the python file in my django project. My project hierarchy is djangoproject //project folder -mysite - mysite - taxonomy //here i stored uploaded files - personal // this app name -venv -requirements.txt mysite/urls.py from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^', include('personal.urls')), url(r'^admin/', include(admin.site.urls)), ] urlpatterns += staticfiles_urlpatterns() personal/urls.py from django.conf.urls import url from personal.views import index,dashboard urlpatterns = [ url(r'^$', index, name='index'), url(r'^dashboard/', dashboard, name='dashboard') ] personal/views.py from django.shortcuts import render, redirect from personal.forms import SignUpForm, StudentForm from personal.functions import handle_uploaded_file from django.http import HttpResponse def dashboard(request): if request.method == 'POST': student = StudentForm(request.POST, request.FILES) if student.is_valid(): handle_uploaded_file(request.FILES['file']) messages.add_message(request, messages.SUCCESS, 'File Uploaded Successfully.') return redirect('dashboard') else: student = StudentForm() return render(request,"registration/dashboard.html",{'form':student}) persona/tampletes/registration/dashboard.html {% if messages %} {% for message in messages %} <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">{{ message }}</div> {% endfor %} {% endif %} <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <div class="col-sm-10"> <div style="padding-bottom:4px; padding-left: 15px; border: 1px solid #d1c9c5;"> {{ … -
MAC - How do I find and remove postgres server?
I cannot find a way to kill or remove my postgresql server. postgres -V shows the version is 9.5.3 but I cannot find the path file in my mac. I tried lsof -i :5432 and the result comes out as below COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME postgres 1403 jk0819 5u IPv6 0x35013bd948ad16e1 0t0 TCP localhost:postgresql (LISTEN) postgres 1403 jk0819 6u IPv4 0x35013bd9438f8821 0t0 TCP localhost:postgresql (LISTEN) but when I run kill -9 1403 it does nothing. Can anyone help me? Thank you. -
Running a python program which uses concurrent.futures within a celery based web app
I am working on a django application which uses celery for the distributed async processes. Now I have been tasked with integrating a process which was originally written with concurrent.futures in the code. So my question is, can this job with the concurrent futures processing work inside the celery task queue. Would it cause any problems ? If so what would be the best way to go forward. The concurrent process which was written earlier is resource intensive as it is able to avoid the GIL. Also, its very fast due to it. Not only that the process uses concurrent.futures.ProcessPoolExecutor and inside it another few (<5) concurrent.futures.ThreadPoolExecutor jobs. So now the real question is should we extract all the core functions of the process and re-write them by breaking them as celery app tasks or just keep the original code and run it as one big piece of code within the celery queue. As per the design of the system, a user of the system can submit several such celery tasks which would contain the concurrent futures code. Any help will be appreciated. -
Django Reset Serializer loses file
I have a Simple serializer. class MySerializer(serializers.Serializer): file = serializers.FileField() I use this serializser in my view: class MyView(APIView): permission_classes = () parser_classes = (MultiPartParser,) def post(self, request): print(request.data) # <QueryDict: {'file': [<InMemoryUploadedFile: some_file.png (image/png)>]}> serializer = MySerializer(data=request.data) serializer.is_valid() print(serializer.data) # {'file': None} I pass data to serializer, which containts file. After checking serializer.data it says that file is None. What is more If I change the serializer.is_valid() line to serializer.is_valid(raise_exception=True) The view will return message that data are invalid. { "file": [ "This field can not be null." ] } This behaviour is strange to my. The docs says that request.data contains both file and non-file object. We can even see that in my print. The question is why my serialzier can't make use of it? -
Regex exclude numbers (0-9), and negative (-) only if occurs on first index of string
I'm still learning on regex, I need to remove all characters in the string except for the numbers(0-9), dots (.), and negative (-) if occurs on first index of string. so basically if i had a string "-12,3asd45,we-678.90" it should give me "-12345678.90" This is my current code, but the problem is I just want to exclude (-) if it occurs on the first index of the string, currently it excludes in all occurrences of (-): value = val.replace(/[^-0-9.]/g , ''); -
push live updates to client through Django Channels & Websockets when database get updated
I am very new to django channels.I wan't to try out. using django channels, If I added one user through django admin portal then this will be update on live on page where i am displaying users list. Using django post-save is this possible Please help me on this. I have tried one week on this till not get any solution. -
Is it possible to extend a site-wide template in Django / refer to templates in higher directories?
I would like to have a header/footer that follows throughout the entire site. Currently, I have a base.html file sitting within an app (project/app1/templates/app/base.html) and would like to apply an html template that I can use across the entire site. Is this possible or are templates only referanceable within the app templates folder? Can I have a template sitting in a higher directory such as project/template/base.html or project/base.html and call that so I don't have to copy and paste the same template into each app templates folder? -
How to handle sessions in django app when deployed in aws lambda
I want to deploy Django application in aws using Zappa. In my local server sessions are working fine.Is it possible to handle same sessions in aws ? if not is there any method to handle sessions in aws(Zappa)? -TIA -
ModuleNotFoundError: No module named '_sqlite3' python django
I am running simple python manage.py runserver and getting this error.i had tried everything like installing sqlite3,sqlite-devel but nothing works File "/usr/local/lib/python3.6/sqlite3/__init__.py", line 23, in <module> from sqlite3.dbapi2 import * File "/usr/local/lib/python3.6/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ModuleNotFoundError: No module named '_sqlite3' -
django project deploy with apache, the apache is running, but its shows error and dependency is already install
[Wed Dec 12 10:59:32.115495 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 13, i$ [Wed Dec 12 10:59:32.115497 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] django.setup(set_prefix=False), referer: http://13.127.165.50/en/admin/ [Wed Dec 12 10:59:32.115501 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] File "/usr/local/lib/python3.5/dist-packages/django/init.py", line 27, in$ [Wed Dec 12 10:59:32.115503 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] apps.populate(settings.INSTALLED_APPS), referer: http://13.127.165.50/en/ad$ [Wed Dec 12 10:59:32.115507 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 8$ [Wed Dec 12 10:59:32.115509 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] app_config = AppConfig.create(entry), referer: http://13.127.165.50/en/admi$ [Wed Dec 12 10:59:32.115513 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 94,$ [Wed Dec 12 10:59:32.115515 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] module = import_module(entry), referer: http://13.127.165.50/en/admin/ [Wed Dec 12 10:59:32.115518 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] File "/usr/lib/python3.5/importlib/init.py", line 126, in import_module, $ [Wed Dec 12 10:59:32.115521 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] return _bootstrap._gcd_import(name[level:], package, level), referer: http:$ [Wed Dec 12 10:59:32.115524 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] File "", line 986, in _gcd_import, referer: http$ [Wed Dec 12 10:59:32.115534 2018] [wsgi:error] [pid 20200:tid 140575906928384] [client 103.3.228.58:42384] File "", line 969, in _find_and_load, referer: h$ [Wed Dec 12 10:59:32.115538 2018] … -
Odd icon in Sublime Text 3
I'm working in Django in ST3. This doesn't used to happen but now whenever I create a new app using ./manage.py startapp userx I get a weird icon in ST3 that I can't open. Has anyone seen this before? -
Unable to create a project in Django
I tried both methods but I am unable to understand what's wrong, I'm using django 1.11.7, it was working a few months ago. I only have one python version installed. I get this system message: C:\WINDOWS\system32>django-admin.py startproject wisdompets Unable to create process using 'c:\program files\python36\python.exe "C:\Program Files\Python36\Scripts\django-admin.py" startprojects wisdompets' C:\WINDOWS\system32>django-admin startproject test_project Fatal error in launcher: Unable to create process using '"' -
Should 'zappa_settings.json' file be committed to source control. What are the best practices?
I came across this issue and I wanted to ask the community about the best practices related to zappa_settings.json. I have a couple of sensitive environment variables declared in the json file and that made me wonder about what are the best practices to manage the json file. Should it be checked in to source control or should we generate it with Zappa init each time? -
how to put initial data on form in CreateView
I have a view which I'm trying to provide default data using the get_initial function. But what happens is that it does not appear to execute my attempt to override the said function. class fileCreate(LoginRequiredMixin, CreateView): model = file success_url=reverse_lazy('file_status:list') login_url = 'login' form_class = fileForm def get_initial(self): initial = super(fileCreate, self).get_initial() initial['name'] = 'this the initial value' return initial the redirect and form will render just as expected but it will not show that value that I set for name. Another thing is that when I put a print statement inside the function. it does not show. Why? Is my assumption correct that the get_initial function is not being called? -
Django Error----name 'self' is not defined
I am trying to add products to my cart along with foreignkey User who would be the current user in session. I know usually you can do self.request.user, but in this case adding self.request.user is not working. I have also tried running it with self as one of the parameter. For example: def cart(request, self, product_id): I have also tested without using: curr_user = get_object_or_404(User,user=self.request.user) and instead: owned_by=self.request.user or owned_by=request.user for adding to Cart and also all_posts but neither worked. I get the error with the code screenshots below: NameError at /mycart/6 name 'self' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/mycart/6 Django Version: 2.1.3 Exception Type: NameError Exception Value: name 'self' is not defined Exception Location: mysrc/cart/views.py in cart, line 25 Python Executable: env/bin/python Python Version: 3.7.0 Python Path: views.py #Create your views here. from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import Cart from shop.models import Products @login_required def cart(request, product_id): cart = Cart(request) product = get_object_or_404(Products,id=product_id) curr_user = get_object_or_404(User,user=self.request.user) cart = Cart(item=product, quantity=1, price=product.price, owned_by=curr_user) cart.save() all_posts = Cart.objects.filter(owned_by=curr_user) context = {'all_posts':all_posts} return render(request,'cart/mycart.html') models.py from django.db import models from shop.models import Products from users.models import User from django.urls import reverse # Create your … -
Django testing - running test_models.py only works fine but testing with other views not working
The test_models.py works fine on its own by the command, python manage.py test users.tests.test_models but when it runs with python manage.py test users.tests it creates the User does not exist. In test_models.py class EmailUserTest(TestCase): @classmethod def setUpTestData(cls): data = { 'email': 'hello@example.com', 'first_name': 'Django', 'last_name': 'Testing' } EmailUser.objects.create(**data) def test_user_model_user_label(self): a1 = EmailUser.objects.get(id=1) field_label = a1._meta.get_field('email').verbose_name self.assertEquals(field_label, 'email') In models.py, class EmailUser(AbstractBaseUser): email = models.EmailField(_('email address'), max_length=255, unique=True) first_name = models.CharField(_('first name'), max_length=255, blank=True) last_name = models.CharField(_('last name'), max_length=255, blank=True) date_joined = models.DateTimeField(_('date created'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=False) objects = EmailUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('email') In views.py if form.is_valid(): email = request.session.get('email') user = form.save(email=email) As in the views.py, the email is input from session. What's wrong in here? -
Django Rest Framework: how to make field required / read-only only for update actions such as PUT and PATCH?
I have a Django Serializer that has a field that should only be required for update actions such as PUT and PATCH. But not for create actions such as POST. I found this similar SO question but there's no clue there regarding how to write a custom validation to detect whether an action is for create or update or patch. Similarly, I want to turn on read_only (or make them not editable) for some other fields but only for update actions. I have googled the django rest framework docs, but there's no explicit examples of such custom validators. Right now, my workaround is to set required=false altogether which is not the best. Please advise. -
How do I link a {% url %} to the haystack search page in haystack 2.8.1?
This is not a duplicate question. The previous answers are outdated. My urls.py has this url(r'^search/', include('haystack.urls')), And all of the previous answers on stackoverflow say to include {% url "haystack_search" %} in my template, but that only returns this error: Reverse for 'haystack_search' not found. 'haystack_search' is not a valid view function or pattern name. Apparently haystack_search is no longer a name included in haystack.urls. This is with django_haystack-2.8.1 on Django-2.1.3 -
Python - Django site admin page is empty after logged in
I'm trying to build a tic tac toe game. My django site admin page is appearing blank and i'm not able to solve it. screenshot of the problem models.py from django.db import models from django.db.models import Q from django.contrib.auth.models import User GAME_STATUS_CHOICES ={ ('F','First Player to move'), ('S', 'Second Player to move'), ('W', 'First Player Wins'), ('L', 'Second player Wins'), ('D', 'Draw') } class GameQuerySet(models.QuerySet): def games_for_user(self, user): return self.filter( Q(first_player = user) | Q(second_player = user) ) def active(self): return self.filter( Q(status='F') | Q(status='S') ) class Game(models.Model): first_player = models.ForeignKey(User, related_name = "game_first_player", on_delete=models.CASCADE) second_player = models.ForeignKey(User, related_name = "game_second_player", on_delete=models.CASCADE) start_time = models.DateTimeField(auto_now_add=True) last_active = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, default='F', choices=GAME_STATUS_CHOICES) objects = GameQuerySet.as_manager() def __str__(self): return "{0} vs {1}".format( self.first_player, self.second_player) class Move(models.Model): x = models.IntegerField() # X and Y co-ordinates y = models.IntegerField() comment = models.CharField(max_length=300, blank= True) by_first_player = models.BooleanField() admin.py from django.contrib import admin from .models import Game, Move admin.site.register(Move) @admin.register(Game) class GameAdmin(admin.ModelAdmin): list_display = ('id','first_player','second_player','status') list_editable = ('status',) I'm a newbie to django. I have been stuck on this problem for a while now. Couldn't find the answers. Thanks. -
Django redirect back to admin login page using reverse() not working
I'm new to Django version 2.1, In Middleware where if user_logged session is empty i'm redirecting it to admin url I'm getting NoReverseMatch at /demo/list Reverse for '../admin/' not found. '../admin/' is not a valid view function or pattern name. error. project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('demo/', include('demo.urls')), ] setting.py 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', 'demosite.middleware.LoginRequiredMiddleWare', ] project middleware.py import re from django.shortcuts import redirect from django.conf import settings from django.urls import reverse class LoginRequiredMiddleWare: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): print(request.session.get('user_logged', None)); if not request.session.get('user_logged', None): return redirect(reverse('admin/')) app urls.py from django.urls import path, include from demo import views urlpatterns = [ path('list', views.demoView.listData, name='list-data') ] FOR REFERENCE BELOW IS SCREEN SHOT OF PROJECT DIRECTORY STRUCTURE THANKS IN ADVANCE -
Django: Access certain attribute of multiple subclasses with inheritance from one superclass
My aim is to access an attribute of a subclass without knowing beforehand which of the two subclasses was choosen (multiple choice classes) Ideally there is an attribute in the SuperClass that changes depending upon which SubClass was choosen. The reason is that I have created Forms directly from the SubClasses and use the SuperClass as the entry point for accessing values. I am aware I can use true or false with hasattr(horse), but ideally I am asking if there is a bit neater solution, such as the SubClass can signal to SuperClass which SubClass was used. e.g. for product 8 on my list subclass = getattr(Product(8), 'subclass', 0) print(subclass) >> Horse or place = Product.location Print(place) >> Stable The whole "problem" stem from the fact that I create Products via SubClass Forms, meanwhile much of the later logic goes top-down, starting with Product class Product(models.Model): product_name = models.Charfield(max_length=20) class Car(Product): engine = models.Charfield(max_length=20) location = models.Charfield(default="Garage", max_length=20, editable=False) product = models.OneToOneField(Product, parent_link=True, on_delete=models.CASCADE) class Horse(Product): saddle_model = models.Charfield(max_length=20) location = models.Charfield(default="Stable", max_length=20, editable=False) product = models.OneToOneField(Product, parent_link=True, on_delete=models.CASCADE) -
Trying to hide button if next step does not exist
I am trying to make the button "next" disappear if there is no next step. I have tried the following and got stuck here. I have tasks with related steps using ForeignKey. I think my method is not working because the PK is not always starting at 1. example task one have steps pk 1,2,3. Task two have steps pk 4,5,6. Is it possible to make the PK always be 1,2,3 for each task? Then this might work? Or is there a better solution? views.py def step_detail(request, task_pk, step_pk): step = get_object_or_404(Step, task_id=task_pk, pk=step_pk) next_step_pk = step_pk + 1 next_step = Step.objects.filter(pk=next_step_pk) if next_step.count() == 0: next_step_pk = None return render(request, 'dailytask/step_detail.html', {'step': step, 'next_step_pk': next_step_pk}) models.py: class Task(models.Model): created_at = models.DateTimeField(auto_now_add=True) user_completed = models.BooleanField(default=False) title = models.CharField(max_length=255) description = models.TextField(blank=True, default="") category = models.CharField(max_length=255, choices=CATEGORIES, default="traffic") done_message = models.TextField(null=True, default="") def __str__(self): return self.title class Step(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True, default="") user_completed = models.BooleanField(default=False) content = models.TextField(blank=True, default="") order = models.IntegerField(default=0) step_number = models.IntegerField(default=1) task = models.ForeignKey(Task, on_delete=models.CASCADE) class Meta: ordering = ['order', ] def __str__(self): return self.title step_detail.html I want this button to hide when there are no more steps in the task. {% if next_step_pk … -
problems with nomenclature for queried database table
when saved the form, where it is marked that can be blank field as the pago after saved in the table it shows as False, how can I change False by 0 or any other value Models.py class MovRotativo(models.Model): checkin = models.DateTimeField(default=timezone.now()) checkout = models.DateTimeField(null=True, blank=True) email = models.EmailField(blank=False) placa = models.CharField(max_length=8, blank=False) modelo = models.CharField(max_length=15, blank=False) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) chk = models.CharField(("Situação"), max_length=15, choices=SAIDA_CHOICES, default='Não') -
Tablesorter stickyHeaders widget not working
I'm having trouble making my table header to stick using the tablesorter widget. I have the following for my table page: {% load static %} <link rel="stylesheet" href="{% static 'css/theme.default.css' %}" type="text/css" /> <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.tablesorter.js' %}"></script> <table id="myTable" class="tablesorter"> <caption> ... </caption> <thead> <tr> ... </tr> </thead> <tbody> <tr> ... </tr> </tbody> </table> <script> $(document).ready(function(){ $('#myTable').tablesorter({ sortList: [[0,0], [1,0]], widgets: ['zebra', 'filter', 'stickyHeaders'], }); }); </script> I tried labeling my table tag and also creating a div tag around my table, but nothing seems to work. The jQuery version is v1.11.2, and the tablesorter version is v2.31.1.