Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTML button not executing Javascript function [closed]
I am a building a website and I have encountered a small issue with Javascript. The following code is in my website. <script> function displayForm(){ var element = document.getElementById("story-form"); if (element.style.display === none) { element.style.display = block; } else { element.style.display = none; } } </script> <button id="form-button" class="link-button" onclick=displayForm()>Edit</button> <div id="story-form" style="display:none;"> <form method="POST"> {% csrf_token %} {{ story_form.content }} {{ story_form.errors }} <button class="normal-button" type="submit">Submit</button> </form> </div> However, when I click the button with the id 'form-button', the displayForm() function is not being executed. Is there a problem with the code? Thanks in advance. -
Braintree - Why is only the default card being used for starting a subscription?
I am trying to understand how to give an option for the user to choose a non-default payment method / card for their subscription. Please see image below: I have two cards. The Visa is the default payment card. But if the user chooses the MasterCard (not default), only the default payment is used to start a subscription. I am using a payment nonce to start a subscription. The customer is saved in a different view and their payment methods are validated. result = braintree_gateway.subscription.create({ 'payment_method_nonce': payment_nonce, 'plan_id': tier_chosen, 'merchant_account_id': settings.BRAINTREE_MERCHANT_ACCOUNT_ID }) Thank you for the help! -
Why image is not getting saved in media directory in django?
I am trying to save the image in media/images directory and have done each and every neccosry step which is described below. But after all, I am not getting the image in my directory please someone guide me where is the problem. Thank You. Models.py from django.db import models # Create your models here. class students(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) fathername = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) state = models.CharField(max_length=50) zip = models.IntegerField(blank=True) address = models.CharField(max_length=100) contact =models.CharField(max_length=20) photo = models.ImageField(upload_to='images/', height_field=None, width_field=None, max_length=None) urls.py from django.urls import path, include from home import views from django.contrib import admin from home import StudentViews from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path("", views.index, name="index"), path("Add_Student", views.Add_Student, name="Add_Student"), path("display_students", views.Display_Student, name="display_students"), path("<int:id>", views.student_profile, name="student_profile"), #path("student/<int:id>/view", views.student_profile, name="student_profile"), path("Student_Home", StudentViews.StudentHome, name="Student_Home") ] #this line is for media urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py In settings.py, I added the following lines of code. MEDIA_ROOT= os.path.join(BASE_DIR, 'media/images') MEDIA_URL= "/images/" My Directory Student_Management_System home media/images templates static Note: I have already installed Pillow. -
Django how to change where uploaded file is saved
After uploading a file, Django creates a copy of this in the project app folder. I want to be able to tell Django to store this copy in another directory. How do I do that? Thanks. -
How to return Django model in a url?
I would like my Django Model to be accessible via http://localhost:8000/teams models.py: from typing import Any from django.db import models class Team(models.Model): top_id = models.CharField(max_length=20, unique = True) def __str__(self): return self.top_id urls.py: from django.urls import path from backend import views,models urlpatterns = [ path("teams/", models.Team, name="teams"), path("", views.home, name = "home"), ] I know that object has no attribute 'get'. How can I set it up? I tried getattribute but doesn't seem to work. I want to have a url like that so I can later on download the model via axios in my react app. -
Reduce the number of the connections to the authentication server
We implemented a middleware in Django to authenticate users using Keycloak, A micro-service Authentication Server for single sign-on solutions. while this works totally fine, but with really bad performance. For every request, a new OpenIDConnection need to be instantiated and talk to the remote server to validate the JWT token posted from the frontend, any ideas of how to improve, Thanks! BTW, we didn't use the built-in auth/session framework. class MiddleWare: def __call__(self, *args): conn = KeyClockConnection() validate_token() ... -
Searching foreign key field in django
I have been trying to build a search functionality in my app but i have stuck on querying for the foreign key field, as it doesn't return anything and the code shows no error. Below is my code. forms.py class StockSearchForm(forms.ModelForm): class Meta: model = Stock fields = ['category', 'item_name'] My view where i implemented the search views.py def list_items(request): header = 'List of items' form = StockSearchForm(request.POST or None) queryset = Stock.objects.all() context = { "form": form, "header": header, "queryset": queryset, } #Searching an item and category if request.method == 'POST': queryset = Stock.objects.filter(category__name__icontains=form['category'].value(), item_name__icontains=form['item_name'].value() ) context = { "form": form, "header": header, "queryset": queryset, } return render(request, "list_items.html", context) My models are as follows. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.name class Stock(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) #category = models.CharField(max_length=50, blank=True, null=True) item_name = models.CharField(max_length=50, blank=True, null=True) quantity = models.IntegerField(default='0', blank=True, null=True) receive_quantity = models.IntegerField(default='0', blank=True, null=True) receive_by = models.CharField(max_length=50, blank=True, null=True) issue_quantity = models.IntegerField(default='0', blank=True, null=True) issue_by = models.CharField(max_length=50, blank=True, null=True) issue_to = models.CharField(max_length=50, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) created_by = models.CharField(max_length=50, blank=True, null=True) reorder_level = models.IntegerField(default='0', blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=False, auto_now=True) last_updated = models.DateTimeField(auto_now_add=True, … -
Django Celery Beat does not running tasks on time
I'm using Django celery beats for my project and there is a problem in beat intervals. I setup a task to run every 1 minute. But the celery run this task like every 3 minutes! **:19 **:22 **:25 what is the problem? -
How to Set default value in 1:m relation, foreign key to user_auth_model in Django
I want to set Default value in my table, which must be the primary key of the admin of user_auth_model , But its showing me this error class department(models.Model): dept_id = models.AutoField(primary_key=True) dept_name = models.CharField(max_length=100) adid = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, null=False, default='admin') def __str__(self): return self.dept_name Here is the Error when i save it ValueError: invalid literal for int() with base 10: 'admin' -
How do I use Sessions with Custom User Model using Django REST Framework?
I am currently working on a project which involves using Django solely for Back-end API endpoints using class-based views to authenticate and serve database content to users on the Front-end. class UserLogin(APIView): # User Login def post(self, request, format=None): print(request) try: User_Cred.objects.get(username=request.data['username'], password=request.data['password']) # Retrieves user record pass # TEMPORARY except User_Cred.DoesNotExist: # If User Record does not exist, raise Http404 Right now, I'm trying to figure out how to implement sessions for user authentication. I know that Django has some sort of integration with sessions. However, I am not using Django's default user model but a custom one instead (see below). class Users(models.Model): username = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) def __str__(self): return self.username Is there any way I can use my custom user model for session authentication? Thanks in advance. -
Django: How to submit the form and receive the result on the same page without reloading the page
I am working in django where I submit the input data and receive the manipulated result on the same page. Whenever I submit the form, the page reloads. I want to receive the output data, which is manipulted in the background, on the same page without reloading the page. The model.py file is like this: from django.db import models from django.urls import reverse # Create your models here. class BFS(models.Model): description = models.TextField(blank=True, null=True) The views.py file is like this; from django.shortcuts import render, get_object_or_404, redirect from .forms import BFSForm from .models import BFS from .ml import Maze # def product_create_view(request): def bfs_view(request): form = BFSForm(request.POST or None) if form.is_valid(): form.save() form = BFSForm() try: image_url_info = None num_states_explored = None final_solution = None text_file = open("BFS\outputs\maze.txt", "w") field_name = 'description' input_value = BFS.objects.latest('id') field_object = BFS._meta.get_field(field_name) field_value = field_object.value_from_object(input_value) field_string_value = str(field_value).split("\n") text_file.writelines(field_string_value) text_file.close() m = Maze("BFS\outputs\maze.txt") print("Solving...") m.solve() m.output_image("BFS\outputs\maze.png", show_explored=True) m.output_image("static/search/bfs/maze.png", show_explored=True) image_url_info = "/../../../static/search/bfs/maze.png" num_states_explored = m.num_explored final_solution = str(''.join(m.end_result)) except: print("BFS ERROR: Error in the try session of BFS in view.py") context = { 'form': form, 'image_url': image_url_info, 'states_explored': num_states_explored, 'solution': final_solution } return render(request, "BFS/bfs.html", context) The BFS app urls.py file is like this: from … -
Is there a function that is called when you visit a view in django
is there a function that is called when a user visits a view (specifically a DetailView) in django. I am trying to count the number of views a particular page has (like StackOverflow), and I want to know if there is a function that I can utilise. If this is useful, here is the DetailView: class DetailQuestionView(DetailView): model = Question template_name = 'questions/questions-part/question-detail.html' -
Communication between a python script and Django REST API
I have created a Django REST API which accepts a image file from user. The image file has to be fed into a python script as input for the python program to run. The python program gives out 3 variable values in return. The result should come to the Django Rest API. I am not able to connect the Django REST API and the python script. Are there any functions/methods available for this? -
Deploy Multiple Apps Under a Single GitHub Repository - Django + React
I have built my website in 1 repository, Django and react I realized later on this is not a very common structure, and I'm stuck with deploying, How and where I can deploy my website where I have Django and React in 1 repository? this is my project structure - backend ( all Django stuff ) - frontend ( all react stuff ) PortfolioWebsite |___PortfolioWebsite | ____ backend | └── All backend stuff (views..etc) | ____ frontend | └── all react stuff |___PortfolioWebsite └── settings.py etc.. is it possible to deploy this and keep updating my code as I usually do in my localhost, without changing the structure? -
Django return a json from a pandas dataframe not correctly formatted
In my django project i call through an url a function that return a json from a pandas Dataset: @csrf_exempt def calc_q(request, c_id): start_d = datetime.date(2021, 6, 22) end_d = datetime.date(2021, 6, 29) v_id = 17 q_time ="15min" d = {"[": "", "]": "", ",": ""} var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), var_id_id=v_id, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", "var_val", "var_val_conv" ) df = pd.DataFrame(list(var_results)) df['id_res__read_date'] = pd.to_datetime(df['id_res__read_date']) df = df.set_index('id_res__read_date') df_15 = df.resample(q_time)['var_val_conv'].agg(['first','last']) print(df_15) df_15_json = df.resample(q_time)['var_val_conv'].agg(['first','last']).to_json(orient='records') return JsonResponse(json.loads(df_15_json), safe = False) well, when i run my function at 127.0.0.0:8000/pd/17 i get my json but is different between original pandas dataset: First in json as node i have a number and i would datetime as in pandas dataframe Second in pandas values are float number, in json i get int, how cani have even in json nodes with datetime and float for results? So many thanks in advance -
Can't not access static files while deploying Django app with apache2 load balancer
I'm trying to deploy a couple of apps developed in Django. Initially, I deployed the apps on a single server and everything worked smoothly. Now I'm trying to implement the site using load balancing using Apache2 load balance module. The problem is that when redirecting the traffic to the different sites, I get correctly to each site, but the static files are not accessible. I tried any trick I found through Google without success. I'm using Apache 2.4 and Gunicorn 20.1.0 (as the backend). The apps were developed with Django 3.1.1. Those are my apache config for the load balancer and for the servers: Load Balancer (apache2.4) <IfModule mod_ssl.c> <VirtualHost *:443> ServerName example.com ProxyRequests off <Proxy balancer://cluster> BalancerMember https://site1.example.com route=192-168-10-10 BalancerMember https://site2.example.com route=192-168-10-15 Order Deny,Allow Deny from none Allow from all ProxySet lbmethod=byrequests </Proxy> <Location /balancer-manager> SetHandler balancer-manager Order Deny,Allow Allow from all </Location> ProxyPreserveHost On ProxyPass /balancer-manager ! ProxyPass / balancer://cluster ProxyPassReverse / balancer://cluster SSLProxyEngine on SSLProxyVerify none SSLProxyCheckPeerCN off SSLProxyCheckPeerName off SSLProxyCheckPeerExpire off SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf SSLProxyCACertificateFile /etc/ssl/certs/lb_clients_certs.pem </VirtualHost> </IfModule> Server1 <VirtualHost *:443> ServerName example.com ServerAlias site1.example.com ServerAdmin admin@example.com SSLEngine on SSLProxyEngine On SSLProxyCheckPeerCN on SSLProxyCheckPeerExpire on ProxyRequests On ProxyPass /static/ ! Alias /static/ /var/www/myapp/static/ … -
why is the Django-atom package not working in my atom editor?
I installed the Django-atom package in atom but it doesn't seem to work since code doesn't autocomplete when I write the abbreviations. can someone please help me fix this? -
Django - Reading from Oracle database and writing to SQLite
I have configured settings.py already to have two databases: an existing Oracle database, and SQLite. I am new to Django, so I hope someone can give me a detailed answer. I want to create an app that takes specifc data from the existing Oracle database. Let us say I want to access the Oracle table called STUDENTS that has three columns: ID, NAME, and GRADE. I want to take the grades of each student and calculate the GPA of each student. Then I want to insert the GPA as a property of a new table (RESULTS) with columns: ID, NAME, GPA. But I want to store RESULTS table in the SQLite database. So I am using Oracle for reading, and SQLite for writing the new table. How can this be done in Django? -
python django global-ish class instance
Word of notice: I'm just starting my first steps with django, or, whatsover, web framework design. I'm using django rest framework, having three relevant endpoints /app/ManualInput Receives params and generates a single random.randint(0,100) /app/FileUploadAPI Receives a csv file and generates a single random.randint(0,100) per row in the csv /app/RetrainAI Retrains the Artificial Intelligence blackbox (it changes it: somehow like resetting the random seed) Now, i'd like to use a class instance that encapsulates the random.randint(0,100) for further refactorization, keeping in mind that two endpoints (classes) shall read from that class' instance and one endpoint (app/RetrainAI) will write to that class' instance. I'd like to set up a robust archetype, such as, for example, avoiding session data (because, if I'm not wrong, it would hardly work with load balancers). What is the best way to achieve my needs? Using global variable (class instance) in views.py? Is this a bad design? Thank you SO much! -
How to search in Django by giving condition
I have a table in db which look like this I need to search by Rule No and store the search string which is Epic="DevOps" AND Desc = "desc1" variable in a variable. note: i gave example for Rule no 1. for all the rule i have to search and store that in a variable Here's my model for Rule table: class assignmentRule(models.Model): Developer = models.ForeignKey(developer, on_delete=models.CASCADE) Jira_Column = models.CharField(max_length=100, blank=True) RelationalOperators= models.CharField(max_length=100) Jira_Value = models.CharField(max_length=500) LogicalOperator = models.CharField(max_length=30) Rule_No = models.CharField(max_length=30) here my developer table: class developer(models.Model): Developer_Name = models.CharField(max_length=100, unique=True) Role = models.CharField(max_length=500) Level = models.CharField(max_length=30) Expertise = models.CharField(max_length=200) Availability_Hours = models.CharField(max_length=500) def __str__(self): return self.Developer_Name Anyone guide me how to do that in django? and what to write in view to achieve this? -
Getting ODBC error in remote server, but localhost works - Django-mssql-backend
I'm deploying a Django app in IIS, but I'm getting the following error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') my settings.py has the following: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DatabaseName', 'HOST': 'HOSTNAME', 'USER': 'username', 'PASSWORD': 'password', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'collation': 'SQL_Latin1_General_CP1_CI_AS', 'SERVER': 'Hostname', 'DATABASE': 'DatabaseName', } } } with this configuratio it works when I run it in my dev environment, but when I move it to deploy it doesn't work, not even when I do a manage.py runserver I have installed the following packages: django django-filter django-msssql-backend pyodbc how can I troubleshoot? in my dev enviroment connects to the same database and server, but in the deployed location it just gives the error when trying to do runserver command. I'm connecting to a Sql server version: "Microsoft SQL Server 2014 - 12.0.2548.0 (X64)" I have Django 3.2.4 Python 3.9.5 Django-mssql-backend 2.8.1 -
Adding m2m fileds based on selected ones using
I'm trying to convert the country 'Latam' or 'Europe' to a list of countries and mantain that as a country also. So, when you select Latam in the list of countries the result in that m2m will be: [latam, Argentina, Chile, Peru, etc.] The Database is build that way... I know is better to split it Regions and Countries but I can't change it right now. This is the approuch I made. I think this is not the way to do it but maybe helps you understand the way it's build. LATAM = [1, 4, 24] class PromoManagement(models.Model): [...] house_id = models.CharField(max_length=6) original_title = models.CharField(max_length=150, blank=True, null=True) country = models.ManyToManyField(Country) [...] def save(self, *args, **kwargs): self.original_title = get_orignal_title(self.house_id) super().save(*args, **kwargs) def region_check(sender, instance, action, **kwargs): if action == 'post_add' or action == 'post_remove': for country in instance.country.all(): if country.name == 'Latam': for id in LATAM: instance.country.add(code) m2m_changed.connect(region_check, sender=PromoManagement.country.through) -
How to catch API call errors in pyhton/Django?
I have a Django app and a workflow like this in my views.py: my front end makes a call to my back end which uses the params received from front end to make an API call to an external API. I map the response from the external API to my serializer and check if the serializer is valid before saving the response to database. What I need help with is how to properly check for the responses from the external API and catch any errors getting from there? Can I just use try/except? At the moment I don't know about their exact responses but that is something I can clarify later. This is my class from views.py: class Example(generics.ListCreateAPIView): permission_classes = (AllowAny,) serializer_class = ExampleSerializer def post(self, request, format=None): pin = request.data['pin'] id = str(uuid.uuid4()) post_obj = {'pin': pin, 'id': id} data = requests.post(url, data=json.dumps(post_obj)) json_result = data.json() serializer = ExampleSerializer(data=json_result['data']) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django file_resubmit doesn't work in a templates view
So I have the problem where for a form that has an ImageField, (rendered using forms.py in Django) whenever the validation error comes up, maybe due to miss matching passwords etc. the ImageField get cleared. After some googling, I found a module called file_resubmit . This seems to have worked well for many people however for some reason it doesn't work for me... Docs of file_resubmit I did as their docs said but doesn't seem to work for me. I'm my settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', . . 'file_resubmit', ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', }, "file_resubmit": { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', "LOCATION": '/tmp/file_resubmit' } } In my forms.py... from file_resubmit.admin import AdminResubmitImageWidget class DriverRegisterForm(forms.ModelForm): mobile = forms.CharField(min_length=10) date_of_birth = forms.DateField(widget=forms.TextInput(attrs={'autocomplete': 'off'}), help_text="You need to be a minimum age of 18 to register with us") gender = forms.ChoiceField(choices=[("M","Male"), ("F", "Female")]) district = forms.ChoiceField(choices=CITY) nic_number = forms.CharField(label="NIC number", min_length=10) license = forms.ImageField(label="License picture") your_picture = forms.ImageField(help_text="A picture of yourself so that we know who you are") class Meta: model = ProfileDriver fields = ('mobile', 'gender', 'district', 'nic_number', 'license', 'date_of_birth', 'your_picture') widgets = { "license":AdminResubmitImageWidget, "your_picture":AdminResubmitImageWidget, } And just in case my models.py.. class ProfileDriver (models.Model): … -
How to filter by a list in Django REST Framework?
Suppose I have a model called X, X contains a field called Ys, a many-to-many field for a class Y. If I have a list of multiple instances of the model Y, how to filter for Xs that have the field Ys that is a superset of my list? Example: I have 3 X objects here: x1.Ys = [y1, y3, y4] x2.Ys = [y1, y2, y3] x3.Ys = [y1, y2] items_list: [y1, y2] I want to write X.objects.filter(xxx=items_list) and get x2, and x3 but not x1. What should I write in place of xxx?