Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I clear path from history in Django?
I want to clear all path from history and redirect to new path. If is there any way to do this please provide suitable solutions. -
from an address get the altitude and longitude in django rest, I am new with this python
I am designing an api with django, I need to convert many directions to latitude and longitude, I don't know where to start I am something new in this -
Importing view is showing error from app in Django?
i am trying to create simple hello world page from django in pycharm and from urls.py file of my app "first_app" trying to import views. But when i type "from first_app import views" in urls.py, pycharm is underlining it as an error but my hello world page is still showing. Earlier it was giving some error. I am attaching screenshot of it. I have also mentioned first_app in installed_apps in settings.py file of the project. If any one knows about it please tell me what the issue is here. -
How do I change a parameter dynamically?
I have a simple e-commerce on Django. Can you show how to implement a dynamic price change depending on the number of items? For example: when adding to cart from 1 to 10 items the cost is 1, from 11 to 20 the cost is 0.9 and so on. Thank you very much! -
Django set relation between two models
I want to save my custom Model as Field in another Model as shown below. It's normal when I create and work with them during one session. But when I start a new session Django loads the Game model with player1 and player2 that have a null id. Here example of my code class Player(models.Model): name = models.CharField(max_length=40) class Game(models.Model): player1 = Player() player2 = Player() -
How to install python package from the project if requirememt.txt is not exist
How to install python package from the project if requirememt.txt is not exist like: In node.js we run npm install command and all npm package install. like that, I want a python package installed from the project. If any way to do that? -
Getting error when setting up HyperlinkedModelSerializer
I keep getting the error Could not resolve URL for hyperlinked relationship using view name "departments-api". You may have failed to include the related model in your API, or incorrectly configured the "lookup_field" attribute on this field. I am trying to link this but am not sure where I am going wrong here. I can get to the '/api/' page but can not click on either of the links to take me to the corresponding page. I believe I may need to change around my serializer hyperlinkedidentityfield or my api_root function but am not sure where to start. Models.py class Department(models.Model): name = models.CharField(max_length=300) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=300) # delete dept == delete teacher department = models.ForeignKey(Department, on_delete=models.CASCADE) tenure = models.BooleanField() def __str__(self): return f'{self.name} teaches {self.department}' def get_absolute_url(self): return reverse('teacher-detail', kwargs={'pk': self.pk}) serializers.py class TeacherSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="teachers-api") class Meta: model = Teacher fields = '__all__' class DepartmentSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name="departments-api") class Meta: model = Department fields = ['url', 'name'] urls.py urlpatterns = [ path('api/', api_root), path('api/teachers/', TeacherAPIList.as_view(), name='teachers-api'), path('api/teachers/<int:pk>/', TeacherAPIDetail.as_view()), path('api/departments/', DepartmentAPIList.as_view(), name='departments-api'), path('api/users/', UserAPIList.as_view()), path('api/users/<int:pk>/', UserAPIDetail.as_view()), ] views.py @api_view(['GET']) def api_root(request, format=None): return Response({ 'teachers': reverse('teachers-api', request=request, format=format), 'departments': reverse('departments-api', request=request, … -
Group by query in Django ORM
I an having a confusion on how to write a django query to get my data. I have 2 tables 'ticket' and 'ticket_details'. Below is the schema for them. Ticket(id, name, type, user) TicketDetails(ticket_id, message, created_time) Note: Multiple message can be associated to one ticket id. And ticket_id is a foreign key to the Ticket table. I would like to fetch all the columns from both the table where only the latest message from the TicketDetails table should be picked for a particular ticket id. Thanks in advance -
REST Django - How to grab recently created Object
I use a post method to create an instance of the class called Project. When the Post method is done, I want to get the ID of the recently created Project-object. How would I do this? my model looks like this: models.py class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, null = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'projects' def __str__(self): return self.name and my view is this: views.py: class ProjectView( APIView, ): def post(self, request): serializer = ProjectSerializer(data = request.data) if serializer.is_valid(): serializer.save() user = request.user return Response({"status": "success", "data": serializer.data}, status = 200) else: return Response({"status": "error", "data": serializer.errors}, status = 400) -
How does Django handle multiple CRUD actions on same table? (at same time)
I am curious about how Django handles multiple actions to be performed on same table at the same time. I'm using Postgresql with Django ORM. Does it have locking mechanism to handle such scenario? If yes then is it by default or any parameter must be added? -
TypeError when querying in bulk - DjangoPhoneNumber
In my application, I'm using the django-phonenumber-field package to store the user phone number. When I try to query in bulk using a list of phone numbers, the following error appears: TypeError: keys must be str, int, float, bool or None, not PhoneNumber This StackOverflow post would help if I was using pure python, but instead I am doing the following Django query: registered_users = User.objects.in_bulk( data["phone_number"], field_name="phone_number" ) The data["phone_number"] is simply a list containing strings. So, it seems I should pass the field differently, but I have no idea how to convert the field to a valid format for Python. Any ideas? -
Best practice for changing certain variables if published to a branch
I work on a custom documentation management system with Django. Currently there is a productive envoirment on an IIS + Hyper-V with a database, let's call it productiveDB. New features are implemented locally in different branches, using another database, let's call this one stagingDB. When I work locally on a new branch I have to adjust the database configuration and credentials from productiveDB to stagingDB in my settings.py - furthermore I set the DEBUG Mode to True. When I commit my changes and merge into master, I sometimes forget to adjust the settings and this is where my question begins: What is the best practice to handle this 'inattention'? Sure, I could keep the local settings adjusted for the staging envoirment and vice versa for the productive settings but here and then I have to add new settings to the aformentioned file and therefore I would have to commit the edited settings.py. Is there a 'build in' way in GitLab or git to mark specific variables and change them according to the branch they are under? Like: if branch=master then set DEBUG=FALSE, DATABASE=productiveDB before while the CI/CD pipeline is running or do I have to stick to a custom script? -
I tried to install django using pip install django, later i get error to upgrade pip, i done upgrade pip, but still got error as below i mentioned
WARNING: The script sqlformat.exe is installed in 'C:\Users\Easwar Sai Prasad\AppData\Roaming\Python\Python38\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The script django-admin.exe is installed in 'C:\Users\Easwar Sai Prasad\AppData\Roaming\Python\Python38\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. -
Why does reset_sequences=True cause pytest to actually flush differences to the test_database?
I'm running my django tests using pytest and I saw some strange behaviour. To find out what happened I put a breakpoint() in my tests and then psql'ed into my postgres database to see what the status was. To my surprise all database tables were empty even though when using MyModel.objects.all().count() gave about 500 (test) records. I looked up the documentation and fiddled around a bit, and then found out that when I change @pytest.mark.django_db at the top of my tests to @pytest.mark.django_db(reset_sequences=True) the counts I see when psql'ing into postgres show the same as what I get from doing a count using the django orm. To add to the confusion, the documentation actually says that reset_sequences=True Must be used together with transaction=True to have an effect. Why does setting reset_sequences to True have the effect that doing a count using psql has the same effect as doing a count using the django ORM? -
How to connect different apps in a server? [closed]
We have multiple apps in different languages on a single python server that needs to be connected together in realtime, my friend suggest using a TCP connection for them to work together, is it the only/right choice? will there be some sort of problems in the future. Is there really no way of connection different programming languages together without using RMI/Docker/Vagrant? -
How to toggle SVG from javascript or jquery , add and removed button?
This is javascript to make it do what you want to do? See //toggle line SVG to get the idea how it works i am using Jquery No more detail StACK overFLOw why do you asking me stupid $(document).ready(function() { var csrfToken = $("input[name=csrfmiddlewaretoken]").val(); console.log("Document.ready"); $("a.tag__follow").click(function (e) { e.preventDefault(); var tag_id = $(this).data('id'); console.log(tag_id); $.post( $(this).data("url"), { csrfmiddlewaretoken: csrfToken, id: $(this).data("id"), action: $(this).data("action"), }, function (data) { if (data['status']=='ok') { var previous_action = $('a.tag__follow.'+tag_id).data('action'); // toggle data-action $('a.tag__follow.'+tag_id).data('action', previous_action == 'follow' ? 'unfollow' : 'follow'); // toggle link SVG $('a.tag__follow.'+tag_id).html(previous_action == 'follow' ? '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="24" height="24" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path d="M23 13.482L15.508 21L12 17.4l1.412-1.388l2.106 2.188l6.094-6.094L23 13.482zm-7.455 1.862L20 10.889V2H2v14c0 1.1.9 2 2 2h4.538l4.913-4.832l2.094 2.176zM8 13H4v-1h4v1zm3-2H4v-1h7v1zm0-2H4V8h7v1zm7-3H4V4h14v2z" fill="currentColor"/></svg>' : '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="24" height="24" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path d="M23 16v2h-3v3h-2v-3h-3v-2h3v-3h2v3h3zM20 2v9h-4v3h-3v4H4c-1.1 0-2-.9-2-2V2h18zM8 13v-1H4v1h4zm3-3H4v1h7v-1zm0-2H4v1h7V8zm7-4H4v2h14V4z" fill="currentColor"/></svg>'); // toggle class $('a.tag__follow.'+tag_id).toggleClass(previous_action == 'follow' || previous_action == 'unfollow' ? 'tag__following': ''); } } ) }) }) -
How to create a service from a function?
I want to create a service using Django Rest API. I have a function. The result of this function should return 2 values and I should return these values in JSON API format. The function will work like this. I will receive the features_list as a parameter and I will use it to create a result and display it as a service in json format in def prediction function. I created a sample API (I guess) it is class PredictionSet in my views but I actually want to make service the def prediction function in my views. I cannot understand how to apply it. I am so confused. Any help would be appreciated. models.py class Liquidity(models.Model): pred_y = models.CharField(max_length=600) score = models.FloatField() views.py class PredictionSet(viewsets.ModelViewSet): queryset = Liquidity.objects.all() serializer_class = LiquiditySerializer def prediction(request, features_list): filename = config.FINAL_MODEL_PATH classifier = pickle.load(open(filename, 'rb')) scale_file = config.SCALER_PATH scaler = pickle.load(open(scale_file, 'rb')) sample = np.array(features_list).reshape(1, -1) sample_scaled = scaler.transform(sample) pred_y = classifier.predict(sample_scaled) prob_y = classifier.predict_proba(sample_scaled) if prob_y[0][1] < 0.5: score = 0 elif prob_y[0][1] <= 0.69: score = 1 else: score = 2 pred_y = pred_y[0] prediction_obj = Liquidity.objects.get_or_create(pred_y=pred_y, score=score) prediction_result = prediction_obj.pred_y prediction_score = prediction_obj.score context = { 'prediction_result ': prediction_result, 'prediction_score ': … -
Can we write a single dockerfile for both front end and backend?
I've to dockerize a django react app. I wonder can we write a single dockerfile for both front end and back end instead of writing separate files and combining them at the end in docker compose? -
I want to insert a button in my table that shows expenses using javascript when the user searches someting in the searchfield
Here is my template html code :- <!---this table will show if the user has noting in the searchField---> <div class = "default-table" > <table class = "table table-stripped table-hover"> <!---table head---> <thead> <tr> <th>Amount ({{currency}})</th> <th>Category</th> <th>Description</th> <th>Date</th> <th></th> <!---this will hold the edit buttons for our expenses---> <th></th> <!---this will hold the delete buttons for our expenses---> </tr> </thead> <!---table body---> <tbody> <!---instead of looping through the expenses here we should loop through the page_obj which will give the number of expenses defined in the paginator class per page---> {% for expense in page_obj %} <tr> <td>{{expense.amount}}</td> <td>{{expense.category}}</td> <td>{{expense.description}}</td> <td>{{expense.date}}</td> <td><a href="{% url 'expense_edit' expense.id %}" class = "btn btn-primary">Edit</a></td><!---this will hold the edit buttons for our expenses---> <td><a href="{% url 'expense_delete' expense.id %}" class = "btn btn-danger">Delete</a></td><!---this will hold the edit buttons for our expenses---> </tr> {% endfor %} </tbody> </table> </div> <!---this table will show if the user tries to search expenses in the searchField---> <div class="table-output"> <table class = "table table-stripped table-hover"> <!---table head---> <thead> <tr> <th>Amount ({{currency}})</th> <th>Category</th> <th>Description</th> <th>Date</th> <th></th> <!---this will hold the edit buttons for our expenses---> <th></th> <!---this will hold the delete buttons for our expenses---> </tr> </thead> <!---table body---> … -
hosting django with angular on digitalocean with nginx
I have a Django-Angular project which I want to deploy on DigitalOcean with Nginx and I am successful in running the whole setup, but I have some doubts that I want to clear before finally proceeding with this solution. This is what I've done so far Currently, I've gunicorn.sock and gunicorn.service files to set up gunicorn and passed this file in Nginx's location block location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # this will proxy pass the request to gunicorn which is running django app } The Django project is running without any issue. For the angular project, I am using supervisor, inside /etc/supervisor/conf.d/my_angular_app.conf, I've set up configurations for angular app [program:my_angular_app] command=ng serve directory=/path/to/angular/project/ user=www-data autostart=true autorestart=true stdout_logfile=/path/to/angular/project/logs/angular.log redirect_stderr=true this starts the angular project on localhost:4200 Now, I've added another location block inside my Nginx file to proxy pass the requests to angular location / { include proxy_params; # this will pass the requests to angular project proxy_pass http://localhost:4200; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # this will proxy pass the request to gunicorn which is running django app } This whole setup is … -
How to save an async function fetchData() and insert it to chart.js?
My goal is to use json data as labels and data in my Chart.js piechart. I have a query which gets the data and converts it to Json in view.py: def get_data(request): filtered_transaction_query_by_user = Transaction.objects.filter(portfolio__user=request.user) total_transactions_by_user = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price') * Sum('number_of_coins'))).order_by('-total') data = list(total_transactions_by_user) return JsonResponse(data,safe=False) Resulting this at http://127.0.0.1:8000/get_data/: [{"coin__name": "Bitcoin", "total": "1220"}, {"coin__name": "Ripple", "total": "160"}] At piechart.html, I fetch it in < scripts >: async function fetchData() { const url = 'http://127.0.0.1:8000/get_data/'; const response = await fetch(url) // wait until the request has been completed const datapoints = await response.json(); console.log(datapoints); return datapoints;} Finally, I call the function, but I dont see how to insert the labels and the data into the piechart: fetchData() var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ['example','example2'], // insert here datasets: [{ data: [45,55], //insert here backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'], hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], -
Nginx can't find static files
o know that it is oftenn question. I have 2 servers with the same nginx config location /static/ { root /var/www/html; } real dicrectory for static is /var/www/html/static One server see the django static files, seconf write 404 and can't see that. I tried alias too. Any suggesions? -
Your URL pattern [<URLPattern> ] is invalid. DJANGO Urls.py file
I am getting this error ERRORS: app_1 | ?: (urls.E004) Your URL pattern [<URLPattern '^static/media/(?P.)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. app_1 | ?: (urls.E004) Your URL pattern [<URLPattern '^static/static/(?P.)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. I don't know why I am getting this error. I have correctly added everything in my url patterns urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/jobs/", include("jobs.urls")), path("api/v1/company/", include("company.urls")), ] if settings.DEBUG: urlpatterns.extend( [ static("/static/static/", document_root="/vol/web/static"), static("/static/media/", document_root="/vol/web/media"), path("__debug__/", include(debug_toolbar.urls)), ] ) -
How do change background color of entire page in bootstrap?
I wanted to change background color of entire page . I'm using bootstrap 5 starter pack and its elements. Please give me the right answer. -
Django-channels and Firefox connection issue
I am using django-channels as a sockets endpoint in django project, I developed a real time chat using django-channels, tested, deployed to Ubuntu on top of docker, and using NGINX as a web server, it is working pretty cool, did many tested. However one of my college lives in United Arab Emirates, when he tests the socket is not working with Firefox and Safari browsers, in console JS says: cant't establish a connection to the server at wss://site.com. We did cache cleaning in his browsers, still no luck Please note that: Other with other people in even in UAE, it working very fine :( I think it might be problem with my NGINX config, so here it is: upstream site_template_wsgi { server localhost:9002; } upstream site_template_asgi { server localhost:9003; } server { root /var/www/site_template; server_name site.com www.site.com; location / { proxy_redirect off; proxy_set_header host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://site_template_wsgi; } location /socket/ { proxy_pass http://site_template_asgi; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/site.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/site.com/privkey.pem; # managed by …