Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Grouping the data financial year wise and month wise
I am developing a django restframework API to show data of the salary paid to employees financial Year wise and month wise sum. Something like below: [ "2019-20":{ "Apr":120012, "May":142566, "June":122223 #So on for every month }, "2020-21":{ "Apr":130019, "May":142526, "June":152221 #So on for every month } ] My models are class Months(Model): month_name = models.Charfield(max_length=3) class FinYear(Model): finyear_name = models.Charfield(max_length=7) class Employee(Model): name=models.Carfield(max_length=50) Class Salary(Model): fin_year=models.Foreignkey(FinYear, on_delete=medels.CASCADE) month=models.Foreignkey(Months, on_delete=medels.CASCADE) salary = models.Integerfield(max_length=8) employee_id=models.Foreignkey(Employee, on_delete=models.CASCADE) Any help will be highly appreciated. -
ViewSet and additional retrieve URL
I have a django model that I expose as a ViewSet. Now I want to add an additional URL where a single instance can be retrieved and custom actions can be executed. # models.py class MyModel(models.Model): id = models.AutoField(primary_key=True) third_party_service_id = models.StringField() # views.py class MyModelViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin): def retrieve(self, request, *args, **kwargs): if kwargs['pk'].isdigit(): return super(MyModelViewSet, self).retrieve(request, *args, **kwargs) else: query_third_party_service_id = self.request.query_params.get('third_party_service_id', None) if query_third_party_service_id is not None: try: instance = MyModel.objects.get(third_party_service_id=query_third_party_service_id) catch MyModel.DoesNotExist: raise Http404 return Response(self.get_serializer(instance).data) return Response(status=status.HTTP_404_NOT_FOUND) @action(methods=['post'], detail=True) def custom_action(self, request, *args, **kwargs): pass # urls.py router = routers.DefaultRouter() router.register(r'mymodels', MyModelViewSet) router.register(r'mythirdpartyservices/(?P<third_party_service_id>[0-9]+)', MyModelViewSet) My goal is to have http://localhost:8000/mymodels point at the entire ViewSet. Also I would like to lookup an individual model, by only knowing its third_party_id like follows http://localhost:8000/mythirdpartyservices/1337/ and also executing the custom action like follows http://localhost:8000/mythirdpartyservices/1337/custom_action/. The problem I have is that the second url returns an entire queryset, not just a single instance of the model. -
Get model field values from FK related objects
I've got a structure of FK related objects that looks somewhat like that: class Object3(models.Model): ... requirement = models.ManyToManyField(Requirement, blank=True) class Object2(models.Model): ... parent = models.ForeignKey(Object3, on_delete=models.CASCADE) requirement = models.ManyToManyField(Requirement, blank=True) class Object1(models.Model): ... parent = models.ForeignKey(Object2, on_delete=models.CASCADE) requirement = models.ManyToManyField(Requirement, blank=True) class Requirement(models.Model): ... All of those object have the same non-required field, which is a ManyToManyField, it's basically a requirement that can be set on either level of the structure. What I need to do is when I set the m2m field on the highest level of the structure, Object3, I need related Object2 and Object1 to set the m2m identically, same if I set it on Object2 instance, I need it to be set on the related Object1 instances. What is the most Django-ish way to achieve that? I hope my explanation is clear enough, I'll be more than happy to provide any more information. I've been pulling my hair out with this simple task, but I can't seem to come up with a good solution, hopefully with your help I'll be able to. -
Access django admin page behind Nginx
I am able to access all of my regular endpoints in my Django project, but I'm unable to access the /admin login page. Whenever I try to enter the url/admin I get redirected to my top-url, the same happens in Postman. I have the following Nginx file: location ~ /api { rewrite ^/api(.*)$ $1 break; include uwsgi_params; uwsgi_pass unix:/run/uwsgi/backend.sock; } location /static/ { root /home/m3csadmin/backend; } location / { try_files $uri $uri/ /index.html =404; } What am I missing? -
Django Rest Framework: How to Dynamically return subset of fields
I would like to filter by fields name and get back a subset instead of having back all my fields name. For example here I am filtering by id and name. It should return me only this two dimension in json format. I have found many solution on the site and I have done exactly the same as suggested but I don't have the expected result. Could you please help me ? my view: router = routers.DefaultRouter() urlpatterns = [ path('', include(router.urls)), path('edges/', edge_list), path('edges/<int:pk>/', edge_detail), path('network/<int:pk>/edges/', edges_of_a_network), ] Here a copy past example from https://www.django-rest-framework.org/api-guide/serializers/#example class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) My serializer class which I would like to filter fields. class EdgeSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer): source = serializers.SerializerMethodField(method_name='get_node_source') target = serializers.SerializerMethodField(method_name='get_node_target') road_type = serializers.SerializerMethodField( method_name='get_road_type_id') class Meta: model = Edge fields … -
Unable to make a "Get" call to a django app residing in a docker container from a flask app in another docker container
I am referring to the tutorial, https://www.youtube.com/watch?v=0iB5IPoTDts. At from 1:18:09 in the tutorial, I am supposed to implement this code below [Api call from a flask app in a docker container to a django app residing in another docker container][1] But I keep getting maximum retry error. [Error image][2] It seems like the get request is failing. I referred to the following link How to get the IP address of the docker host from inside a docker container, and tried solutions present in answer 1 and 2, but they give an error 400. I am quite novice in flask and django. Please help. Thanks in advance. [1]: https://i.stack.imgur.com/O0tZf.png [2]: https://i.stack.imgur.com/UozYE.png -
Pass a value to an api and return a specific object
I have created an api where #urls.py router = DefaultRouter() router.register('login', GetUserViewSet, basename='get_user') urlpatterns = [ path('', include(router.urls)), ] #views.py class GetUserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = GetProfileSerializer #serializers.py class GetProfileSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ('password', 'groups', 'user_permissions') The above code returns the list of users when I hit 'http://localhost:8000/api/login/' and the specific user when I hit 'http://localhost:8000/api/login/1/'. Here I want to pass the 'mobile_number' to the api and return the only user with the mobile number. I have achieved it by adding get_queryset() to the views as follows. #views.py class GetUserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = GetProfileSerializer def get_queryset(self): mobile_number = self.request.query_params.get('mobile_number') queryset = User.objects.filter(mobile_number=mobile_number) return queryset But the above code is returning the object in an array. I am following a common response format as given below { "status": true, "message": "Successfully registered your account.", "data": { "id": 1, "first_name": "User", "last_name": "U", "email": "user@gmail.com", "dial_code_id": "91", "mobile_number": "9876543211", } } and I am not able to achieve this with this get_queryset(). Please suggest me the best possible way to achieve this. -
Show a set of car models after the user chooses the car brand in Django forms
I am using Django 3.2 to make an uber clone and that when I want to allow the users to register with their vehicle I first want the user to be able to choose the car brand, and then afterwards choose the car model which is sorted according to the car brand. class Vehicle (models.Model): brand = models.CharField(max_length=60) model = models.CharField(max_length=60) vehicle_colour = models.CharField(choices=COLOURS, max_length=10) vehicle_number = models.CharField(max_length=8) I want to add some choices for the brand and model field, but I feel like I might need some javascript to intervene. Do you know any method that I could use to get this done? Your help is greatly appreciated. Thanks! -
Mpesa object has no attribute 'update'
I would like to update the first item in the database each time a user clicks on a button but I keep getting the error every time, any assistance would be appreciated, below is the snippet. Mpesa.objects.filter(Paid_user=self.request.user, Completed=False).first().update(Completed=True) -
how to create comment tree in django
I need a comment system so can reply a comment to any comment I know how to write models and views and my only problem is showing them in the template For example, maybe a group of comments are like this: comment comment comment comment comment comment comment comment comment comment How can I display this structure in the template? -
ValueError - The view didn't return an HttpResponse object. It returned None instead
My view currently returns an error of The view viajecenter.views.receive_payment didn't return an HttpResponse object. It returned None instead. I tried some of the solutions from other related posts here but of no luck. Here is my function in my views.py file: def receive_payment(request, account_code): template_name = 'receive-payment.html' def get_context_data(self, *args, **kwargs): user = self.request.user context = super(receive_payment, self).get_context_data(*args, **kwargs) account = get_object_or_404(Account, account_code=self.kwargs['account_code']) if user.is_assigned: puv = Puv.objects.get(assignment_id=user.assignment_id) locations = puv.route.locations.all().order_by('distance_from_base') context["account"] = account context["puv"] = puv context["locations"] = locations return render(request, self.template_name, context) else: return user and the corresponding url in urls.py file: from django.urls import path from . views import ..., receive_payment urlpatterns = [ ... path('receive-payment/<str:account_code>', receive_payment, name="receive-payment"), ] Thank you for lending me your time and answering my question :) -
How to send emails using RabbitMq and Django
I am new to RabbitMQ at the same time, if possible would someone also link me to a good tutorial for my task? -
How to update text area contents in django
Am trying to refresh a text area with data from a service that scans a bar code and logs the code. Am not sure what am doing wrong, I cant get the scanned data to appear on the text area. This is what I have done so far My camera stream for scanning the barcodes and logging to the console and to a list used_codes variable class CameraStream: used_codes = [] def __init__(self): self.camera = cv2.VideoCapture(int(0)) def get_frames(self): used_codes = self.used_codes while True: # Capture frame-by-frame success, frame = self.camera.read() if not success: break else: ret, buffer = cv2.imencode('.jpg', frame) # Add text on top of the barcode if there is a barcode in the stream using opencv # convert camera frame to numpy array color_image = np.asanyarray(frame) # decode numpy array to check if there is a barcode in color_image if decode(color_image): for code in decode(color_image): if code.data.decode('utf-8') not in used_codes: print('Approved. You can enter!') print(code.data.decode('utf-8')) used_codes.append(code.data.decode('utf-8')) elif code.data.decode('utf-8') in used_codes: print('Sorry, this code has been already used!') else: pass cv2.imshow('Testing-code-scan', frame) cv2.waitKey(1) return used_codes My Views getting the data from the used_codes variable and sending it to the view def detect(request): stream = CameraStream() success, frame = stream.camera.read() … -
How to Use Deep Learning model trained on GoogleColab in Django
I have Trained one text classification model using Jupyter notebook and saved model using Joblib which I easily use in django to predict ouput. Now I have trained one similar text classification on Google Colab but there am not able to use Joblib to save trained model. Also I have one doubt about how to use tokenizer used in google colab from server. If I want to predict I have to do some preprocessing on text x = ['this is a news'] x = tokenizer.texts_to_sequences(x) So, this tokenizer is fit on Trained dataset. Please let me know about this, how to save that model and use of it in django also how to preprocess the requested data. Thank You! -
Procfile gunicorn doesn't find module (Django)
My project structure looks like this git_root/ -django_project_root/ --core/ ---... ---settings.py ---wsgi.py ---... --app1/ --... Procfile ... So I have Procfile in git_root and wsgi in django_project/core/ My Procfile looks like that web: gunicorn --preload django_project.core.wsgi Heroku logs: ModuleNotFoundError: No module named 'core' P.S. Also tried next 2 things Tried putting Procfile in django_project folder. But it is not found when deploying. Created new repo and unwrapped django_project, so git_root is now django_project. And edited the Procfile to look like this web: gunicorn --preload core.wsgi and that worked. But i need it to work on initial repo. -
How can the data entered by a user get updated in the database in Django?
This is my html code for checkbox : <div class="col"> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Melody</label></div> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Rock</label></div> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Classical</label></div> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Jazz</label></div> <div class="form-check"><input class="form-check-input" type="checkbox" id="formCheck-1"><label class="form-check-label" for="formCheck-1" style="color:rgb(255,255,255);">Metal</label></div> </div> Views.py (I am very new to programming, so the code could be wrong) def Userregister(request): if request.method == 'POST': Name = request.POST['Name'] Melody = request.POST.getlist['Melody'] Rock = request.POST.getlist['Rock'] Jazz = request.POST.getlist['Jazz'] Classical = request.POST.getlist['Classical'] Metal = request.POST.getlist['Metal'] models.py from django.db import models class User(models.Model) : Name= models.CharField(max_length=100) Melody = models.BooleanField(default=False) Rock = models.BooleanField(default=False) Jazz = models.BooleanField(default=False) Classical = models.BooleanField(default=False) Metal = models.BooleanField(default=False) -
How do I Calculate interest on balance in days with django
How do I calculate the compound interest on balance? I want 3 percent of the amount in balance to be calculated and then automatically added to the running balance of every user that have a balance. What I meant is that the amount in running balance will be as the results of the calculation of 3 percent of the balance in user account. I want this calculation to be done consecutively every five days. Three percent interest of every amount in balance will be calculated in every 500 days. This calculation is continual and infinite from the last time it was calculated class UserAccount(models.Model): user =models.OneToOneField(User, related_name='account', on_delete=models.CASCADE,) balance =models.DecimalField(default=0 max_digits=12,decimal_places=2) running_balance =models.DecimalField(default=0 max_digits=12,decimal_places=2) interest_startdate =models.DateTimeField(auto_add=now) rate = models.IntegerChoices() days = models.IntegerField("number of days", default=0) def __str__(self): return str(self.balance) def get_interest_calculation_months(self): account = UserAccount.objects.get(balance__gt=0, pk=<something>) calc_interest = lambda value: value * useraccount.rate amount = useraccount.balance for i in xrange(12): interest = calc_interest(amount) amount += interest print 'days {}: {} ({} interest)'.format(i, amount, interest) running_balance +=interest A little confused right away. How do I get this to work The interest of all the balance in the userAccount should be calculated and then added to the user running balance This action's is … -
CouchDB user jwt authentication with python/django
Iam new to Software development and Iam implementing login page with couchdb and django, I want the authentication should be token based and I don't have any idea how to develop and I searched alot I didn't find perfect solution, I need ideas Pls help and Than you -
content is over lapping the navigation bar
I'm making the blog site with django I got a problem after adding navigation bar the problem is content of the web site is overlapping the navigation bar when I scroll down the page. Or if you know how add sticky navigation bar in another better way than this let me know.I usedw3 school web site to add this navigation bar .Anyway here is my code. {% extends "base.html" %} {% block content %} <style> body { font-family: "Roboto", sans-serif; font-size: 18px; background-color: #fdfdfd; background-image: url("images/background.png"); } .head_text{ color: white; } .card{ box-shadow: 0 16px 48px #E3E7EB; } #navbar { overflow: hidden; background-color: #333; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: #04AA6D; color: white; } .content { padding: 16px; } .sticky { position: fixed; top: 0; width: 100%; } .sticky + .content { padding-top: 60px; } </style> <!-- Nav bar --> <div id="navbar"> <a class="active" href="javascript:void(0)">Home</a> <a href="javascript:void(0)">News</a> <a href="javascript:void(0)">Contact</a> </div> <script> window.onscroll = function() {myFunction()}; var navbar = document.getElementById("navbar"); var sticky = navbar.offsetTop; function myFunction() { if (window.pageYOffset >= sticky) { navbar.classList.add("sticky") } else … -
502 bad gateway error nginx/1.14.0 (Ubuntu)
Hello Can anyone help me resolve 502 bad gateway Error nginx/1.14.0 (Ubuntu). I want to run my website and I am facing an issue for the same . Please let me know the steps to resolve this error . enter image description here -
Why Django update page and log out didn't work?
This is dashboard page with django login This is analyse page after i login but the user didn#t show up I click the analyse page when i am anonumoususer, the user didn't change after i login I don't get the reason why i am logged in but the user did not show up. Besides when i click logout it doesn't work either.Below is my logout code. I really appreciate it if anyone could help me!! from django.shortcuts import render,redirect import hashlib from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import AnonymousUser from django.contrib.auth import authenticate,get_user_model,login,logout,get_user from .forms import UserLoginForm,UserRegisterForm from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from django.template import Template,Context from .decorators import unauthenticated_user,allowed_users, admin_only from django.contrib.auth.decorators import login_required @csrf_exempt @unauthenticated_user def login_view(request): next = request.GET.get('next') form =UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username,password=password) login(request,user) if next: return redirect(next) else: return redirect('/home') context = { 'form': form, } return render(request,'users/login.html',context) def index(request): return render(request,'users/home.html') @csrf_exempt def register_view(request): next = request.GET.get('next') register_form = UserRegisterForm(request.POST or None) if register_form.is_valid(): user = register_form.save(commit=False) password = register_form.cleaned_data.get('password1') user.set_password(password) user.save() new_user = authenticate(username=user.username,password=password) login(request, new_user) if next: return redirect(next) return redirect('/userlist') context = { 'form': register_form, } return … -
How to preprocess uploaded images in views wih Django Rest Framework, and Django
I decided to process the image being uploaded to get the GPS location in views. the code work and saves to the db but I get prompted to with a FileNotFoundError at /api/v1/addWaste/ [Errno 2] No such file or directory: '/tmp/tmpnsym9i2b.upload.jpg' error. I learnt that this is because my upload is larger than 2.5mb. It is more complicated because the data ends up getting saved in the db. here is snippet of my views code I am using Django Rest Frameworks Generic Create View def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) # file = request.FILES['files'] serializer.is_valid(raise_exception=True) # geospatial fields picture=(serializer.validated_data['field_picture']) print(picture.temporary_file_path()) latitude, longitude = get_coordinates(picture) serializer.validated_data['latitude']= latitude serializer.validated_data['longitude'] = longitude # geom serializer.validated_data['geom'] = Point(latitude,longitude) serializer.save() if serializer.save(): return Response({ 'Response': 'Waste point Created suceesfully', 'payload': serializer.data }) ``` Here is a copy of my terminal debug message /.local/share/virtualenvs/Backend-bhMgLIsh/lib/python3.8/site-packages/django/core/files/move.py", line 56, in file_move_safe with open(old_file_name, 'rb') as old_file: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpnsym9i2b.upload.jpg' [02/Jun/2021 11:24:51] "POST /api/v1/addWaste/ HTTP/1.1" 500 179179 Thank you for your help. -
Auto Create new superUser for new teanants created in django
I tried this solution also but it is creating user in public schema only not in tenant schema . I am using djnago-tenant to create a new tenant. from django.dispatch import receiver from tenant_schemas.utils import tenant_context from django.contrib.auth.models import User @receiver(post_save, sender=Client): def create_superuser(instance, **kwargs): if 'created' in kwargs: # tests if this client was created tenant=instance with tenant_context(tenant): # Create the superuser by using the new client tenant schema User.objects.create_user( # insert your user data here ) Let me know what should i do or any other way to handle this -
Is it possible to use a custom test url for testing when running server using Python/Django on Windows?
I am used to PHP / Apache as I can add an entry in the Windows Hosts file and access that instead of using localhost url. For example, Windows > hosts file > 127.0.0.1 testsite.test and then I add this testsite.test in the Apache VirtualHost directive too. I am new to Python and Django and have been following a tutorial where it showed me how to setup Python an Django, and set up a virtual environment. After setting it up, it run python manage.py runserver that launched the default page on http://127.0.0.1:8000 Is it possible to access this url same as Apache above? -
Django-chatter base template not updating
I am unable to set the base template of django_chatter to my apps base template.Though i have added CHATTER_BASE_TEMPLATE = "accounts/base.html" in settings.py.Please help.