Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django API calls on SSO enabled service now
the requirement is to fetch the incident details based on incident number from service now which is SSO enabled. Currently we are trying to fetch the incident details of service now from a Django application by django APIs but it is saying authentication failed because service now is SSO enabled. I am passing URL with username and password as below r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass')) and its saying not valid. The service now API is being called from the same server. -
Am a newbie in django, am trying to count number of app registration request but result does not display on the template?
below is my code that i was trying to implement the task my views.py this is my view for counting the request def appSummary_view(request): context = {} user = request.user applications = ApplicationRequest.objects.all().filter(developer=user) total_request = applications.count() registered_app = applications.filter(status=1).count() pending_app = applications.filter(status=0).count() context = {'total_request':total_request, 'registered_app':registered_app, 'pending_app':pending_app} print(applications) return render(request, 'dashboard.html', context) #my models this is my model for app request class ApplicationRequest(models.Model): id = models.BigAutoField(primary_key=True) developer = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="%(app_label)s_%(class)s", null=True, blank=True, on_delete=models.CASCADE, ) name_of_app = models.CharField(max_length=255, blank=True,null=True) domain = models.CharField(max_length=100, unique=True,null=True) org_name = models.CharField(max_length=200,null=True) redirect_uris = models.TextField( blank=True, help_text= ("Allowed URIs list, space separated") ) claim_of_property = models.TextField( blank=False, help_text= ("Proof of property, space separated"),null=True ) date_requested = models.DateTimeField(auto_now_add=True) status = models.IntegerField(default=0) def __str__(self): return self.name_of_app #my forms.py this is my form for registering the applications class RegisterAppForm(forms.ModelForm): name_of_app = forms.CharField(max_length=255, help_text='Required.Please enter the name of your applications') domain = forms.CharField(max_length=100, help_text='Required.Please enter the domain for your application') org_name = forms.CharField(max_length=200, help_text='Required.Please enter the name of the organization of your application') redirect_uris = forms.CharField(max_length=400,help_text='Required.Please enter redirect uris for your app') claim_of_property = forms.CharField(max_length=400, help_text='Required.Please provide the proof of property') class Meta: model = ApplicationRequest fields = ('name_of_app', 'domain', 'org_name', 'redirect_uris' , 'claim_of_property') template code this is my template … -
how can remove city name and update society name and save it into the database?
So I want to know how can I remove the city name from the society name and update the society name and save it into the database? Below code is taking all the society names that contain the city name. but I want to update all the society's names and save them. qs = Society.objects.all() citys = City.objects.values_list('name', flat=True) clauses = (Q(name__iendswith=name) for name in citys) query = reduce(operator.or_, clauses) data = qs.filter(query) Thanks!! -
Django Grapelli change background column headers
I'm using django grapelli. In my model there is color field which users can select color with colorfield widget. I want to change columns header background color. Does anyone know anything about this? I couldn't found anything. -
Django - How do you handle Two way Bindings
I have the following two models: class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) steps = models.ManyToManyField('manager.Step', related_name='steps') However when editing the Schedule and adding steps via admin the Step does not update its schedule? How do you handle two way binding like this in Django? -
Get rid of   in ckeditor Django
How I can get rid of &nbsp appearing on templates, when using django-ckeditor, I tried with 'entities_additional': '' in settings as follows but still it is visible when using quotes or double space. CKEDITOR_CONFIGS = { 'default': { 'toolbar': [["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Subscript", "Superscript"], ['Undo', 'Redo'], ["Source"], ["Maximize"]], 'height': 250, 'width': '100%', 'entities_additional': '' }, } -
why if i call the fields of the form one by one and i have action on the button reliant to this form there was no result displayed on Django
i want to use a form but what i want is calling the fields of the form one by one on the Html template and then if i click on a button "there was some calculation results will be displayed" , after much tries I have found that if i call the all the form in the html template using: <form action="{% url 'areas' %}" method="post" id="maincont" novalidate> {% csrf_token %} {{ form }} <button id="reslink" >Result</button> </form> --------> It works fine and show me the result values what i want to do call the fields of the form one by one on the html <form action="{% url 'areas' %}" method="post" id="maincont" novalidate> {% csrf_token %} <p>{{ form.domestic_residential}} Domestic and residential areas ml</p> <p>{{ form.office_area}} Office areas ml</p> <input id="submit" type="button" value="Click"/> <p >{{ resultat }}</p> </form> --------> It doesn't show any result. Any help will be appreciated because really i want to do it ( i want to call the fields one by one for things reliant to the design of the page). I want Just to know How i can correct this part of template to make me show some results( or any advices or some one had … -
Django CeleryTask return GeoDataFrames leads to TypeError: Object of type int64 is not JSON serializable
I am trying to build a web app in which I make use of celery to tackle a long running process. I need to pass to the view that called the task a couple of GeoDataFrame and an epsg projection value. return {'Working_area_final': Working_area_final.to_json(), 'PoI_buffer_small': PoI_buffer_small.to_json(), 'Streets_gdf': Streets_gdf.to_json(), 'PoI_buffer_BIG_exp': PoI_buffer_BIG_exp.to_json(), 'projection': str(proj.to_epsg(), 'ip': ip.to_json()} The problem occurs here. I get 'TypeError: Object of type int64 is not JSON serializable'. I can tell that before this command I manage to successfully print to console everything that has to be passed as result. -
distance based ordering in django
So i am using django and get user's location at registration time. Then i show these users on the front page of the app but sorted as per the distance, i.e, the closest ones to the logged in user are on the top and so on. Now what i am doing is i am ordering them as per distance on the backend using some annotate (etc) functions provided by django ORM. sortedQueryset = self.get_queryset().annotate(distance=Distance( 'coords', user.coords, spheroid=True)).order_by('distance') Where 'coords' is the column in db to store the point (location), user.coords is point (coordinates) of the logged in user. Now to get only first 100 users (say) from the database i can do something like this; sortedQueryset = self.get_queryset().annotate(distance=Distance( 'coords', user.coords, spheroid=True)).order_by('distance')[:100] But what it think, it still grabs all the rows, orders them as per distance and then gets 100 of them. Say we have a million users in db, then it always has to get all those and then sort them and then get only 100. I think it is a lot of overwork (maybe i am wrong or maybe this is the only way as i have to sort as per distance and that also depends on the … -
how to implement automatically send email when MySQL column get updated (django+MySql)
I have models like Id, Name, email, Status. And created serializers and views. I am updating the Status values by PUT method. How to implement an automatic email notification to smtp.example.com with the changed Status value. Ex: Status column value is 'abc' I am updating value 'abc' to 'xyz' using PUT. I want an email should automatically send to particular email-id belongs to that row using primary key Id. -
Pass request URL parameter into create view
I am hoping this is a simple tweak. I've been reading through various threads here but I am missing a very basic step -- how do I grab the argument from the URL request? For instance, the URL is http://127.0.0.1:8000/registration/student/item/create/8 URL definition is path('student/item/create/<int:pk>',views.CreateStudentBehaviorItem.as_view(),name='student_item_create'), My class view is as follows: class CreateStudentBehaviorItem(LoginRequiredMixin, generic.CreateView): model = StudentItem form_class = StudentItemForm success_url = reverse_lazy('registration:student_item_list') def get_form_kwargs(self): kwargs = super(CreateStudentBehaviorItem, self).get_form_kwargs() kwargs['pk'] = self.request.GET.get('pk') return kwargs The form is: class StudentItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.course = kwargs.pop('pk', 'all') super().__init__(*args, **kwargs) # Begin filtering by course ID class Meta: model = StudentItem fields = ("item_student","behavior_category","behavior_item","response","internal_comments") widgets = { 'item_student': forms.Select(attrs={'class': 'form-control'}), 'behavior_category': forms.Select(attrs={'class': 'form-control'}), 'behavior_item': forms.Select(attrs={'class': 'form-control'}), 'response': forms.Select(attrs={'class': 'form-control'}), 'internal_comments': forms.Textarea(attrs={'class': 'form-control', 'rows':5}), } I haven't even gotten to the point to filter because I can't seem to get the PK from the request URL. My minimal Django experience is with get_context_data to grab request URL details. I hope this is a simple correction to grab the value. I appreciate it. -
Django deployment on Heroku failed due to "ModuleNotFoundError at / No module named '_tkinter'"
I'm trying to deploy my Django app to Heroku and this error faced me on deployment I'm not using tkinter anywhere on my app of course and the stack trace does not point to my app the app is running with no issues locally -
ProgrammingError at /admin/patients/appointment/ column patients_appointment.date does not exist
I am facing the above error, even though the "date" column is there in the model. class Appointment(models.Model): name=models.ForeignKey(Patient, on_delete=CASCADE) doctor=models.ForeignKey(DoctorDetail, on_delete=CASCADE) start_time=models.TimeField() end_time=models.TimeField() date=models.DateField() def __str__(self): return self.name.name This was the error I was facing: -
Django Multiple Databases for Different Users
I'm wondering if it's possible to use multiple databases for different users in the same app? I've read about the multiple database documents and searched a lot online but could'nt found any tutorial for it. Is there any way to use different databases for different users in the same app ? -
Django with Postgres - Unique Constraint for One Tenant in Multitenant Database
I've been reading and reading and reading, but finally decided to shortlist my questions regarding multitenant Postgres with Django. I'm quite new with using Django, so please bear with me. We are developing a multitenant business platform with more than 300 tables. For tenants' ids, we have chosen UUID4, so there are my questions coming: Is it enough to use UUID4 for tenants' and users' ids only and then reference them as foreign keys in every other table? If not, Is there a need to use UUID4 in every table? That means that pk in each table will be UUID and that table will have all foreign keys as UUID4s as well.... The second solution would be the UUID4 for tenants' and users' pks only. Other tables would have bigint pks and only 2 foreign keys as UUID (tenant & user). In some tables, we need to have other unique data than just pk (such as names, document numbers, tax data and so on). Is there a way to determine/check the uniqueness of such data in a tenant dataset by db constraint or should that be solved by code? The data volume and number of tenants and users are in … -
How to get ids of the objects from django model?
How to get ids of the objects from the model. qs = Society.objects.all() cityID = City.objects.get(pk=1) The above query will return only one object whose id is 1. but I need all cities id so that can I access the city's names from id as you can see in below code. for s in qs: ... s_name = qs.filter(name__iendswith=cityID.name) ... break -
Live Recording -- saving to google cloud storage -- is it possible
i am wondering is there any possibility of uplaoding the live stream or recording to the google storage frame by frame with audio and video, aws is having the live recording storage options but i am not finding any good resources with the google cloud storage. is there any one out there who can help me with this problem? Thanks in advance. -
Django ajax url not reading
I have an ajax file which calls the url from the urls.py which gets the json data from the views.py but when I run the server it just shows Not Found:/dept-json/ I did manage to get it to work using the django snippet {% url 'accounts:dept-json'%} However I do not want this since I need to get and pass the variable from the dept-json data to another ajax url which is: url:`/prog-data/${selectedDept}/` I have read here that you can't pass variables in ajax like {% url 'accounts:prog-json' department%} how do I manage to do this? here is my code: main.js $.ajax({ type: 'GET', url: "/dept-json/", // url: "{% url 'accounts:dept-json'%}", success: function(response){ console.log(response) }, error: function(error){ console.log(error) } }) urls.py path('dept-json/', get_json_dept_data, name='dept-json'), path('prog-json/<str:department>/', get_json_prog_data, name='prog-json'), views.py def get_json_dept_data(request): qs_val = list(Department.objects.values()) return JsonResponse({'data':qs_val}) def get_json_prog_data(request, *args, **kwargs): selected_department = kwargs.get('department') obj_prog = list(Program.objects.filter(department__name=selected_department).values()) return JsonResponse({'data':obj_prog}) -
I already have a form created in HTML, how can I post the data from this form to the user's account on the Django database?
I am working on the project in which one user can create a quiz on the HTML pages without coding, in an interactive way. This created quiz should be displayed on the screen of another user, who will be attempting the tests. I am using Django framework for backend and I am very new to backend. -
Djangi : django.core.exceptions.FieldError: Cannot resolve keyword 'email' into field
**I Got errors like that, please help me. django.core.exceptions.FieldError: Cannot resolve keyword 'email' into field. Choices are: auth_token, created_at, id, is_verified, nama, order, pengiriman, user, user_id view.py def processOrder(request): id_transaksi = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.profile order, created = Order.objects.get_or_create(user=customer, selesai=False) else: customer, order = gusetOrder(request, data) total = float(data['form']['total']) order.id_transaksi = id_transaksi if total == order.get_cart_total: order.selesai = True order.save() if order.shipping == True: Pengiriman.objects.create( user=customer, order=order, alamat=data['shipping']['address'], kota =data['shipping']['city'], provinsi=data['shipping']['state'], kode=data['shipping']['zipcode'], ) return JsonResponse('Payment complete', safe=False) checkout.html function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'name':null, 'email':null, 'total':total, } var shippingInfo = { 'address':null, 'city':null, 'state':null, 'zipcode':null, } if (shipping != 'False'){ shippingInfo.address = form.address.value shippingInfo.city = form.city.value shippingInfo.state = form.state.value shippingInfo.zipcode = form.zipcode.value } if (userau == 'False'){ userFormData.name = form.name.value userFormData.email = form.email.value } console.log('Shipping Info:', shippingInfo) console.log('User Info:', userFormData) var url = "/process_Order" fetch(url, { method:'POST', headers:{ 'Content-Type':'applicaiton/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction completed'); cart = {} document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" window.location.href = "{% url 'store' %}" }) } base.html function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for … -
Relation between two models in Django
It seems like a trivial question but I am new to Django. I have two models user and competition. The user can create and join one or many competition. How to specify this relation as the user can be the owner of competition/s and can be a participant in one or more competition. -
data encryption on amazon Aurora and django system
I am using amazon aurora and django. Now, thinking about using RDS encryption Hoever while reading documents, a few questions come up to me. My final goal is encrypting data itself, even mysql root user can not check the data. This doesn't encrypt the database data itself, so if DB user/password is leaked, the data could be stolen? Is there any good way to encrypt the data in database? even root mysql user can not check the data. I am using django, It is enough that only django can encode-decode the data. I should use some django library not database itself? or database has some structure for this purpose? -
Django still working fine even when DEBUG=False in settings.py
In settings.py, DEBUG set to True. But when we move it to the production we should be setting DEBUG=False. So in my local environment itself, I have changed to DEBUG=False. But still my application is working fine even with this settings. Usually when we changed DEBUG to false we should be getting some issues like 500 or 404 error something like that , but in my case its not like that. I have referred this """ https://stackoverflow.com/questions/38617046/django-debug-false-still-runs-in-debug-mode/47266619""" but it did not help much for me. Please let me know if i misunderstood or missed something. Below is the small snippet of code i have in settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'MyApp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] 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', ] Please let me know if i need to provide anymore details. -
DJANGO : checkout:293 POST http://127.0.0.1:8000/process_Order 403 (Forbidden)
```Help errorrrhi [enter image description here][1]I got error like that please help me[ def processOrder(request): id_transaksi = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.profile order, created = Order.objects.get_or_create(user=customer, selesai=False) else: customer, order = gusetOrder(request, data) total = float(data['form']['total']) order.id_transaksi = id_transaksi if total == order.get_cart_total: order.selesai = True order.save() if order.shipping == True: Pengiriman.objects.create( user=customer, order=order, alamat=data['shipping']['address'], kota =data['shipping']['city'], provinsi=data['shipping']['state'], kode=data['shipping']['zipcode'], ) return JsonResponse('Payment complete', safe=False) function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'name':null, 'email':null, 'total':total, } var shippingInfo = { 'address':null, 'city':null, 'state':null, 'zipcode':null, } if (shipping != 'False'){ shippingInfo.address = form.address.value shippingInfo.city = form.city.value shippingInfo.state = form.state.value shippingInfo.zipcode = form.zipcode.value } if (userau == 'False'){ userFormData.name = form.name.value userFormData.email = form.email.value } console.log('Shipping Info:', shippingInfo) console.log('User Info:', userFormData) var url = "/process_Order" fetch(url, { method:'POST', headers:{ 'Content-Type':'applicaiton/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction completed'); cart = {} document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" window.location.href = "{% url 'store' %}" }) } function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this … -
Can I access Django Admin Site using deployed URL?
I just deploy my first Django Rest Framework into Heroku. Site URL is https://mysite.herokuapp.com/ I already can access admin site using http://127.0.0.1:8000/ through created superuser account. But How I am gonna access the admin site using the deployed url?. Thanks