Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django timesince filter showing '0 minutes' when it is less than one day. How can I fix this?
I am trying to show time since I added a post with following code - {{ listing.list_date|timesince }} and it is showing "0 minutes". But it is showing correctly when it is more than one day. How can I show times less than one day with hours and minutes? -
Django Query Issue (int() argument must be a string, a bytes-like object or a number, not 'BoundField')
So I'm having issues with a query i am running on views.py . Basically on my html page there is a drop down list that has all classroom lists, when you select a class from the drop down list, all the students on the page change to that particular class. Problem with the query is the drop down menu displays the name of the class in a string format and it wants the ID number of class to pass through. Here is my code, I have no idea how to fix this. I appreciate the help. Thank you in advance. Here is the error i am getting : int() argument must be a string, a bytes-like object or a number, not 'BoundField' views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import NhsPointsForm, K8PointsForm from .models import K8Points , NhsPoints, TeacherClass, Student from django.db.models import Sum import datetime @login_required def Nhs_Points(request): if request.method == 'POST': form = NhsPointsForm(request.POST) if form.is_valid(): #username = form.cleaned_data.get('username') points = form.save(commit=False) points.save() return render(request, 'points/nhs_points.html', {'form': form}) else: form = NhsPointsForm() return render(request, 'points/nhs_points.html', {'form': form}) @login_required def K8_Points(request): if request.method == 'POST': form = K8PointsForm(request.POST) if form.is_valid(): … -
How to tell which django forms widget has triggered a POST?
In the following scenario (code in forms.py): class MyForm(forms.Form): option_one = forms.CharField(label='Pick 1st option', widget=forms.Select(attrs={'onChange': 'form.submit();'})) option_two = forms.CharField(label='Pick 2nd option', widget=forms.Select(attrs={'onChange': 'form.submit();'})) The request.POST dictionary will contain both option_one and option_two keys and their values regardless of which onChange event triggered the POST (unlike submit button where the key is only present if it caused the POST). How can I tell which widget actually changed to trigger the POST so that I can work with that info in views.py? -
wrap_socket() got an unexpected keyword argument '_context'
I'm currently trying to put in production a django project using nginx and gunicorn for the first time. The project consist on a register page in wich the user access, fills a form and the data is used to make a request to another server to create a profile using the data taken from the form of my app. To do such task i have the following libraries: requests 2.22.0 gunicorn 20.0.4 eventlet 0.25.1 (with greenlet 0.4.15) The project was entirely tested and functional in a testing enviroment inside an ubuntu 18.04 virtual machine. Now the server in production is a Debian 10. Every web page of the project works corretly and so does the django admin page. The thing is that when i try to fill the form to actually register on the databese of the second server it returns the following error: Environment: Request Method: POST Request URL: http://reg.rocstar.tv/register/customer/ Django Version: 2.2.7 Python Version: 3.7.5 Installed Applications: ['reg.apps.RegConfig', 'import_export', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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 "/home/rocstar/.local/share/virtualenvs/register-page-Z_TgQ-vY/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/rocstar/.local/share/virtualenvs/register-page-Z_TgQ-vY/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/rocstar/.local/share/virtualenvs/register-page-Z_TgQ-vY/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. … -
How to connect django db.sqlite database using python sqlite module
def getConnection(database_type): properties = Settings.getProperty() if database_type.upper() == "SQLITE": DatabaseConnectionFactory.connection = sqlite3.connect(properties.get("DATABASE","SQLITE_PATH")) print("Database Connection created successfully") path in property file - C:\Users\vipin\PycharmProjects\PythonBehaveFramework\db.sqlite3 -
Django ensure you only use CORS Simple Request
My Django app is contacting another server that has OPTIONS Method disabled. As a result CORS rejects the PREFLIGHT request, which should be valid GET request (it's only a basic redirect with HttpResponseRedirect). How do I ensure that I'm only sending CORS headers valid for a Simple request so the preflight never occurs? I'm basing my understanding of CORS simple / preflight requests off this article: https://dev.to/effingkay/cors-preflighted-requests--options-method-3024 -
Website home page prompts to download file
I am facing a irritating issue with my django website hosted in Heroku. It was running well earlier but now when someone click xyz.com, it prompts to download a file which contain source of the home page. other pages like xyz.com/about working fine. Even in Localhost facing same issue. I tried deleting everything from home page and still same issue. So I think home page source code is not causing this. Its been 3 days I am unable to fix it. Anyone please help what might be the reason for it? -
What uses the memory of my python process?
If I execute the Python interpreter it needs roughly 111 MByte: >>> import psutil >>> psutil.Process().memory_info() pmem(rss=19451904, vms=111677440, shared=6905856, text=4096, lib=0, data=12062720, dirty=0) After importing django it uses 641 MByte >>> import django >>> django.setup() >>> psutil.Process().memory_info() pmem(rss=188219392, vms=641904640, shared=27406336, text=4096, lib=0, data=284606464, dirty=0) And the WSGI process (which has already executed some http requests) 919 MByte: >>> psutil.Process(13843).memory_info() pmem(rss=228777984, vms=919306240, shared=16076800, text=610304, lib=0, data=485842944, dirty=0) I think that's too much. What can I do to investigate this in more detail? What occupies the memory? -
Post JS variables to Django view and display as context variables in separate template
I'm trying to achieve three things: collect some user input using standard HTML forms in one template (questions.html below); post that input to my views.py; and finally display that input as context variables in a separate template (results.html below). Once I get this to work, I'll do some processing of the input in the views.py before passing some output on as a context variable - but first I need to figure out the basic principle of moving from user input in one template --> views.py --> context variables in another template. Also, I'm deliberately doing this without touching any database, since I don't want to save any user data. Here's what I have for my questions.html, collecting age and level of education: <script type="text/javascript"> $(document).ready(function(){ $('#submit_answers').submit(function (event) { var user_age = document.getElementById("age-choice").value; var user_education = document.getElementById("education-choice").value; $.ajax({ type:"POST", url:"{% url 'results' %}", data : { 'age': user_age, 'education': user_education, 'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val() }, }) } )}); </script> <p>Please answer the following questions:</p> <p>What is your age?</p> <form action="" method="GET" id="age-dropdown"> {% csrf_token %} <select class="browser-default custom-select" id="age-choice"> <option value="18-30">18-30</option> <option value="30-40">30-40</option> <option value="40-50">40-50</option> <option value="50-65">50-65</option> <option value="65-100">Over 65</option> </select> </form> <p>What is your highest level of education?</p> <form action="" method="GET" id="education-dropdown"> {% … -
File manipulation in Django models.py
I am building a Django app that saves an .stl file passed using a formulary and my goal is to open the file, extract some information with a script that is already tested, and save this information in the same register that the file. I am doing this: def informationGeneration(stl_route, *args, **kwargs): # scripts that generates the information class Piece(models.Model): """Piece model.""" # ... file = models.FileField(upload_to='pieces/files', default='NA') # ... information = models.IntegerField(default=0) def save(self, *args, **kwargs): """Overriding the save method.""" self.information = informationGeneration(self.file) super().save(*args, **kwargs) def __str__(self): # ... The problem is that when I try to save a new instance, numpy-stl detects an error, self.file is not the .stl file, is an alement of the formulary. How can I pass the file and not the route? -
How to make a form in django that can hold a list of questions, and submit them at once
Is there a way to create a form that can hold a list of data in Django, as it is with django-rest serializers? The form must look like this -
How to fix Django 'Can't find msguniq' error
I try to use internationalization in my Django project I follow a tutorial: https://www.youtube.com/watch?v=xI97sLMd1rM but author skip the configuration for gettext I have installed gettext librairie and seems to be OK: xgettext --session in a prompt confirm it is installed And I follow beginning of the tutorial settings.py LOCALE_PATHS = [ os.path.join(BASE_DIR,'locale'), ] base.html {% load static i18n %} {% load static %} # don't know if should import twice static test_translation.html {% extends 'layouts/base.html' %} {% load i18n %} h2>{% trans "A test of translation" %}</h2> however, when I run in my env (env) PS myproject > django-admin makemessages -l fr I got the following error: CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. Do I need to install somethings else? -
Django ModelForms - Display different choice than what will be saved
From the title this sounds like something I shouldn't wanna do. But I have two models. Both have AutoField PK's and model B has a foreign key ID for A. In my form to create B, I have all of B's fields including the foreign key ID. This simply shows up to the user as something like "B Object 1". This is absolutely useless to me as when I have more items I'd rather have a name to identify it to the user. So my question is: can I substitute A.name in place of the foreign key ID, but still save just the foreign key when it comes to saving the model? -
Create nested serializer of same type
Assume there is a child and parent relation in models, such as: class Foo(models.Model): parent = models.ForeignKey('Foo', related_name='children') Now I want to have a serializer to show children of a Foo object, something like this: class FooSerializer(serializers.ModelSerializer): children = FooSerializer(many=True) class Meta: model = Foo fields = '__all__' But this gives me error that it does not recognize FooSerializer when creating that class which is correct regarding the way python parses the class. How could I implement such relation and have a serializer to get its children. I must mention that I want to able to use depth option of nested serializer. I am using django 2.2.7 and rest framework 3.10.1. -
How can I set DJANGO_SETTINGS_MODULE correctly (using virtualenv)?
My Django skill level: noob. I am going nuts at setting the DJANGO_SETTINGS_MODULE properly to finally get my model imported within a script. I use a virtualenv for my project. This is my current error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Background: I first used the solution posted here. However, this solution raised this error... So I hope DJANGO_SETTINGS_MODULE can do the trick. According to the documentation (docu) I have to use Django-admin to set DJANGO_SETTINGS_MODULE. What I've tried: Executed $ set DJANGO_SETTINGS_MODULE=dashex.settings in my command prompt on windows, just nothing happens. Executed $ django-admin set DJANGO_SETTINGS_MODULE=dashex.settings in the manage.py root of my project raises the error no module named dashex. This answer from @Casper suggests to do the above mentioned, but where to insert this: C:\temp\testproject> set DJANGO_SETTINGS_MODULE=testproject.settings ? This solution from @Max suggests to append export DJANGO_SETTINGS_MODULE=<django_project>.settings to my virtual-environment. What is meant with this, how to do that? Executed $ django-admin runserver --settings=dashex.settings which also raises the error no module named dashex. For several reasons I would like to avoid working with the shell. My project: -
Third foreign key to through table
Im having in many to many field 'modules' in CourseShareItem table. I want to add extra data to it using a through table CourseShareItemModule. The through table has foreign keys to both of the tables plus one extra foreign key to another third table.I want to know if this is allowed in Django . I understand Django automatically creates this through table. class CourseShareItem(TenantShareItem): name = models.CharField(max_length=128, default=None, null=False) identifier = models.CharField(max_length=32, default=None, null=False) description = models.CharField(max_length=150, default=None, null=True) modules_ordered = models.BooleanField(default=False) modules = models.ManyToManyField(Module, through='CourseShareItemModule',blank=True) added_by = models.UUIDField(default=None, null=True) time_created = models.DateTimeField(default=timezone.now) class ModuleGroup(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=128, default=None, null=False) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True) equivalency = models.IntegerField(default=0) weight = models.IntegerField(default=0) stop = models.BooleanField(default=False) class CourseShareItemModule(models.Model): course_share_item = models.ForeignKey(CourseShareItem, on_delete=models.CASCADE) module = models.ForeignKey(Module, on_delete=models.CASCADE) max_retries = models.IntegerField(default=1, null=True, blank=True) order = models.IntegerField(default=0) group = models.ForeignKey(ModuleGroup, on_delete=models.PROTECT, null=True, blank=True) weight = models.IntegerField(null=True, blank=True) stop = models.BooleanField(default=False) -
Django NOT NULL constraint failed: users_profile.slug
I'm trying to create user profile automatically and it didn't work so I tried adding it with the admin panel and it gives me this error IntegrityError at /admin/users/profile/add/ NOT NULL constraint failed: users_profile.slug Heres my user profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) image = models.ImageField(default='', upload_to='profile_pics') real_name = models.CharField(max_length=150) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) here the view that create the profile: @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm( request.POST, request.FILES, instance=request.user) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been Updated!') return redirect('/') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, 'users/profile.html', context) Automatic profile generating signal: @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() -
Submit button with javascript passing two values
I want to pass name and value from buttons submitting by js. How to pass those values to submit? I only want first button to take action by js with double confirmation. {% if zami.akcept == False and zami.wyslane == False %} <form method="post" id="systemForm"> {% csrf_token %} <button type="button" onclick="testFunction(this)" name="akcept" value={{zami.id}} form="systemForm" class="akceptacja" data-toggle="tooltip" data-html="true" data-placement="top" title="<b>Tooltip</b> on top">Akceptacja</button> <button type="submit" name="system" value={{zami.id}} form="systemForm" class="akceptacja">Do poprawy</button></form> {% endif %} JS script: <script> function testFunction(elem) { var t = elem.id var nazwa = elem.name var wartosc = elem.value alert(wartosc); swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", icon: "warning", buttons: [ 'No, cancel it!', 'Yes, I am sure!' ], dangerMode: true, }).then(function(isConfirm) { if (isConfirm) { swal({ title: 'Shortlisted!', text: 'Candidates are successfully shortlisted!', icon: 'success' }).then(function() { document.getElementById('systemForm').submit(); }); } else { swal("Cancelled", "Your imaginary file is safe :)", "error"); } }); }; </script> -
I want users to vote only once and for only one option for my polling app I made with django
I am new to django, and wanted to improve the polls tutorial app. this is the exact code from the tuttorial but this allows users to vote again for the same or different option if they want to, I want to restrict users to only one vote and choice per question. VIEWS.py def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) #shows results -
Save user details after phone verification
I have phone verification in my project. It sends otp to users and they need to verify. When otp is sent and verified it should save user data in the DB. But I am saving before verifying their phones and I do not know how to do it. Can anybody help please? here is my code views.py class RegisterApi(views.APIView): permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): phone_number = request.data.get('phone', False) first_name = request.data.get('first_name', False) last_name = request.data.get('last_name', False) password = request.data.get('password', False) if phone_number and first_name and last_name and password: phone = str(phone_number) user = User.objects.filter(phone__iexact=phone) if user.exists(): return Response({ 'status': 'Fail', 'detail': 'Phone number is already existed' }) else: key = send_otp(phone) if key: old = OTPModel.objects.filter(phone__iexact=phone) if old.exists(): old = old.first() count = old.count if count > 5: return Response({ 'status': 'Fail', 'detail': 'Limit Exceeded' }) old.count = count + 1 old.save() return Response({ 'status': 'True', 'detail': 'OTP resent', 'response': response }) else: OTPModel.objects.create( phone=phone, otp=key ) serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ 'status': 'True', 'detail': 'OTP sent successfully', 'account': serializer.data }) else: return Response({ 'status': 'Fail', 'detail': 'Error in sending otp' }) else: return Response({ 'status': False, 'detail': 'Phone number is not entered' }) To … -
Xmlsec library to implement Django SAML2 Authentication
I'll use this Django package to integrate SAML2 Authentication into my django APP : https://github.com/fangli/django-saml2-auth. This package requires xmlsec libary, unfortunately i am using windows server where i will install this library. I've tried to install it in windows by following the documentation : I got the library here : https://www.aleksey.com/xmlsec/download.html I got windows binaries from here : https://www.zlatkovic.com/pub/libxml/64bit/ After following the documentation to install this libary on windows : i could configure the install by : cscript configure.js prefix=c:\opt include=c:\opt\include lib=c:\opt\lib debug=yes This is the result : Microsoft (R) Windows Script Host Version 5.812 Copyright (C) Microsoft Corporation. All rights reserved. libxmlsec version: 1.2.29 Created Makefile. XMLSEC configuration ---------------------------- Use Crypto: openssl Use Default Crypto: openssl Use OpenSSL: Enabled Use OpenSSL Version: 110 Use NSS: Disabled Use MSCrypto: Disabled Use MSCng: Disabled Use LibXSLT: Enabled Use iconv: Enabled NT 4.0 support: Enabled Win32 build configuration ------------------------- C-Runtime option: /MD Unicode: Enabled Debug symbols: Enabled Warnings as errors: Disabled C compiler: cl.exe C compiler flags: Static xmlsec: Enabled Enable DL support: Enabled Install prefix: c:\opt Put tools in: $(PREFIX)\bin Put headers in: $(PREFIX)\include Put static libs in: $(PREFIX)\lib Put shared libs in: $(PREFIX)\bin Include path: c:\opt\include Lib path: c:\opt\lib i've … -
Django FilePathField raises file not found error
I've defined a Django model which makes use of FilePathField(allow_files=False, allow_folders=True) which shall allow to define a file system directory in the model. If I try to add a new model in the admin interface I get a file not found error. All my other models registered the same way are just working fine. How can I fix the model making use of the FilePathField field? -
Making a dependent dropdown required when there are available options using Django?
I have a form with a dependent drop-down that I implemented using this tutorial https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html. Currently, I have it set so that the second drop-down only appears if there are options available in it, otherwise is hidden. What I am having trouble with is that, whenever you choose a primary(Work Area) option that has a secondary(Station) drop-down, you can submit the form without having selected an option from the dependent (secondary) drop-down, which is supposed to be required whenever there are options in it. How can I modify this so that the dependent drop-down is required whenever it appears? models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Station(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE, related_name="stations") name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = Station.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = Station.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['station_number'].queryset … -
mypy django rest framework - Unsupported left operand type when multiple permission classes are used
I am integrating mypy on a existing codebase(using django, drf frameworks). Sample code in view.py: @api_view() @permission_classes([IsAuthenticatedOrReadOnly | IsAdminUser]) def listAbc(request): queryset = ... serializer = ... return Response(serializer.data) Result: $ mypy error: Unsupported left operand type for | ("Type[IsAuthenticatedOrReadOnly]") Plugins used: $ pip list | grep stubs django-stubs 1.2.0 djangorestframework-stubs 1.0.0 mypy configuration file (mypy.ini): [mypy] plugins = mypy_django_plugin.main, mypy_drf_plugin.main ;ignore_missing_imports = True files=**/*.py [mypy-*.migrations.*] ignore_errors = True [mypy.plugins.django-stubs] django_settings_module = project.settings Checked with both mypy (0.720 and 0.740). What could be the issue here ? Since the operation '|' is not recognized by mypy, I suspect the metaclass BasePermissionMetaclass (containing the operations) is not added BasePermission during mypy evaluation. I assume just installing djangorestframework-stubs and configuring the same in mypy.ini is enough. -
Why i can't to update nested serializer by id?
When i send data throw PUT request this id can't get this id in validated data. For example body of PUT request: { "slug": "string", "company_id": 1, "api_secret": "string", "merchant_url_list": [ { "id": 1 "merchant_url_type_id": 1, "url": "string" } ] } But in validated_data {'slug': 'string', 'company': <Company: Company object (1)>, 'api_secret': 'string', 'merchanturl_set': [OrderedDict([('merchant_url_type', <MerchantUrlType: Бот (None)>), ('url', 'string')])]} There is not id. How i can get id? class MerchantUrlSerializer(IdModelSerializer): merchant = serializers.PrimaryKeyRelatedField(required=False, read_only=True) class Meta: model = MerchantUrl fields = ('id', 'merchant_url_type', 'merchant', 'url') class MerchantSerializer(NestedSerializerMixin, IdModelSerializer): merchant_url_list = MerchantUrlSerializer(source='merchanturl_set', many=True) class Meta: model = Merchant fields = ('id', 'slug', 'company', 'api_secret', 'merchant_url_list') { "slug": "string", "company_id": 0, "api_secret": "string", "merchant_url_list": [ { "merchant_url_type_id": 0, "url": "string" } ] }