Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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" } ] } -
Could not import QUERY_TERMS
I am running a website through Python and Django . Django-filters=2.1 installed Django=2.1 installed when i run, i get the error, importError: Could not import 'django_filters.rest_framework.DjangoFilterBackend' for API setting 'DEFAULT_FILTER_BACKENDS'. ImportError: cannot import name 'QUERY_TERMS' from 'django.db.models.sql.constants' (C:\Users\Android V\AppData\Loc al\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\constants. py). -
Unable to install gettext
I work in Django and want to implement internationalization I have admnistration right I need to install gettext but even following doc (https://www.drupal.org/docs/8/modules/potion/how-to-install-setup-gettext) it does not works My prompt display that gettext is not recognize... I have downloaded the 2 gettext files required (runtime and tools - V0.17) I get thoses folders for gettextruntime: bin lib manifest I get thoses folders for gettexttools: bin include lib manifest share Then I extract bin content of each files in a new folder: C:\Programmes\gettext (I also try to extract in a bin folder: C:\Programmes\gettext\bin) I have set my Path with C:\Programmes\gettext\bin don't know what is the problem? why other folders not mandatory? -
How do i implement a new feature in my Django framework website [closed]
I want to add a "add to wishlist" and some other ones. I have already tried to -
In Django, how to create .svg file of QR code and store models.py fields in QR code?
I am facing some issues regarding QR code generation in SVG format. When I feed 4 fields of data in qrform.html to generate QR code, the data is stored in the database but it was not showing any SVG file in project folder that is QR code data is submitted in the database but not creating SVG file. In views.py file, how to store all models field in QR code. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class qrcod(models.Model): Type_Of_Wallet = models.CharField(max_length=120) BLE_MAC_ID = models.CharField(max_length=17) Bar_code = models.CharField(max_length=100) Version = models.FloatField(blank=False) def __str__(self): return self.Type_Of_Wallet forms.py from django import forms from .models import qrcod class QRForm(forms.ModelForm): class Meta: model = qrcod exclude = [] urls.py from django.conf.urls import url from . import views app_name = 'qrcodes' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^topics', views.topics, name='topics'), url(r'^qr_topic/$', views.qr_topic, name='qr_topic'), url(r'^output/$',views.output, name='output'), ] views.py from django.shortcuts import render from .models import qrcod import requests from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from .forms import QRForm import pyqrcode from pyqrcode import QRCode # Create your views here. def index(request): return render(request,'index.html') def topics(request): topics = qrcod.objects.all() context = {'topics':topics} return render(request, 'qrcode.html', context) def … -
Error while connecting Django with sql server database
Im using mssql as the backend for the database.In the setting.py file,I need to use the host name with backslash. Due to this, I got the timed out error. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'xxxxx', 'USER': 'xxx', 'PASSWORD': 'xxxx', 'PORT': '1433', 'HOST': 'aaa\bbb', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', }, } } Is there any way i could use the backslash in the host name. Thanks in advance.Please help me sort out. -
Does Django get() performs query to database on values()?
I have values queryset, if I get some date from it, does this perform a call to the database? instances_values = Model.objects.filter(**kwargs).values(*args) instance_with_id_one = instances_values.get(id=1) # does this perform a call to the databse? -
Send an array with ajax to my python function in django
I'm trying to send an array to my python function inside views.py but I can't. It always crash with a keyError because is not recognising the data from js. Code: Python function in views.py: def cargar_datos_csv(request): if request.method == 'POST': filtros = request.POST['node'] print(filtros) ctx = {'A':filtros} return JsonResponse(ctx) JS var csrftoken = $("[name=csrfmiddlewaretoken]").val(); var frutas = ['Manzana', 'Banana']; $.ajax({ url: '/../../data_bbdd/', type: 'POST', headers:{"X-CSRFToken": csrftoken}, data: { 'node': frutas, }, dataType: "json", cache: true, success: function(response) { coords = JSON.stringify(response.A); alert(coords); } }); How can I send an array to my python function? Thank you very much. -
While-True loop results in RecursionError because of django.setup()
I try to build a function that runs 24/7 (while True). The function is supposed to fetch data, convert the received string and populate the PostgreSQL DB. However, when I run the below shown script/function, I get an RecursionError: maximum recursion depth exceeded while calling a Python object which implies that something is wrong with the looping logic I guess. Why is that? feeder.py import django from django.conf import settings import zmq import time from time import sleep import uuid settings.configure(settings) django.setup() from Dashboard_app.models import AccountInformation # create zeroMQ Pull Socket to fetch data out of the wire context = zmq.Context() zmq_socket = context.socket(zmq.PULL) zmq_socket.bind("tcp://*:32225") time.sleep(1) while True: # check 24/7 for available data in the pull socket try: msg = zmq_socket.recv_string() data = msg.split("|") print(data) # if data is available, convert received string to required datatypes and assign variables version = data[1] DID = uuid.UUID(data[2]) accountNumber = int(data[3]) broker = data[4] leverage = data[5] account_balance = float(data[6]) account_profit = float(data[7]) account_equity = float(data[8]) account_margin = float(data[9]) account_margin_free = float(data[10]) account_margin_level = float(data[11]) account_currency = data[12] # push the manipulated data to the PostgreSQL DB using `AccountInformation` model feed = AccountInformation( version=version, DID=DID, accountNumber=accountNumber, broker=broker, leverage=leverage, account_balance=account_balance, account_profit=account_profit, account_equity=account_equity, account_margin=account_margin, … -
Django checkbox update
hey guys i need some help with a checkbox of mine here is my model: class Legend(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) title = models.CharField(max_length=100) description = models.CharField(max_length=1000) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_created = models.DateTimeField('date created', auto_now_add=True) date_edited = models.DateTimeField('last edited', auto_now=True) date_pub = models.DateTimeField('date pubished', blank=True, null=True) is_pub = models.BooleanField(default=False) image = models.ImageField(upload_to='gallery/legends', blank=True, null=True) here is my view: def legend_update(request, id): template_name = 'legends/update.html' if request.method == 'POST': form = LegendUpdateForm(request.POST, request.FILES) if form.is_valid(): legend = get_object_or_404(Legend, pk=id) legend.title = form.cleaned_data.get('title') legend.description = form.cleaned_data.get('description') legend.image = form.cleaned_data.get('image') legend.is_pub = form.cleaned_data.get('is_pub') print('is published: ', legend.is_pub) legend.save() return HttpResponseRedirect(reverse('pages:owned')) and the part in my template: <div class="row s12"> <label> <input id="id_is_pub" name="is_pub" type="checkbox" {% if form.is_pub.value %}checked{% endif %}> <span>Veröffentlichen <small>(macht deinen Champion auf der Seite sichtbar für andere)</small></span> </label> </div> the reason im manually creating the form are the file input and the checkbox, since django doesnt create the proper layout which the mateializecss needs it ot be How do i update the value properly in the view since there seems to be a problem getting the value from the input box if it is checked or not Django version: 2.27 python version: 3.8 -
django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading
I installed spatialite for Django project but when I try to migrate it show me this error File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/contrib/gis/db/backends/spatialite/base.py", line 44, in get_new_connection raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading. I don't know how to figure out I tried this -
Getting token from local storage slowly in django rest framework & react development
AuthAction.js -> export const authLogin = (username, password) => { return dispatch => { dispatch(authStart()); axios.post('http://127.0.0.1:8000/rest-auth/login/', { username: username, password: password }) .then(res => { const token = res.data.key; const expirationDate = new Date(new Date().getTime() + 3600 * 1000); localStorage.setItem('token', token); localStorage.setItem('expirationDate', expirationDate); dispatch(authSuccess(token)); dispatch(checkAuthTimeout(3600)); axios.defaults.headers.common['Authorization'] = localStorage.getItem('token'); }) .catch(err => { dispatch(authFail(err)) console.log("ERROR") }) } } I want to make accessible the dashboard page when it gets the token. but First time it doesnt get the token so return the unauthorized message then after 2/3 seconds it redirects to dashboard automatically. Dashboard.js-> const {auth} = useSelector(state => ({ auth : state.authenticated })) const dispatch = useDispatch(); React.useEffect(()=>{ dispatch(actions.authCheckState()) },[]) if(!auth){ return( <p>Unauthorized</p> ) } -
Can't use variable in django template tag in AJAX function
Let say that my AJAX success: function(data) looks like this: success: function(data){ var li, trans_pk; for (i=0; i<data['income_transactions'].length; i++){ li = document.createElement('li'); trans_pk = 1; li.innerHTML = `<a href="{% url 'update_expense' ${trans_pk} %}">edit</a>`; document.querySelectorAll('.list_of_transactions')[0].appendChild(li); } } And it throws me an error: Could not parse the remainder: '${trans_pk}' from '${trans_pk}' But it works fine when I simply hard-code it: li.innerHTML = `<a href="{% url 'update_expense' 1 %}">edit</a>`; I can't figure it out how to do it with variable though. What am I missing here? -
How to allow superuser to edit or delete all data in django rest framework?
How to allow superuser to edit or delete all data in django rest framework but i want to do user only can see his data not others. I made that user only can see his data but admin cant see or cant edit.