Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, Broken pipe from ('127.0.0.1', 55301)
I am encountering this problem when making fast requests for a Django == 4.0.5 project that I am still developing: [11 / Apr / 2023 18:50:14,703] - Broken pipe from ('127.0.0.1', 55300). I have 1 video on my page and it takes up 3mb. However, when I make quick transitions between pages, i.e. when I create too many requests, a spinner appears and it takes time for the video to load. I am using Django DEBUG True and not using any Nginx or WSGI Server. What is the solution? -
how to generalize query with more of two dates in ArrayField(models.DateTimeField()) field?
I have a Model: from django.contrib.postgres.fields import ArrayField class MyClass(models.Model): some_field = ArrayField(models.DateTimeField(), default=list) And have this query to filter for objects that has at least one of the date inside a range: date_range_for_reminders_check = [yesterday.date(), timezone.now().date()] MyClass.objects.filter(( Q(some_field__0__date__range=date_range_for_reminders_check) | Q(some_field__1__date__range=date_range_for_reminders_check) )) But this worked when every row of MyClass had only two dates in some_field, nowadays these may have more dates and need to be generalized take account diferent quantity of dates so i need something like: date_range_for_reminders_check = [two_days_ago.date(), timezone.now().date()] MyClass.objects.filter(( Q(some_field__0__date__range=date_range_for_reminders_check) | Q(some_field__1__date__range=date_range_for_reminders_check) | Q(some_field__2__date__range=date_range_for_reminders_check) | ... Q(some_field__X__date__range=date_range_for_reminders_check) | )) but without specifying indexs. -
Django Returning Items outside filter when filtering by time
I have a snippet of code designed to grab the entries that are <24 hours old yesterday = datetime.now() - timedelta(days=1) items = get_model(name=p).objects.filter(tagid=tag.id, t_stamp__gt=yesterday).order_by('t_stamp') for i in items: print(f'{i.t_stamp} - {i.t_stamp > yesterday}') print(yesterday) Yet for some reason, it returns 2 items, when it should return 0. Results of the print statement above: 2023-04-06 13:12:54.540000 - False 2023-04-06 14:12:46.976000 - False 2023-04-10 10:06:27.526066 As you can see, the timestamp is NOT greater than yesterday, so why is it being returned? -
django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.33). in Django
I have this error when performing migrations to my file command I tried this command python manage.py makemigrations but Error insist django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.33). Is there anyway to perform migration? or should I downgrade my python version to v.9? python version python v.3.10 -
Custom fonts working on development but not in production django
I have a project I'm working on that's hosted on Digital Ocean's app platform. In development my locally stored fonts work just fine. As soon as I load my project on Digital Ocean they no longer work. I use Digital Ocean's spaces for static files and uploaded files. My CSS looks like this: /* Fonts */ @font-face { font-family: 'canto'; src: url('../fonts/Canto-Bold.woff2') format('woff2'); } @font-face { font-family: 'Poppins'; src: url('../fonts/Poppins-Light.woff2') format('woff2'); } @font-face { font-family: 'canto-roman'; src: url('../fonts/Canto-Roman.woff2') format('woff2'); } @font-face { font-family: 'poppins-bold'; src: url('../fonts/Poppins-SemiBold.woff2') format('woff2'); } My folder structure looks like this: -Project --app --app --templates --media --static ---static/CSS -> .CSS file ---static/fonts/ font files All other files work fine, just the fonts don't. I've tested this with two seperate computers. Neither one has the fonts installed. Did I miss something? -
How to implement change in transfer_pin and receive an OTP
I am currently working on an application and using Django for the backend. It's a payment platform that requires a transfer_pin which can be reset or changed for security reasons by the user. When a user change the transfer_pin, an otp is sent to him/her to confirm he is the owner of the account. Below is what I have been able to do but I am having this error from Twillo that says: Unable to create record: The number is unverified. I will appreciate it if someone can help. I feel I am not doing something right. class TransferPin(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) transfer_pin = models.CharField( max_length=100, null=True, blank=True, validators=[ RegexValidator(regex="^\d{4}$", message="PIN must be a 4-digit number.") ], ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.transfer_pin = make_password(self.transfer_pin) super().save(*args, **kwargs) # This method checks if the pin matches the hashed pin in the TransferPin instance. def verify_pin(self, pin): return check_password(pin, self.transfer_pin) class TransferPinChangeSerializer(serializers.ModelSerializer): transfer_pin = serializers.CharField(max_length=4) class Meta: model = TransferPin fields = ['transfer_pin'] def create(self, validated_data): otp = random.randint(100000, 999999) # otp_expire = datetime.now() + timedelta(minutes=10) phone_number = self.context['request'].user.phone_number user = self.context['request'].user try: pin = TransferPin.objects.get(user=user) except TransferPin.DoesNotExist: pin = TransferPin(user=user) pin.transfer_pin = validated_data["transfer_pin"] pin.save() … -
NoReverseMatch at /processor/quantum-computing/ Reverse for 'post_detail'
I have a django blog site, but when a user adds a comment,the page returns an error page instead of the commented post. NoReverseMatch at /processor/quantum-computing/ Reverse for 'post_detail' with keyword arguments '{'slug': 'quantum-computing'}' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'] URLs.py urlpatterns = [ path('search/', views.search, name='search'), path(r'<slug:category_slug>/<slug:slug>/', views.detail, name='post_detail'), path('<slug:slug>/', views.category, name='category_detail'), ] Models.py class Post(models.Model): ACTIVE = 'active' DRAFT = 'draft' CHOICES_STATUS = ( (ACTIVE, 'Active'), (DRAFT, 'Draft') ) category = models.ForeignKey(Category, related_name='posts', on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() intro = models.TextField() body = HTMLField() created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=CHOICES_STATUS, default=ACTIVE) image = models.ImageField(upload_to='uploads/', blank=True, null=True) class Meta: ordering = ('-created_at',) def __str__(self): return str(self.title) def get_absolute_url(self): return '/%s/%s/' % (self.category.slug, self.slug) Here is a look at my views.py file where after user posts comment, the user should be redirected to the post. Views.py def detail(request, category_slug, slug): post = get_object_or_404(Post, slug=slug, status=Post.ACTIVE) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', slug=slug) else: form = CommentForm() -
django views the cartItems which is called from Models is showing error
hello I'm trying to get cartitems from models with related name and the cartitem is getting error in views what so i do ? here is my view-- def cart(request): cart = None cartitems = [] if request.user.is_authenticated: cart, created = Cart.objects.get_or_create(user=request.user, completed=False) cartitems= cart.cartitems.all() context = {"cart": cart, "items": cartitems} return render(request, "cart.html", ) def add_to_cart(request): data = json.loads(request.body) products_id = data["id"] products = Product.objects.get(id=products_id) if request.user.is_authenticated: cart, created = Cart.objects.get_or_create(user=request.user, completed=False) cartitem, created = CartItem.objects.get_or_create(cart=cart, products=products) cartitem.quantity += 1 cartitem.save() print(cartitem) return JsonResponse('it works', safe=False) Models.py--- class Cart(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) completed = models.BooleanField(default=False) def __str__(self): return str(self.id) class Meta: db_table = 'hatkesh_cart' class CartItem(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE , related_name='items') cart = models.ForeignKey(Cart, on_delete= models.CASCADE, related_name='cartitems') quantity = models.IntegerField(default=0) def __str__(self): return self.products.title class Meta: db_table = 'hatkesh_cartitems' and the error is------ `Cannot access member "cartitems" for type "Cart" Member "cartitems" is unknown` error is coming from views.py I have tried different related names but it still not works !! I was trying to call cart items to cart -
Cant' start gunicorn for a django project, due to failed (Result: resources) error
I can't figure out what's wrong. Spend almost 2 days on this error and I am not able to find if it is a typo or concept mistake. I want to mention that the app started perfectly using `python3 manage.py runserver 0.0.0.0:8080. My environment is on this path: home/paul/env My project directory is on this path: home/paul/project wsgi file is on this path: home/paul/project/application gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=paul Group=paul # i also used www-data WorkingDirectory=/home/paul/project ExecStart=/home/paul/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ application.wsgi:application [Install] WantedBy=multi-user.target When I run sudo systemctl status gunicorn.socket, as you can see below everything looks fine, enabled, active. ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; preset: enabled) Active: active (listening) since Tue 2023-04-11 12:31:59 UTC; 32min ago Until: Tue 2023-04-11 12:31:59 UTC; 32min ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket But when I run sudo systemctl status gunicorn it fails. × gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; preset: enabled) Active: failed (Result: resources) TriggeredBy: ● gunicorn.socket CPU: 0 The error make you think about the resources, but I checked and there are enough resources. -
How to fix when sending email a local variable referenced before assignment problem in Django?
I like to send an email to an admin if a new user is filled out his profile. If the user choose an association from the form the queryset finds the admin's email and sends the message but It works not because of this error: local variable 'adminemail' referenced before assignment. I can understand what the problem is but I don't know how to fix it. If I add a static email address outside the POST method it works well but it's not right for me. Please show me the right solution! views.py def ProfileFun(request): form = ProfileForm(request.POST, request.FILES) if request.method == 'POST': assoc = form.instance.egyesulet for email in Association.objects.raw('SELECT * FROM szaknevsor_association WHERE rovidnev = %s', [assoc]): adminemail = email.admin.email if form.is_valid(): form.save() send_mail( 'New notification', 'This is amessage', 'e@mymail.com>', [adminemail], fail_silently=False, ) print (form.errors) return redirect('szaknevsor:szakemberek') else: print (form.errors) return render(request, 'szaknevsor/profile.html', {'form':form,}) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' exclude = ('valid',) models.py class Profile(models.Model): def __str__(self): return str(self.user) ASSOCIATION = [ ('first', 'First'), ('second', 'Second'), ] user = models.OneToOneField(User, unique=True, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Felhasználó") egyesulet = models.TextField(max_length=200, choices=ASSOCIATION, verbose_name="Melyik egyesületnek vagy tagja?* (csak ennek a logója jelenik meg)") datetime = models.DateTimeField(auto_now_add=True, auto_now=False) … -
How to use django channel and celery to send messages regularly?
Below are my consumer code and tasks code. I want the task to start when the first user opens the page and establishes a channel, which begins querying data and periodically broadcasting to the corresponding group's channel. When subsequent users create channels, there is no need to start new tasks again. I have considered making the Celery task a scheduled task that broadcasts to the specified group's channel regardless of whether any user has opened the channel or not. However, I am not sure if this is a good solution. # consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from app_monitor.tasks import monitor class MonitorConsumer(AsyncWebsocketConsumer): async def connect(self): self.group = 'monitor' await self.channel_layer.group_add(self.group, self.channel_name) monitor.delay(self.group) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group, self.channel_name) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] async def send_data(self, event): print(event) await self.send(text_data=json.dumps({"data": event['data']})) # tasks.py from dbaOps.celery import app from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from django.db import connections from app_monitor.utils.sqlarea import MONITOR_SQL @app.task def monitor(group): try: with connections['tools'].cursor() as cur: cur.execute(MONITOR_SQL) data = cur.fetchall() channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(group, {'type': 'send.data', 'data': data}) except Exception as e: print(e) -
Django filter_horizontal pre-selected items
I want see in django admin filter_horizontal not all my tags, but only tags of one selected group. Example: My tags: Group Fruits: Apples, Plums, Appricots.. Group Flowers: Roses, Tulips, Asters.. I want to be able select anywhere in admin one plants group (for example "Fruits") and see in filter_horizontal tags "Apples, Plums, Appricots.." , but not "Roses.." My models: class PlantsGroups(TitleRequiredModel): is_active = models.BooleanField(default=True) ... def __str__(self): return self.title class PlantsTags(TitleRequiredModel): is_active = models.BooleanField(default=True) ... plants_group = models.ForeignKey(PlantsGroups, on_delete=models.CASCADE) def __str__(self): return self.title class PlantsTags(TitleRequiredModel): is_active = models.BooleanField(default=True) ... plants_tags = models.ManyToManyField('PlantsTags', blank=True, related_name="blabla", verbose_name='blablabla') def __str__(self): return self.title Thanks! I am novice to django, please help me :) -
Highlight entire row in Django admin list
I've been stuck on this issue for days. I have a change_list with applicants, now I want to highlight the rows of objects that have been changed recently. To do this I made a custom property: @property def has_recently_been_modified(self): return datetime.now() - self.updated_at < timedelta(days=5) Which I use in the admin.py to create a field that houses a class I need: def recently_modified(self, obj): if obj.has_recently_been_modified: return mark_safe("<span class='row_yellow'></span>") recently_modified.allow_tags = True list_display = ('custom_status','viewed', 'updated_at', 'first_name', 'last_name', 'vacancy', 'created_at', 'recently_modified') And with JS I use that class to color the row: window.onload = function () { const x = document.getElementsByClassName("row_yellow"); let i; for (i = 0; i < x.length; i++) { let ligne = x[i].parentNode; while (ligne.tagName !== "TR") { ligne = ligne.parentNode; } ligne.style.backgroundColor = "yellow"; } } Although it does color the entire row, the extra empty column at the end of the row is a real thorn in my eye. Removing it from the list_display doesn't obviously work. So my question is, is there a clever way to "hide" it? Or even a completely different method to color the row? I have tried using django-liststyle, but that seems like a broken package. I immediatly get a … -
How to test an OTP-secured Django form?
I'm building a Django application using the django_otp OTP extension, and I'm running into some issues with automated testing of forms. Specifically, despite everything I've tried, attempts to call a form decorated with otp_required results in getting shown the 'you need to enable OTP on this account' redirect page. I've made several attempts at implementing things suggested by google searches, such as this one and several others. Right now, during the TestCase __init__ I create a user with the following code: # Set up a user: self.testuser = User.objects.create(username='testuser') self.testuser.set_password('12345') self.testuser.is_superuser = True self.testuser.is_verified = True self.otp_device = self.testuser.staticdevice_set.create(name='Testdevice') self.otp_device.confirmed = True self.otp_device.save() self.testuser.save() And when using a Client object to make a request: def setup_client(self): client = Client() client.force_login(self.testuser) client.session.save() return client The failing test case is: def test_connection_create_form_no_circuit(self): testdata = baseData() client = testdata.setup_client() client_group = ClientGroup.objects.get(name='testgroup') context_id = Context.objects.get(name='testcontext').id bandwidth_id = BandwidthProfile.objects.get(name='testprofile').id conntype_id = ConnectionType.objects.get(name='testconntype').id postdata = { 'id_enabled': True, 'id_circuitless': True, 'id_debug_info': False, 'id_connectionref': 'Test 1234', 'id_customer': '321', 'id_install_address': '123 Stockton Bvd.', 'id_carrierref': 'nil', 'id_c_context': context_id, 'id_c_bandwidthprofile': bandwidth_id, 'id_c_connectiontype': conntype_id, 'id_ppp_username': 'test_conn_123', 'id_ppp_password': 'pass_54321', 'id_ipv4_address': '1.2.3.4' } response = client.post('/radius/clientgroup/%d/connection/' % client_group.id, postdata) self.assertEqual(response.status_code, 200) Rather than a 200 I'm getting a 403 and the 'You … -
What should a django view that processes the post request from esp32 look like
I have a challenge sending data from esp32 to my django server. I am using HttpClient and my site is hosted on ngrok. I have a sensor conneted to an Arduino Uno and the Arduino send sensor values to esp32 using serrial communication. I need to display these values on my django website. I had thought of using the Ethernet shield instead of esp32 but still facing te same problem, In the Ethernet shield configuratio, i need a port but my ngrok url does not have one or maybe it has but i dont know how to use it. views.py def post_entry(request): if request.method == 'POST': post_data = request.body return HttpResponse('Hey there im working') The esp32 code: #include <WiFi.h> #include <HTTPClient.h> const char* ssid = ""; const char* password = ""; void setup(){ Serial.begin(115200); delay(1000); WiFi.mode(WIFI_STA); //Optional WiFi.begin(ssid, password); Serial.println("\nConnecting"); while(WiFi.status() != WL_CONNECTED){ Serial.print("."); delay(100); } Serial.println("\nConnected to the WiFi network"); Serial.print("Local ESP32 IP: "); Serial.println(WiFi.localIP()); } void loop(){ if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status HTTPClient http; http.begin("my-url-created-from-ngrok/post-entry/"); //Specify destination for HTTP request http.addHeader("Content-Type", "application/json"); //Specify content-type header int httpResponseCode = http.POST("POSTING from ESP32"); //Send the actual POST request if(httpResponseCode>0){ String response = http.getString(); //Get the response to the request … -
best way of authentication for django rest framework [closed]
I have searched so much about different ways of authentication(JWT,Session,..) but I can't draw a conclusion which one is the best and I'm confused. I would be glad if someone has any experience. Thanks. -
Returning data to Django form for editing
I am using multiple forms which opens in modals from the same page at my Django app. I got it to work with custom functions, but now I'm a bit struggling on how to add editing functionality since I am very new to Django. Since this way working with forms is very new to me I got lost where should I provide instance that form would show already entered data for that instance. This is form variable in views.py edit_employment_form = _get_form(request, EditEmploymentForm, "edit_employment_form_pre") This is function I use to differiante between forms. (Or at least i think that this does it) def _get_form(request, formcls, prefix): data = request.POST if prefix in request.POST else None return formcls(data, prefix=prefix) This is my full view in views.py to better understand structure. Below request.method condition is variable employment_id which I am going to use to filter instance. I get that id from button in html which itself is form and returns me item id from for loop. @login_required def person_profile(request, person_id): current_user = request.user user = Person.objects.get(user=current_user) people = Person.objects.all() jobs = Job.objects.all() person = Person.objects.get(pk=person_id) employments = Employments.objects.filter(person_id=person_id).order_by("-start_date") workflows = Workflows.objects.filter(person_id=person_id).order_by("-workflow_date") sources = Sources.objects.filter(person_id=person_id).order_by("-source_date") tags = Tags.objects.filter(person_id=person_id) comments = Comments.objects.filter(person_id=person_id) person_calls = … -
How to send json data from events sent from server in Django?
I'm looking for an answer to my question, how do I send "JSON data"? For example, if I wanted to submit a discussion, it would be sent as a string, not "JSON" This is what I'm sending but I really want to send the discussion but I count the number of discussions and send it and if the number the user has is different from this number it updates the data and I see it's a bad way views.py def stream(request): def event_stream(): discussion = Discussion.objects.all() count = discussion.count() while True: time.sleep(3) yield 'data: %i\n\n' % count return StreamingHttpResponse(event_stream(), content_type='text/event-stream') template if(typeof(EventSource) !== "undefined") { var source = new EventSource("stream/"); source.onmessage = function(event) { console.log(event.data); }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events..."; } -
Error that says -: template does not exist
So , this is my first ever try with django and im currently learning about urls and views, ive been encountering the error that says "template not found " i apologize beforehand if the question is noob-ish. (here is the code for urls.py file) `""" URL configuration for views_urls project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home) ] ` (below is the code for the view.py file that i created , which exists in the same folder as the url.py file) `from django.shortcuts import render def home(request): return render(request, 'main.html')` (below is the main.html file the exists in a folder called templates) `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" … -
'Order' object has no attribute 'orderitem_set'
1 I'm trying to get the orderitem per order. The error AttributeError at /cart/ 'Order' object has no attribute 'orderitem_set' models.py class Order(models.Model): customer= models.ForeignKey(Users,on_delete=models.SET_NULL,null=True, blank=False) date_oder= models.DateTimeField(auto_now_add=True) status= models.BooleanField(default=False) transaction_id= models.CharField(max_length=100, null=True) delivery_date= models.DateTimeField(auto_now_add=True) delivered= models.DateTimeField(auto_now=True) def str(self) : return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class Order_detail(models.Model): product= models.ForeignKey(Products,on_delete=models.SET_NULL,null=True, blank=False) order= models.ForeignKey(Order,on_delete=models.SET_NULL,null=True, blank=False, related_name='order_items') quantity=models.IntegerField(default=0,null=True, blank=True) date_added=models.DateTimeField(auto_now_add=True) def get_total(self): total= self.product.pro_price * self.quantity return total View.py def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer ,status = False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0,'get_cart_items':0} context = {'items':items , 'order': order} return render(request,'app/cart.html',context) please, I cannot solve this problem -
How to solve permission error while testing drf view?
I am getting permission error AttributeError: 'WSGIRequest' object has no attribute 'authenticators' while testing my drf view. I am using djangorestframework-api-key for rest framework permission. views.py class SliderViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet): queryset = Slider.objects.all() serializer_class = SliderSerializer lookup_field = "id" test_view.py class TestSliderViewSet: @pytest.fixture def api_rf(self) -> APIRequestFactory: return APIRequestFactory() def test_get_queryset(self, slider: Slider, api_rf: APIRequestFactory): view = SliderViewSet() request = api_rf.get("/fake-url/") view.request = request assert slider in view.get_queryset() def test_get_object(self, slider: Slider, api_rf: APIRequestFactory): from rest_framework_api_key.models import APIKey api_key, key = APIKey.objects.create_key(name="my-remote-service") view = SliderViewSet() request = api_rf.get("/fake-url/") request.META['X_API_KEY'] = f'Api-Key {key}' view.request = request view.kwargs = {"id": slider.pk} assert slider == view.get_object() if I remove rest_framework_api_key.permissions.HasAPIKey from DEFAULT_PERMISSION_CLASSES test is done successfully. -
Sum of object fields in django
I have a "Bet" model, there is a total_amount field. I want that when creating a model object, 'total_amount' is the sum of the fields "rubles", "euros", "dollars". But when i create new object then 'total_amount' is 0 class Bet(models.Model): bet_id = models.AutoField(primary_key=True) event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='bet_event') user = models.ForeignKey(User, on_delete=models.CASCADE) euros = models.IntegerField(default=0) rubles = models.IntegerField(default=0) dollars = models.IntegerField(default=0) total_amount = models.IntegerField(default=0) max_amount = models.IntegerField(default=0) def save(self, *args, **kwargs): balance = {'euros', 'rubles', 'dollars'} self.total_amount = sum([value for key, value in self.__dict__.items() if key in balance]) super(Bet, self).save(*args, **kwargs) -
Django hitcount gives error AttributeError at /admin/hitcount/hit/ 'NoneType' object has no attribute '_base_manager'
AttributeError at /admin/hitcount/hit/ 'NoneType' object has no attribute '_base_manager' 'NoneType' object has no attribute '_base_manager' 43 {% if site_url %} 44 <a href="{{ site_url }}">{% translate 'View site' %}</a> / 45 {% endif %} 46 {% if user.is_active and user.is_staff %} 47 {% url 'django-admindocs-docroot' as docsroot %} 48 {% if docsroot %} 49 <a href="{{ docsroot }}">{% translate 'Documentation' %}</a> / 50 {% endif %} 51 {% endif %} 52 {% if user.has_usable_password %} 53 <a href="{% url 'admin:password_change' %}">{% translate 'Change password' %}</a> / 54 {% endif %} 55 <a href="{% url 'admin:logout' %}">{% translate 'Log out' %}</a> 56 {% endblock %} 57 </div> 58 {% endif %} 59 {% endblock %} 60 {% block nav-global %}{% endblock %} 61 </div> 62 <!-- END Header --> 63 {% block breadcrumbs %} -
Indexing SearchVector makes query slower in django ORM - PostgreSQL
I have a model with 2 string fields, the model stores around 8m of records. from django.contrib.gis.db import models from postgres_copy import CopyManager class Patent(models.Model): office = models.CharField(max_length=100) office_patent_id = models.CharField(max_length=100) type = models.CharField(null=True, blank=True, max_length=100) application_filed_date = models.DateField(null=True) granted_date = models.DateField() title = models.TextField() abstract = models.TextField(null=True, blank=True) claims_count = models.IntegerField() figures_count = models.IntegerField(null=True) sheets_count = models.IntegerField(null=True) withdrawn = models.BooleanField() objects = CopyManager() Running the following query without indexing anything runs in 425s ~ 7m from django.contrib.postgres.search import SearchVector, SearchQuery cpu_gpu_count = Patent.objects.annotate( search=SearchVector('title', 'abstract') ).filter(search=SearchQuery("CPU | GPU")).count() Indexing the SearchVector like this, in a new migration file and running the same query, gives me the same result but in 453s, which is even worse than the un-indexed timings. What's going on? from django.db.migrations import Migration, AddIndex, RunPython from django.contrib.postgres.indexes import GistIndex, GinIndex from django.contrib.postgres.search import SearchVector class Migration(Migration): dependencies = [ ("main", "0001_initial"), ] operations = [ AddIndex("Patent", GinIndex(SearchVector("title", "abstract", config="english"), name="main_patent_title_abstract_idx")) ] I have also tried adding a SearchVectorField and using a GIN index on that. Initially populate it, and then add a trigger to update it as the docs suggest but this made my database unresponsive. Even the count(*) query never finished within an hour, the … -
Multiple migrations are created everytime in django
I have a model in my app : class PutAwayProductsPosition(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE) put_position = models.CharField(max_length=50, default=0) is_put = models.BooleanField(default=False) class PutAway(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) grn = models.ForeignKey("grn.GRN", on_delete=models.CASCADE) employee_assigned = models.ForeignKey(Employee, on_delete=models.CASCADE) putaway_id = models.IntegerField(default=0) products_position = models.ManyToManyField(PutAwayProductsPosition) completely_executed = models.BooleanField(default=False) partially_executed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) scheduled_datetime = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) evertime i run makemigrations a file is created like the following in migrations class Migration(migrations.Migration): dependencies = [ ('grn', '0068_auto_20230411_0703'), ('putpick', '0033_auto_20230410_0810'), ] operations = [ migrations.AlterField( model_name='putaway', name='grn', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='grn.GRN'), ), ] even when there is no change in the model, i migrate them and then after that if i run makemigrations again this file is created in the folder, I am unable to understand the reason for this