Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i use Task Errors exponential backoff in django-background-tasks?
I was trying out django-background-tasks on one of my projects and I have a case where I would like to retry a function if it throws an error after an hour. The documentation has details about Task error and using exponential backoff. But I am not sure how and where to provide it. Task errors Documentation -
Cannot access User last_name, first_name attributes through foreign key
Not sure what I am doing wrong here. I basically want to show the last_name and first_name from auth.User. Here is the model: class StudentItem(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT) last_updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, related_name="+", null=True) In the template, I am trying to reference the last_name as follows: {{student_item_details.created_by.last_name}} {{student_item_details.created_by}} works just fine which shows the username. I would rather not go through the exercise of overriding str on User or creating a custom User model if this is an easy fix. Thank you. -
Websockets, React + Django
I'm curious if there's a definitive answer on using Websockets, React and Django. From what I've read (1) the preferred way to link React with Django is to use Django Rest Framework (DRF.) (2) The preferred way to leverage websockets in Django, it would seem is through Django Channels. (3) And the preferred way to use websockets in React is through Socket.io. So it seems that linking all three is rather difficult. I see two possible solutions, which neither might be valid. React uses Socket.io and passes communicates w/ the backend via DRF. React is rendered through a Django template and websockets are leveraged via Channels. I imagine that #2 is the path with more headaches as Django is very opinionated framework. Is there a definitive answer on how Websockets, React and Django should be used together? (This question got virtually no traction.) Edit Less preferred option 3: Use React, Node & Express for most of the application, including websockets and DRF solely for the things that python really shines (ex ML pipelines.) -
Django Database Routers
I have set up routers in my django project, but the tables do not seem to be populating in any of the databases. Each time I run 'python manage.py makemigrations HealthcareProject4' I can see that the migration file is being created successfully. However when I run 'python manage.py migrate --database=default nothing appears to populate in any of the databases I have set up. db_routers.py from HealthcareProject4.settings import DATABASE_ROUTERS from HealthcareProject4.Conditions.models import * class AuthRouter: route_app_labels = ['auth', 'contenttypes', 'admin',] def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return model._meta.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return model._meta.app_label return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == app_label return None class EducationRouter: route_app_labels = ['EducationProject'] def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return model._meta.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return model._meta.app_label return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == app_label … -
Django - Using multiple databases for single project
I'm working on a booking system with the Django framework. Requirements are that i need to create two projects (the Website and an admin site for staff on-boarding and booking system management). I want to use SQLite3 for session details and other Django required tables/data and use a MySQL database to link the to projects together. Basically I want to be able to set available dates for booking via Admin site, which then will be able to be shown on the Website for people to be able to make the booking. I have tried multiple different ways to do this, but nothing seems to be working for me. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'theRock_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'theRock', 'USER': '<Database Username>', 'PASSWORD': '<Database User Password>', 'HOST': '<Database Host>', 'PORT': '<Database Port>', } } DATABASE_ROUTERS = ['routers.db_routers.theRockRouter',] db_routers.py class theRockRouter: route_app_labels = ['theRockAdminAccounts',] def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'theRock_db' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'theRock_db' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): … -
How to write regular expressions in JavaScript
I am using Django formset to enter values in multiple forms on one page. The 'date' field uses the 'datetimepicker' jquery, but the datetimepicker is not applied separately to each 'date' field of the 3 forms. In my opinion, each input has a unique name, so I need to create a regular expression using it. What do I need to fix? $( ".date" ).datetimepicker({ format: 'Y-m-d H:i' }); <input type="text" name="form-0-date" id="date" autocomplete="off" class="form-control col-sm-12 date"> <input type="text" name="form-1-date" id="id_form-1-date" autocomplete="off" class="form-control col-sm-12 date"> -
Django - unit test AssertionError: 302 != 200, decorator problem
I'm trying to write tests for my django app. The tests are failing because I'm getting 302 errors. For CBV I used have a decorator.py file that checks that the user is_teacher. I believe that this is what is causing the problem. view @method_decorator([login_required, teacher_required], name='dispatch') class ClassroomList(ListView): model = Classroom def get_queryset(self): return Classroom.objects.filter(user=self.request.user).order_by('classroom_name') model class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) def __str__(self): return self.username test.py class GradebookTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='tester', email='tester@email.com', password='tester123' ) self.user.is_active = True self.user.is_teacher = True def test_classroomgradebook(self): self.client.login(username='tester', password='tester123') response = self.client.get(reverse('gradebook:gradebookstart')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Choose the gradebook') self.assertNotContains(response, 'Enter') self.assertTemplateUsed(response, 'gradebook/classroom_list.html') decorator.py def teacher_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_teacher, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator If I remove the @method_decorator... from the view, the test passes. -
I can't find this error AttributeError at /register/ 'function' object has no attribute '_meta'
I'm not sure what does it mean by 'function' object has no attribute'_meta' error in my code if I try to click the register page it throws this error. On the other hand, it should create a new user. I think I have missed something and I can't seem to figure out what was that thing. Thank you Blockquote views.py from asyncio import tasks from dataclasses import field, fields from http.client import HTTPResponse from multiprocessing import context from pyexpat import model from re import template from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView, FormView from django.urls import reverse_lazy from base.models import Task from .models import Task from django.contrib.auth.views import LoginView from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login from django.contrib.auth.mixins import LoginRequiredMixin class CustomLoginView(LoginView): template_name ='base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('task') class RegisterPage(FormView): template_name = 'base/register.html' form_class =UserCreationForm redirect_authenticated_user = True success_url = reverse_lazy('task') def form_valid(self, form): user = form.save if user is not None: login (self.request, user) return super(RegisterPage, self).form_valid(form) class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = 'tasks' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) context['count'] = context['tasks'].filter(complete=False).count() return context class … -
project wit React, Rest API with python, Sql database
I have a project for school and they want me to create schedule app with: React as Frontend Rest API with python(i chose django rest framework) SQL database (i chose SQLite as default of django) But i have no idea to how to connect them to each other, i am all open to new ideas please help me. My main question is; Do i have to use fetch method to get the data in react or just django functions Thank you. -
Django: Transfer group permissions from one database to another
I have customized groups with custom permissions on my development server via the Django admin. I would like to transfer/migrate these groups along with their permissions to a production server. How would you suggest completing this task? Example of a group I would like to transfer it to production with these specific permissions -
Django aggregate sum of manytomany is adding up everything in its field instead of the ones selected
2 Classes involved in question class Appointment and class Service appointmentApp.models class Service class Service(models.Model): service_name = models.CharField(max_length=15, blank=False) service_time = models.IntegerField(blank=False) def __str__(self): return self.service_name class Meta: verbose_name_plural = "Services" appointmentApp/models.py class Appointment class Appointment(models.Model): service_chosen = models.ManyToManyField(Service, blank=False) total_time = models.IntegerField(blank=False, null=False, default=0) #will add up the amount of time needed for each service def save(self, *args, **kwargs): self.total_time += Service.objects.all().aggregate(total_time=Sum('service_time'))['total_time'] super(Appointment, self).save(*args, **kwargs) def __str__(self): return self.client_dog_name Services are chosen through a multiplechoice field and on save the service_chosen's service_time are added up but what my save function is doing instead is adding up all the existing service.service_time instead of the ones selected, why is this happening? -
Can I use React.js to create a presentation tool?
I'm trying to create a simple web tool that displays a moving object to 2 browsers/users at the same time. It also needs to allow User A to control the moving object (speed, direction). Any changes User A makes should be reflected in both User A's and User B's browser. Can I accomplish this with JavaScript and the React library? Or would I be better or using a framework like Angular? Or perhaps Python/Django? -
selecting some form inputs and show it to the user
I want to be able to select only required fields and show it to my frontend, this is the html template. {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> <div class="row"> <div class="col-6"> {{ field }} </div> </div> {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} I did something like {{ field.first_name }} but this does not show first name form input but if I use {{ field }} all the fields are shown up even the ones I don't want the user to see. How can I select only the fields I want to return to the user? -
Issues With Python Request using django
Am trying to Consume an API by sending a post request This is my code below def sendpostrequest(request): form = RechargeForm (request.POST or None) if form.is_valid(): mobile_number = form.cleaned_data['mobile_number'] amount = form.cleaned_data['amount'] network_id = form.cleaned_data['network_id'] plan_id = form.cleaned_data['plan_id '] if request.method == "POST": url = "https://exampleapi/api/topup/" payload = "{\"network\": network_id,\n\"mobile_number\": \"09037346247\",\n\"plan\":plan_id}" headers = {'Authorization': 'Token s66666vbbbbbbbb5c891fe9e7bbe3f9a0a8742d','Content-Type': 'application/json'} response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) info = response.json() info['mobile_number'] = mobile_number info['network_id'] = network_id info['amount'] = amount return render(request, 'data_api_recharge_successful.html', { 'info':info, 'mobile_number':mobile_number, 'network_id':network_id ,}) ERROR status_code = 400( The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing). error = response.text error = {"non_field_errors":["Invalid data. Expected a dictionary, but got str."]} . Error Clarification After this request is been sent i got Status Code=400 when i do status_code = response.status_code and response.text gave me {"non_field_errors":["Invalid data. Expected a dictionary, but got str."]} . status_code = response.status_code Request For Help Can someone Help me fix this because am very sure am doing something wrong to be … -
How can I call field level validation methods defined on both child and parent serializers?
I have a scenario where I have 3 serializers that each have a set of the same fields, as well as their associated serializer.validate_field methods: class Serializer1(serializers.Serializer): same_field_1 = serializers.BooleanField() same_field_2 = serializers.BooleanField() ... validate_field_1() validate_field_2() ... class Serializer2(serializers.Serializer): same_field_1 = serializers.BooleanField() same_field_2 = serializers.BooleanField() ... validate_field_1() validate_field_2() ... class Serializer3(serializers.Serializer): same_field_1 = serializers.BooleanField() same_field_2 = serializers.BooleanField() ... validate_field_1() validate_field_2() ... NOTE: each class contains other fields and validate methods that aren't shared with the other serializers as well. I would like to bring the common fields and validate methods up into a parent class, then have each of these child classes inherit from that parent class. The issue then becomes, how do I run the validation defined on the child and the parent? I don't see any specific documentation discussing how we can run the is_valid() cycle on the parent class as well as the child class. -
Django: custom Action with date parameter not working
I have the following code in Python Django: @action(detail=True, methods=['get'], url_path=r'by_date') def get_meal_by_date(self, request, meal_date=date.today): print(meal_date) meals_by_date = Meal.objects.filter( owner=self.request.user, mealTimestamp__day=meal_date.day, mealTimestamp__month=meal_date.month, mealTimestamp__year=meal_date.year ) serializer = self.get_serializer(meals_by_date, many=True) return Response(serializer.data, status=status.HTTP_200_OK) That Code works on call it like this: http://localhost:8000/meals/by_date/ My problem is how can I enrich the method to gets data back with date parameter. For example with this call: http://localhost:8000/meals/by_date/2022-03-16T21:30:45.290Z/ -
Django CBV use Values from Modelform to Calculate other Model Fields
I am trying to make a warehouse management system with Django 3.2 based on this models: class itemtype(models.Model): item_id = models.IntegerField(primary_key=True) item_name = models.CharField(max_length=100) group_name = models.CharField(max_length=100) category_name = models.CharField(max_length=100) mass = models.FloatField() volume = models.FloatField() used_in_storage = models.BooleanField(default=False, null=True) class Meta: indexes = [ models.Index(fields=['item_id']) ] def __str__(self): return '{}, {}'.format(self.item_id, self.item_name) class material_storage(models.Model): storage_id = models.AutoField(primary_key=True) material = models.ForeignKey(itemtype, on_delete=models.PROTECT) amount_total = models.IntegerField(null=True) price_avg = models.FloatField(null=True) order_amount = models.IntegerField(null=True) order_price = models.IntegerField(null=True) timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return '{}, {} avg.: {} ISK'.format(self.material, self.amount, self.price) "itemtype" defines basically the possible objects which could be stored and "material_storage" shows what is in stock. I tried to combine the total amount of every item as well as the average price paid for it and the amount and price for a single order in the same database row. The idea is to get the last record for the chosen item/material when a new order happens, add the amount of that order and recalculate the avg price. Theoretically this could be split up on two tables, but I don't see a reason to do so at the moment. However, I am not able to figure out the actual function code to do … -
system design for blockchain transactions ETL
I am trying to come up with scalable system design for one the projects i am working on in which i am using one of the google's blockchain public datasets bigquery-public-data.bitcoin_blockchain.transactions I would like to get the input/output address with most number of transactions by inflow and outflow and serve that information via a web application, so any time a GET request is sent for instance GET /address, my web app should get the top N input and output address for the given address and should return the response in the below format the Get request takes in address as a required parameter and startdate, enddate, flowtype(inflow,outflow, both) as optional parameters • { • "data": [ • { • "address": "", • "inflow_val": "", • "outflow_Val": "", • "total_val": "" • } • ], • "success": true • } I thought about exporting the transactions data from bigquery and dumping it to google cloud storage and have an airflow task that will copy over the bigquery extract from cloud storage to Postgresql, then i will setup django with postgresql as backend, and take care of GET request routes inside urls.py and the logic to calculate inflow and outflow inside of … -
return the user to specific blog post they deleted their comment from django
I am wondering could someone help me. I am new to Django and a part of my website the authorsied user will be allowed to comment on blogs that I have created. As part of this I want the user to be able to delete their own comment. Once they have chosen to delete their comment, I want them to be brought back to the blog that they originally had their comment on. As of now I have managed to get things working right up until the user is asked "are you sure you want to delete your comment", and this is when I run into errors. Just from reading and looking on the internet I think I need a "get_success_url" but this is where I get lost as I am not sure where to go from here or how to right the code. All I have in the class in my views.py file to render the html template. Thanks for any help provided :) -
Django filterset on aggregation, with multiple lookup expressions
For an API, I am calculating some values in real time (simple aggregations/functions such as sum, count, ratio). I would like to filter by these values with different operators. Currently for the filters i am using a filterset_class. The class looks a little like this: class BuildingFilter(filters.FilterSet): class Meta: model = Building fields = { "unit_number": ["gte", "gt", "lt", "lte", "range", "exact"], } address = filters.CharFilter(field_name="address", lookup_expr='icontains') The model Building has a relation with the model BuildingLeaseLog. In the BuildingLeaseLog there is a field rent. In the API response, I am returning a key "building_average_rent", which is calculated with an annotation in the queryset. So, for the field building_average_rent (and other similar ones), I would like to implement in this class filters with the following operators: "gte", "gt", "lt", "lte", "range", "exact". The API might receive any of the combinations of building_average_rent and the operators (ex building_average_rent__gte, building_average_rent__lt etc), and the filterset class should be able to filter accordingly However, I cannot: include it directly in the fields list (like I did with unit_number), because it is not an actual field of the model call a filter like I did for address, because I need 7 filters for it (one … -
How to insert bulk insert data in Djnago model Without providing fields
How to bulk insert data with only providing dictionary key and not worry about manually providing fields and type of fields in models.py What I have to do right now: models.py from django.db import models # Create your models here. class Info(models.Model): name = models.CharField(max_length=70) email = models.CharField(max_length=70) mongodb collection name | email Jon | j@g.com what I want without using fields and assigning more than 20-30 fields: name | email | fname | lname | cellNum | add | age | height | etc... for example using mongoClient to bulk insert data without providing fields data = {x:x, y:y, z:z} collection.insert_one(data) collection.insert_many([data,...]) -
How to prevent redirect_to_login from targeting LOGIN_REDIRECT_URL
So in general when a user logs in, my app redirects him to dashboard-overview: # settings.py # Login and Logout target routes LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'dashboard-overview' LOGOUT_REDIRECT_URL = '/' However for a specific case I want the user to be redirected to 'calculator-page' using a helper function which doesn't work as the user is again redirected to the value of LOGIN_REDIRECT_URL. # views.py def render_calculator(request, slug): """ Renders the calculator page """ # Check for the user being authenticated if not request.user.is_authenticated: return redirect_to_login('calculator-page') # routes to http://127.0.0.1:8000/login/?next=calculator-page which looks fine, # but then it fails after login to re-route as specified and sends to # 'dashboard-overview' again else: club_obj = Offer.objects.get(club__slug=slug) # Create Context context = { 'club_obj': club_obj, } return render(request, 'core/calculator.html', context) -
How to hide or modify <pk> in url in Django app?
In my url.py I have: path('gpd/<pk>/', views.gpd, name='gpd'), my view.py looks like: @login_required(login_url='login') def gpd(request,pk): # do smth context = {.... , 'pk':pk, } return render(request, 'app/gpd/gpd_form.html', context) I have noticed, that when my logined user change manually pk - then he has an access to page with another pk. How to prevent it? -
How do I get all objects that are more than a day old in Django?
I'm trying to write a query in Django for posts older than 24 hours. The Post form contains a DateTime field named Created_at and this field contains the time the post was added. How do I get all posts older than 24 hours in Django? -
the contact form dont send me it is show 404
I am a beginner in django and I have had a problem for 1 week now, several tutorials that I have watched have not solved anything, so I trust you. it's just making the different contact forms of my website designed with django work I therefore attach the source code of my project and the code, when I launch the send button (submit) I receive a 404 error DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FORM_EMAIL="ouesergegedeon225@gmail.com" EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'ouesergegedeon225@gmail.com' EMAIL_HOST_PASSWORD = 'Gedeon225@@' EMAIL_USE_TLS = 'True' EMAIL_USE_SSL = 'False' def send_mail(request): if request.method=="POST": name = request.POST.get['name'] subject = request.POST.get['subject'] email = request.POST.get['email_address'] message = request.POST.get['message'] send_mail( name, subject, email, message, 'ouesergegedeon225@mail.com', ['gedeonachat@mail.com'], fail_silently=False, ) message.info (request, 'Votre message a été envoyé') return render(request, 'contact.html') path('send_mail/', views.send_mail, name="send_mail"),```