Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
APScheduler not running in Django
APScheduler is not running in Django. I want to use the APScheduler library in a Djnago frame to get LINE notifications when a todo list deadline comes up, but I am not getting LINE notifications. Is there something wrong with the APScheduler settings? testapscheduler.py from apscheduler.schedulers.background import BackgroundScheduler from datetime import datetime, timedelta import pytz import requests import json from .models import Todo def notify_todo(): # 現在の日時を取得 now = datetime.now(pytz.timezone('Asia/Tokyo')) # 締め切りが30分以内のTODOリストを取得 todos = Todo.objects.filter( deadline__gt=now - timedelta(minutes=30), deadline__lt=now + timedelta(minutes=30), ttime__isnull=False, ttime__gt=now.time() ) for todo in todos: #LINE NotifyのAPIトークンを取得 api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 通知メッセージの作成 message = f"【{todo.title}】\n締切時間:{todo.deadline.strftime('%Y/%m/%d %H:%M')}\n詳細:{todo.description}" # LINE Notifyに通知を送信 headers = {'Authorization': f'Bearer {api_token}'} payload = {'message': message} requests.post('https://notify-api.line.me/api/notify', headers=headers, data=payload) #BackgroundSchedulerの設定 def start(): scheduler = BackgroundScheduler(timezone='Asia/Tokyo') scheduler.add_job(notify_todo, 'interval', seconds=1)#1秒ごとに実行 scheduler.start() apps.py from django.apps import AppConfig class TodoConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'todo' def ready(self): from .testapscheduler import start start() models.py from django.db import models class Todo(models.Model): title = models.CharField("タスク名", max_length=30) description = models.TextField("詳細", blank=True) deadline = models.DateField("締切") ttime = models.TimeField("") def __str__(self): return self.title -
start Django project in vs code
Im trying to learn Django. I started a youtube tutorial managed to do some basic stuff etc. After closing the vs code, the server closed too. Now when I try to start the project using python manage.py runserver or python manage.py startapp, i get the error "zsh: command not found: python" im trying to do all that in vs code terminal -
Company - Worker Algorithm in Django
I want to ask a question about my algorithm. The operation should be like this; There is one or more companies, this is the top cluster. There are work fields affiliated with these companies. When the company receives a project, it gives it to the work fields, and at the same time, this project has a total price. It divides work packages into work fields and allocates a budget to each work field from the total price of the project. Each work field belonging to the company has its own work package to be completed, and there is a price for this package. When any work package is completed, I want to reduce both the price of the work completed from the work field budget and the total price of the project. But I was undecided on how to connect the payment. Can you help me? Here is the ERD Model link: https://ibb.co/ch0F3Bg I made a mistake on the worker part, ignore it. 🙂 More than one worker can work in a work field, I will fix it while connecting the diagram 🙂 I have given all the details above. -
How do I get the values out of a string object
I am sending some values to a Django back end and I would like to get the values from the object. This is the part that gets the data on the front end and sends it to the back end: function addCartToDB(cart) { let formdata = new FormData(); formdata.append("user", loggedUser); formdata.append("carttotal", cart.carttotal); for (var item of cart.items) { let data = { id: item.id, qty: item.qty, }; formdata.append("products", data); } axios .post("api/v1/cart/c/", formdata) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); } This is the view that is supposed to process the request: class CreateCart(generics.CreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = CartSerializer def post(self, request): entries = request.data.getlist("products") for entry in entries: breakpoint() Since there is just one product in the cart the entry object looks like this: [object Object] and the data that is supposed to be in there is the product id and the product quantity which will be strings. How do I get the values of out the object please? -
Nuxt 3 dynamic route not found
I have a problem with nuxt 3 frontend application: I use nuxt 3 as my frontend and django as my backend and api service. When I run npm run build (it executes nuxt generate) command in local, to get files ready to be send to production, the files like /blog/9, /blog/6, /blog/4 etc. are generated into /.output/public dir. These numbers are posts ids, and posts are fetching from backend using axios, and they are generated because they already exists on backend and are automaticly fetching by nuxt when command is ran. The thing is, when i enter the domain like https://example.com/blog/9 via button or link on website, that includes the id param, that has been previously generated via npm run build command, it's all good, even with blog posts that have been generated after deploying nuxt files the production server, like https://example.com/blog/12 or https://example.com/blog/27. But when I enter the url https://example.com/blog/12 manually, not via the link or buttom on the website, it returns me a default 404 error provided by the server, as the post wasn't found. I want it to automaticly get id param from url and execute the fetch method by axios. Axios method from Post.vue component: import … -
Enable CSRF TOKEN in Django html coded using element-ui
I am trying to add CSRF TOKEN (to ensure CSRF protection) to my html script in Django for the POST requests so that it will not be classified as an unsafe request. However I am unsure of where I should place it. When I place it within {% verbatim %}, it comes off as a text as shown on in the image. Really desperate and really appreciate any advice. {%extends "doctor.html" %} {% block emr %}active{% endblock %} {% block mainbody %} {% verbatim %} {% csrf_token %} <div id="app2" class="container"> <el-row :gutter="20" style="width: 90%; height: 120%;"> <el-col :span="12"> <div class="info-wrapper"> <div class="header">Add new medication delivery jobs</div> <el-form ref="deliveryInfoForm" :model="deliveryInfo" :rules="deliveryRules" label-width="110px" label-position="left"> <el-form-item label="Order ID" prop="order_id"> <el-select v-model="deliveryInfo.order_id" placeholder="Select an Order ID" style="width: 100%; margin-left: 0px;" > <el-option v-for="item in order_id" :key="item.id" :label="item.order_id" :value="item.order_id"> <span style="float: left">{{ item.order_id }}</span> </el-option> </el-select> </el-form-item> <el-form-item label="Box Number" prop="box_number"> <el-select v-model="deliveryInfo.box_number" placeholder="Default: Box 1" style="width: 100%; margin-left: 0px;" > <el-option v-for="item in box_options" :key="item.value" :label="item.label" :value="item.value"> <span style="float: left">{{ item.label }}</span> </el-option> </el-select> </el-form-item> <el-form-item> <el-button style="width: 100%;" type="primary" @click="onSubmit">Confirm</el-button> </el-form-item> </el-form> </div> </el-col> <el-col :span="12"> <div class="info-wrapper"> <div class="header"><center>Medications Delivery Status</center></div> <el-table :data="list" stripe style="width: 100%" :cell-style="{ textAlign: 'left' }" :header-cell-style="{textAlign: … -
Is there a way to make chatsocket.send send the data to all of the instances at the same time?
In a typical consumers class, we would have the following: class SomeConsumer(AsyncWebsocketConsumer): async def connect(self): ... async def disconnect(self, close_code): ... async def receive(self, text_data): ... async def chat_message(self, event): await self.send(text_data=json.dumps({"event": event})) In this example, self.send is called once for each instance of SomeConsumer. However, I don't think all of the chat_message methods get called concurrently, at the same time for each instance, since I notice a delay in the display of the javascript data when I have multiple windows open. Ideally, I would like the data to display at the exact same time across X number of windows. Is there a way to make this work? I tried to create tasks and then await them once number_of_chat_message_calls = number_of_instances, like this: async def chat_message(self, event): SomeConsumer.count+=1 SomeConsumer.tasks.append(asyncio.create_task(self.send(text_data=json.dumps({"event": event})))) if SomeConsumer.count == SomeConsumer.consumers: done, pending = await asyncio.wait(SomeConsumer.tasks) SomeConsumer.tasks.clear() SomeConsumer.count = 0 but it still doesn't display the data synchronously. Is there any way to achieve this? -
How to improve reliability of Django-Q Schedule Tasks
My project currently has about 300 scheduled tasks. Some of these run every hour on the hour and some run once a day (at midnight). The tasks make API calls to third party API's. This is the current set up of my Q_CLUSTER Q_CLUSTER = { 'name': 'DataScheduler', 'workers': 3, 'timeout': 15, 'retry': 300, 'queue_limit': 10000, 'bulk': 10, 'max_attempts': 1, 'orm': 'default' } Of the 300 tasks, about 120 of them fail (different ones every time). If I manually trigger these to run they pass so there isn't anything wrong with the actual request. I believe the q cluster can't process all of the tasks when they are triggered at the same time. I think this can be improved by tweaking the Q_CLUSTER settings but I'm unsure how best to do this. I've tried running through the documentation https://django-q.readthedocs.io/en/latest/configure.html But I'm unsure how to improve the success rates of the scheduled tasks. I've struggled to find any other articles or documentation to explain how best to utilise these settings. My question is - how can I improve these settings to ensure the tasks pass? With time I will have more scheduled tasks so looking to address now before it gets … -
Django generating a query in the group
I have models like this: class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) class Project(models.Model): name = models.CharField(max_length=128) class EmployeeProject(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='employee_projects', ) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) role = models.ForeignKey(ProjectRole, on_delete=models.CASCADE) skill_level = models.ForeignKey(SkillLevel, on_delete=models.CASCADE) hourly_rate = models.DecimalField(decimal_places=2, max_digits=9) class TaskRole(LogOnSaveMixin, DiffModel): task = models.ForeignKey( Task, on_delete=models.CASCADE, related_name='roles', ) estimated_hours = models.FloatField(null=True, blank=True) And I have a queryset like this: qs = Task.objects.all() user = self.request.user host_roles = EmployeeProject.objects.filter( employee=user.employee, ) qs = qs.annotate( total_estimated_hours=Sum('roles__estimated_hours'), ) open_tasks_qs = qs.filter( Q(project__in=host_roles.values('project_id')), ).filter( ( Q(total_estimated_hours__isnull=False) ), ) qs = open_tasks_qs | qs.filter(author=user).distinct() qs = qs.values('id') qs = qs.distinct() return qs The problem is that this query yields an error, saying that more than one row returned by a subquery used as an expression The corresponding sql looks like this: SELECT DISTINCT "tasks_task"."id" FROM "tasks_task" LEFT OUTER JOIN "tasks_taskrole" ON ( "tasks_task"."id" = "tasks_taskrole"."task_id" ) GROUP BY "tasks_task"."id", ( SELECT U0."project_id" FROM "tasks_employeeproject" U0 WHERE U0."employee_id" = 1 ) HAVING ( ( "tasks_task"."project_id" IN ( SELECT U0."project_id" FROM "tasks_employeeproject" U0 WHERE U0."employee_id" = 1 ) AND SUM( "tasks_taskrole"."estimated_hours" ) IS NOT NULL ) OR "tasks_task"."author_id" = 1 ) ORDER BY "tasks_task"."id" DESC There are two questions: How … -
How to send data from other Django app to other server
How to send data from other Django app to other server using HTML file (client side), with cors I’ve tried disabling cors -
How to handle POST net::ERR_CONNECTION_REFUSED error in Axios Vue.js django
I am using axios to send the data for the backend but it keeps break, what should i do? in .then(response => { this.$router.push('/Log-in') return response }) i returned the "response" because the console is saying "error 'response' is defined but never used" vue.js file import axios from 'axios' if (!this.errors.length) { const formData = { username: this.username, password: this.password, email: this.email } axios .post('/api/v1/users', formData) .then(response => { this.$router.push('/Log-in') return response }) .catch(error => { if (error.response) { for (const property in error.response.data) { this.errors.push(`${property}: ${error.response.data[property]}`) } console.log(JSON.stringify(error.response.data)); } else if (error.massege) { this.errors.push('Something went wrong, Please try again!') console.log(JSON.stringify(error)); } }) } setting.py django CORS_ALLOWED_ORIGINS = [ 'http://localhost:8000', 'http://127.0.0.1:8000/' ] -
I want to get the specific reviews from a different model Django
I am making a review section for my record company, but I have a hard time figuring out how I can get the specific reviews for the specific album, I pass in an id to a template called "Albumin" to get the exact album, but how do I get the reviews? models: class albums(models.Model): title = models.CharField(max_length=100) description = models.TextField() release_date = models.CharField(max_length=10) artist = models.CharField(max_length=100) genre = models.CharField(choices=GENRE_CHOICES, max_length=20) image = models.ImageField(default='default2.jpg', upload_to='album_pics') slug = models.SlugField() def __str__(self): return self.title class ReviewRating(models.Model): album = models.ForeignKey(albums, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100, blank=True) review = models.TextField(max_length=500, blank=True) rating = models.FloatField() ip = models.CharField(max_length=20, blank=True) status = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject or f"ReviewRating #{self.pk}" views: def albuminfo(request, id): album = albums.objects.get(id = id) reviews = ReviewRating.objects.all() return render(request, "home/AlbumInfo.html", {'album' : album, 'reviews' : reviews}) def submit_review(request, album_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ReviewRating.objects.get(user__id=request.user.id, album__id=album_id) form = ReviewForm(request.POST, instance=reviews) form.save() messages.success(request,'Your review has been updated') return redirect(url) except ReviewRating.DoesNotExist: form = ReviewForm(request.POST) if form.is_valid(): data = ReviewRating() data.subject = form.cleaned_data['subject'] data.review = form.cleaned_data['review'] data.rating = form.cleaned_data['rating'] data.ip = request.META.get('REMOTE_ADDR') data.album_id = album_id data.user_id = request.user.id data.save() messages.success(request, 'Your review has … -
Safe to use django ORM from gevent greenlets or threads under WSGI?
I think the answer is “yes” but is there some official documentation I can point to? I try to inspect what is happening under the hood but have trouble convincing myself -- see this code snippet, which compares thread locals and DB connection objects between gevent greenlets and gevent threads: import time from django import db import gevent from gevent.pool import Pool from gevent.threadpool import ThreadPool def my_view(request): pool = Pool(4) start = time.time() for _ in range(4): def foo(x): time.sleep(x) print(db.connections['default']) print(threading.local()) pool.spawn(foo, 1) pool.join() delay = time.time() - start print('Running "time.sleep(1)" 4 times with 4 greenlets. %.3fs' % delay) threadpool = ThreadPool(4) start = time.time() for _ in range(4): def bar(x): time.sleep(x) print(db.connections['default']) print(threading.local()) threadpool.spawn(bar, 1) threadpool.join() delay = time.time() - start print('Running "time.sleep(1)" 4 times with 4 threads. %.3fs' % delay) I guess the django ORM is thread-safe, but I also want to make sure that each thread is getting its own DB connection. This appears to be the case from the output: <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f92aef538b0> <gevent._gevent_clocal.local object at 0x7f92809a2be0> <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f92810fefd0> <gevent._gevent_clocal.local object at 0x7f92809a2c40> <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f92810f1af0> <gevent._gevent_clocal.local object at 0x7f92809a2ca0> <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f9281068190> <gevent._gevent_clocal.local object at 0x7f92809a2d00> Running "time.sleep(1)" … -
Django interface buttons no longer work after connecting to IP 0.0.0.0:8000
I am trying to access Django website from a secondary device using python manage.py runserver 0.0.0.0:8000 The primary device that my laptop is connected to the same network as my secondary device, and I have turned off all firewalls. Also, I have configured the Allowed Host in settings.py file in Django by adding the IP address of the common connected data (192.168.61.130). However, when I access the website, the buttons on the website does not direct me to any page that I have linked in urls.py file. ALLOWED_HOSTS = ['192.168.61.130', '127.0.0.1', 'localhost'] From the example below, I have pressed the log in button and the POST request does show on the terminal. However, it does not direct me to the next page when I connect to the IP: 0.0.0.0:8000. The website works completely fine when I run on local host. Not sure why this is so and really need help on this. Hope to get any advice. -
Redis Broker getting OOM as "*.reply.celery.pidbox" keys count increased
Recently I have pushed around 10-15k tasks into celery by iterating in a for loop. Attaching below code for reference. for index, htl_urls_chunk in enumerate(iteration_grouper(htl_urls, n=10, chunk_type=list)): update_cache_for_hotel_detail_page_chunk.apply_async(kwargs={'htl_urls_chunk': htl_urls_chunk}) the length of htl_urls is around: 10-15k. Total tasks pushed ~ 1500 at given point of time. This lead to creation of below keys in redis: 01f6ebdb-361b-32ec-afe9-2eb7c8511288.reply.celery.pidbox 6292044c-a816-349a-a159-682536ea9bfa.reply.celery.pidbox Each key is of 150MB and total 29 keys created (4.24GB) This lead to OOM issue of my redis cluster. Can anyone suggest why this is happening ? I have tried to explored why these keys are being created in my redis cluster, but not able to reach any conclusion so far. -
Using MySQL CONVERT_TZ in django ORM
I am using the CONVERT_TZ MySQL function to convert datetime saved into the database into other timezone while running query. But I want to do the same thing with Django ORM due to performance issues with the next steps. Below is the code I am doing. boarding_stations = StationPoints.objects.filter(bus_id__in=bus_ids, station_id=sourceStation).annotate(coverted_timezone=Func(F('reachedTime'), '-08:00', '+05:30', function='CONVERT_TZ')) The above code returns FieldError as it says Cannot resolve keyword '-08:00' into the field. What's the correct way to use this MySQL function? -
Unable to call django view from template
Below is my urls.py code snippet for the main app urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home'), path('save_query',views.SaveQuery,name='SaveQuery'), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Below is my html template snippet <form method="post" action="{% url 'save_query' %}"> {% csrf_token %} <p id="error-msg"></p> <div class="row"> <div class="col-lg-6"> <div class="mb-3"> <label class="form-label" for="name">Name</label> <input name="name" id="name" type="text" class="form-control" placeholder="Enter your name..." /> </div> </div> <div class="col-lg-6"> <div class="mb-3"> <label class="form-label" for="email">Email address</label> <input name="email" id="email" type="email" class="form-control" placeholder="Enter your email..." /> </div> </div> </div> <!-- end row --> <div class="mb-3"> <label class="form-label" for="subject">Subject</label> <input name="subject" id="subject" type="text" class="form-control" placeholder="Enter Subject..." /> </div> <div class="mb-3"> <label class="form-label" for="comments">Message</label> <textarea name="comments" id="comments" rows="3" class="form-control" placeholder="Enter your message..."></textarea> </div> <div class="text-right"> <!-- <input type="submit" id="submit" name="send" class="submitBnt btn btn-primary" value="Send message" /> --> <button type="submit" id="submit" name="send" class="submitBnt btn btn-primary" value="Send message"></button> </div> </form> Below is my view function (in the views.py file of the main app folder) def SaveQuery(request): if request.method == "POST": name = request.POST["name"] email = request.POST["email"] subject = request.POST["subject"] message = request.POST["comments"] query = Query(name=name,email=email,subject=subject,message=message) query.save() print(f"[DEBUG] New query has been saved @ {debug()}") return redirect('home') return render(request,"main.html") On running the application I get the following error Reverse for 'save_query' not found. 'save_query' is not a valid view … -
Registration during performance testing
I have an app on django, that I am writing performance tests for it using locust. I have a custom registration process (not the built-in one from django, session-based), that require you to verify your email by sending a link with token to your email. What is the best way to register and authenticate a user in locust? Generate a verification token in locust bu providing it the same secret key Make the request to some email api to get the token from there Skip the registration process and use pre-configured users Something else? -
Permission in pytest
I would like to test views with PermissionRequiredMixin where permission_required = 'can_manage_employees' Fixture below. I got error assert 403 == 302. It look like I did not grant correctly permission to user. Where is mistake? I tried give permission in different way but i did not give result `@pytest.fixture def my_permission(): permission, _ = Permission.objects.get_or_create( codename='can_manage_employees', name='can manage employees', content_type=ContentType.objects.get_for_model(User) ) return permission @pytest.fixture def user_with_permission(my_permission): u = User.objects.create_user( username='Dariusz', email='testuser@example.com', password='password' ) u.user_permissions.add(my_permission) return u ` Another ways of add permission -
Override the template of a widget and pass values to it with Django 4.0
I am creating a simple app to do product reviews. I have a Product, Manufacturer and Review models which I will now summarize (this is not my actual code, if you see some small errors it is because I am rewriting everything now to make it easier to understand) class Manufacturer(models.Model): name = models.CharField() class Product(models.Model): name = models.CharField() manufacturere = models.ForeignKey(Manufacturer) class Review(models.Model): title = CharField() product = models.ForeignKey(Product) I created a ModelForm to create the review. So far I was only able to create a custom widget with an overridden template. class CustomSelectWidget(forms.widgets.Select): option_template_name = 'widgets/select_option.html' class NewReviewForm(forms.ModelForm): review = forms.ModelMultipleChoiceField( queryset = Review.objects.none(), widget = CustomSelectWidget(), ) class Meta: model = Review fields = '__all__' The form view is a normal function based view. The review field is rendered with a list of products in a <select>.What I want to do is change the text inside <option> to make it so that the manufacturer's name is also there. IMPORTANT: I have to take the manufacturer's name from the respective Object, I can't just insert it into the Product name field. ES: what I have now Geforce RTX2080 MAXSUN AMD Radeon RX 550 Arca770 the goal NVIDIA - … -
Download files when popup is open in Django project
Hello there I need to download the file buy the in put post by the popup window in my Django project I am sharing the, the html code of popup window and function in views.py. if I don't use popup window it is working file and able to download file. HTML of Popup window <div class="modal-content"> <div class="modal-header"> {% for fil in instance %} <h5 class="modal-title">Download files for {{ fil.recorule_name|title }}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <table class="table table-hover tablebdr"> <thead> <tr> <th>Account</th> <th>Rule name</th> <th>Date</th> </tr> </thead> <form action="{% url 'downloadlog'%}" method="POST" enctype="multipart/form-data" id="downloadlog-form"> {% csrf_token %} <tbody> <h6 id="modal_body"></h6> {% if fil.in_file1 %} <tr scope="row"> <td> <input type="text" class="form-control m-0" name="account_name" id = "account_name" value="{{ fil.account_name|title }}" readonly style="background-color: #f2f2f2; border: none;"> </td> <td> <input type="text" class="form-control m-0" name="recorule_name" id = "recorule_name" value="{{ fil.recorule_name|title }}" readonly style="background-color: #f2f2f2; border: none;"> </td> <td> <input type="date" class="form-control" name="recon_date" id= "recon_date"> </td> </tr> {% endif %} {% endfor %} </tbody> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary btn-rounded btnwidth" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary btn-rounded btnwidth" id="downloadlog-submit">OK</button> </div> </div> <div class="modal-body"> <div class="alert alert-danger" style="display:none;" id="error-message"> Error message goes here. </div> <div class="alert alert-warning" … -
Django Modelformset
I have followed this link https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/ to help me in creating a modelformset. However, each time I press "submit", it creates new forms and it shows the previously submitted forms. That's not what I want, I want to specify in my view how many forms I want and it should stay that way after submitting. How can I cause no extra forms to be made after submitting? views.py: def test(request): AuthorFormSet = modelformset_factory(Author, fields=('name', 'title', 'birth_date'), extra=3) if request.method == 'POST': formset = AuthorFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() return render(request, 'voting/test.html', {'formset': formset}) # do something. else: formset = AuthorFormSet() return render(request, 'voting/test.html', {'formset': formset}) models.py: TITLE_CHOICES = [ ('MR', 'Mr.'), ('MRS', 'Mrs.'), ('MS', 'Ms.'), ] class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3, choices=TITLE_CHOICES) birth_date = models.DateField(blank=True, null=True) def __str__(self): return self.name forms.py: class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ('name', 'title', 'birth_date') test.html: <form method="post"> {{ formset.management_data }} {% csrf_token %} {{ formset }} <button type="submit" name = "voting" class="btn btn-primary save">Submit</button> </form> -
How to test @login_required view in django
I've a django view which has @login_required decorator then it renders html file with context and I'm trying test it's function whether the context is in response @login_required def my_view(request): #code goes here context={'name':name} return render(request, home.html, context) class TestEmployer(TestCase): def setUp(self): self.client = Client() self.client.login(username='1', password='Pass@123') def test_list_employer(self): url = reverse(my_view) response = self.client.post(url, follow=True) self.assertEqual(response.status_code, 200) self.assertIn('name', response.context) So @login_required decorator blocking me to test the function and asserts an error with 'name' not in signin html page -
Django Query two Models and Display Records in One HTML Table
I am working on a Django Daily Saving Project where I have Statement view and I want to display a Customer's Deposits and Withdrawals (all his deposits and withdrawals) in one HTML Table. I am looking at the Best Performance (Constant Complexity for Big O Notation if possible in this case). I don't know whether there is another way of displaying records in a table from a Model other than using a For Loop. If there is, then your kind answer is also welcome. Here are my Models: class Deposit(models.Model): customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' class Witdrawal(models.Model): account = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) withdrawal_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.account}- Withdrawn - {self.withdrawal_amount}' Here is my view: def account_statement(request, id): try: customer = Account.objects.get(id=id) #Get Customer ID customerID = customer.customer.id except Account.DoesNotExist: messages.error(request, 'Something Went Wrong') return redirect('create-customer') else: deposits = Deposit.objects.filter(customer__id=customerID).order_by('-date')[:5] #Get Customer Withdrawal by ID and order by Date minimum 5 records displayed withdrawals = … -
Celery: Would increasing the number of queues speed things up?
I'm running my site on a VPS with 4 vCPUs, so by default each queue has 4 worker processes. I'm running 6 queues simultaneously now for my Celery process. The first queue, let's call it queue1, it's a very busy queue with multiple tasks/processes running all the time (mostly I/O tasks). Should I split queue1's tasks into smaller queues, e.g. queue1a, queue1b, queue1c, etc.? Will there be a performance benefit? My CPU utilization is quite high, I was just wondering if doing this will ease things up a little.