Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to make foreingkey object in django forms (like "+" in django admin)
im using django forms and i want to add like in django admin "+" for adding in form filed a foreign key object. I want the same as in django admin, you pushing +, then opens foreign key object form, filling foreign object fields, saving it, and object appears in main form field. How can i do this? (using django crispy forms) -
How to implement a Central Authentication Server in Django?
I am trying to implement a Authentication Server using Django which will be used only for user authentication. We have multiple services hosted on different subdomains like one.service.com, two.service.com, three.service.com etc. And we don't want our users to memorize/use different login credentials for each service. We want a system where user can authenticate themselves through the auth server and can access all the services of the subdomains. Just think about Google or Microsoft, we just need one login credential and then we can access all of their services. How can I implement this type of system for our services using Django ?? Note: We are primarily using JWTAuthentication for our servers. -
Django application deployed on AWS is quite slow
I have used AWS Elastic Beanstalk to deploy a Django project and I’m using a RDS PostgreSQL (size db.t2.micro) database from AWS. What I have noticed is that while testing the app locally (localhost) with the default sqlite3 the app is much faster than the deployed version that uses the PostgreSQL database from AWS/RDS. This may be something normal but I’m quite new working with AWS and RDS and I would like to know why this is happening and what can I do to make the application work as fast as it works locally. Thanks, -
How to query for an object that has specific number of foreignKey relations and has specific values in those foreinKey values in Django?
I am building a Django GraphQL API to use for a chat app. I have the following 2 models, one for Chat and one for chat members, which is tied in as a foreingKey:- class Chat(models.Model): name = models.CharField(max_length=100, blank=True, null=True) members = models.ManyToManyField(User, related_name="privateChats", through="ChatMember", through_fields=('chat', 'member'), blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class ChatMember(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.chat I have a certain method that is supposed to take in 2 user Ids and first it looks to check if an existing chat exists between these 2 members. If it exists, it returns that chat. If not then it creates a new chat for these 2 members and returns the newly created chat. The tricky part is where it tries to search if an existing chat exists. Because I'm using this same chat model for group chats, it is possible that it could return a group that also has these 2 members. So the condition to check if there is a one on one chat between these 2 members, it is to first check if the chat has only 2 members in it … -
nginx how can properly setting public domain names for Django apps with gunicorn
I have set up nginx for Djnago apps with gunicorn on ubuntu 20.04 by following this tutorial, and as result of this, the site works locally with local domain name. But after buying public domain name, I can not manage how to set up this public domain name with my nginx server. And I take this error on browsers: -
How to search in Django [closed]
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 Anyone guide me how to do that in django? 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 -
ImageField default upload_to directory changes
when I upload an image, it doesn't get saved to default upload_to directory (get_news_image). Instead it created a new directory (new) that has the name of the Model (News) and each image I add uploads there. I'm using class based views, are they automatically making an upload folder for my images?? On the left side in the bottom you can see my media folder: