Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter objects based on the value of a field of the last data in another model
There are 2 models class A(models.Model): name = models.TextField() class B(models.Model): a = models.ForeignKey(A) status = models.BooleanField(default=False) Now I want to filter objects of class A based on the last data in class B status. if there are 2 datas of Model B id | a | status 1 | abc | False 2 | abc | True So if I want to filter objects of Model A which are having status False. In this case it will give me abc. If I wanted to filter objects of Model A which are having status True. In this case it should not return me abc. I want to write a query something like A.objects.filter(b__status__last=True) Is it possible to do using filters? -
register your Django router
when i use route.register(r'codes', SmsCodeViewset) don't add base_name="", this is an error `AssertionError: `basename` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. when i useroute.register(r'codes', SmsCodeViewset, bose_name="")` there is no error ,may i ask why? -
How can I avoid users having to reenter their password when signed in to o365?
I am building a webapp with Django which allows our users to create a meeting in their office365 calendar while also storing the meeting in a database so we can display some information about it on a screen in the office. I am using exchangelib to create the meetings and it works really well. I want to make it so our users do not have to enter their passwords for their o365 account every time they use it, but I would prefer not storing the passwords locally either since they change regularly. Our users are always logged in to sharepoint or owa when they use this app is it possible to get their credentials from there? Or is it possible to link it to our local AD? -
Django 1.11 ManyToMany
I'm having problems with Django 11.1. I added a ManyToMany relation to a file upload but in Admin there is no option to send the files. In this system I have the registration information of a course and I need to send files to download. There may be several files per course, so a ManyToMany interface. Below is the image of how Admin is showing the field. Django Admin input print models.py class PalestraFile(models.Model): file = models.FileField( upload_to=path_and_rename('uploaded_files/palestra/'), blank=True, verbose_name="Arquivo da programação", help_text="(.pdf, .doc, .txt, .png, .jpg)") class Palestra(Programacao): palestrante = models.ForeignKey(Palestrante, null=True, blank=True, limit_choices_to={'ativo': True}) palestrantes = models.ManyToManyField( Palestrante, related_name='palestra_palestrantes', blank=True, limit_choices_to={'ativo': True} ) file = models.ManyToManyField( PalestraFile, related_name='palestra_palestrafiles', blank=True, verbose_name="Arquivos da palestra") class Meta: verbose_name = 'Palestra' verbose_name_plural = 'Palestras' def __str__(self): return '%s | %s ' % (date(self.dia, "d/m"), self.tema) admin.py from django.contrib import admin from .models import Palestrante, Palestra, PalestraFile from .forms import PalestranteFormAdmin @admin.register(Palestrante) class PalestranteAdmin(admin.ModelAdmin): form = PalestranteFormAdmin list_display = ['nome', 'email', 'slug', 'ativo'] prepopulated_fields = {"slug": ("nome",)} # actions = ['compress_uploads'] def compress_uploads(self, request, queryset): for obj in queryset: obj.save() compress_uploads.short_description = "Comprimir Imagens de Uploads" @admin.register(Palestra) class PalestraAdmin(admin.ModelAdmin): search_fields = ( 'tema', 'palestrante__nome', 'dia', 'evento__nome', 'evento__local' ) list_display = [ 'evento', 'palestrante', … -
Dynamic DOB Year selection in Django
I am using django 1.7.7. I want to make a year selection dropdown using for loop. <option value="0">Year</option> {% for year in 2018|getxrange:1893 %} if year < 10 %} <option value="0{{year}}">0{{year}}</option> {% else %} <option value="{{year}}">{{year}}</option> {% endif %} {% endfor %} Instead of 2018 I want a dynamic year. My Try: {% with now "Y" as name %} {%endwith%} Its not working. please suggest better way to achieve this. -
AWS lambda serverless website (using django ) session maintaining
I developed a website using django. Recently I am trying to make it serverless and deploy to lambda. I haven't figured out how to maintain the session after user logged in when deployed to lambda.any suggestions please. -
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