Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I join two tables in Django ORM?
I am a beginner in Django and I know this question has alredy been asked, but I've tried every possible solution from previous answers and it still doesn't work. I can't figure out what I'm doing wrong. The thing is my view currently returns all the fields of the Grade table, but I need it to return all of those fields plus the "name" field which is in the Student table, by joining the two tables. I read that Django should do it automatically as long as I use ForeignKey, which I did, but it actually doesn't work. What am I doing wrong? I'm sorry if it's a noob question and if the solution is really obvious, I'm still trying to learn how Django works. app/models.py class Student(models.Model): id = models.IntegerField(primary_key=True, default=0) name = models.CharField(max_length=50) class Grade(models.Model): subject = models.CharField(max_length=50) grade = models.IntegerField(default=0) student = models.ForeignKey(Student, on_delete=models.CASCADE) app/serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('id', 'name') class GradeSerializer(serializers.ModelSerializer): class Meta: model = Grade fields = ('subject', 'grade', 'student') app/views.py class StudentView(viewsets.ModelViewSet): serializer_class = StudentSerializer queryset = Student.objects.all() class GradeView(viewsets.ModelViewSet): serializer_class = GradeSerializer queryset = Grade.objects.all().select_related("student") filterset_fields = ('student') -
How to create and zip multiple files together and download them using Django and Python 3
In my django app I create two text files and I want them to download automatically when a form is submitted. I believe that in order to do this I need to zip the files together, and then download the zip file. I am using the zipfile module to do this. Here is my code in the views.py file. with open('file1.txt', 'w') as file_1: numbers = ['1', '2', '3'] for num in numbers: file_1.write(num) file_2.write('\n') with open('file2.txt', 'w') as file_2: letters = ['A', 'B', 'C'] for letter in letters: file_1.write(letter) file_2.write('\n') comp_file = ZipFile('My_Files.zip', 'w') comp_file.write('file1.txt', compress_type=zipfile.ZIP_DEFLATED) comp_file.write('file2.txt', compress_type=zipfile.ZIP_DEFLATED) comp_file.close() return HttpResponse(content_type='application/zip', headers={'Content-Disposition': 'attachment; filename="My_Files.zip"'}) My expected output would be a zip file that could be extracted to contain the file1.txt and file2.txt. However, the output I actually get is a zip file that can't be extracted because it is empty. Also, this method actually creates all of the files in my working directory, which I don't really want to do. Does anyone know how I can do this without actually saving the files in my own directory? My current plan is to just delete the files after they are downloaded by the user. Thanks! -
How to return a file in django
I have a django app through which I would like to serve an index.html file. This html file isn't in default django template, rather I have the index.html in a react build folder. I don't want to render the template, rather I want to send it. The render method isn't working, and I don't know if there is any django method that can serve the file. What I want to accomplish can be done using res.sendFile() in expressjs. def home(request): return FileResponse(request, 'home/home.html') The FileResponse method isn't working here. -
Did you forget to register or load this tag? Using Django
I dont get it, if i remove the last im not getting this error, here's my HTML, i know im not closing a "if" tag correctly or something, the only solution for me is to remove the last last {% if request.get_full_path != "/addAssest/" and request.user.is_authenticated %} <div class="sidebar" style="height: 35%"> <div class="sidebar-wrapper"> <div class="logo"> <a target="_blank" href="https://www.creative-tim.com/product/black-dashboard-django" class="simple-text logo-mini" > CC </a> <a target="_blank" href="https://www.creative-tim.com/product/black-dashboard-django" class="simple-text logo-normal" > Crypto Castle </a> </div> <ul class="nav"> <li class="{% if 'index' in segment %} active {% endif %}"> <a href="/"> <i class="tim-icons icon-chart-pie-36"></i> <p>Dashboard</p> </a> </li> <li class="{% if 'page-user' in segment %} active {% endif %}"> <a href="{% url 'profilePage' %}"> <i class="tim-icons icon-single-02"></i> <p>User Profile</p> </a> </li> <li class="{% if 'logout' in segment %} active {% endif %}"> <a href="{% url 'logout' %}"> <i class="tim-icons icon-user-run"></i> <p>Logout</p> </a> </li> </ul> </div> </div> {% endif %} -
How to access array of python in JavaScript from Views in Django?
I am writing this array in Views in Django: address=["Main Address"] and passing in dic. and accessing in Java Script in HTML page: address={{context.lat_long.address}} addMarker(address,{lat: property_lat, lng: property_long}, "red"); But it is not working at all -
Django imports from . import views
from . import views python Django framework command that i don't understand what is . in there . is it like * means all ? or have another meaning ? -
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!