Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get max date for each month in query
I have a simple model with the fields date(DateTimeField) and value(IntegerField). I would like the query this model for the value of the last day for each month (see example output) date value 2020-01-01 55 2020-01-02 12 2020-01-03 13 ... 2020-01-31 34 ... 2020-02-01 14 2020-02-02 54 2020-02-03 16 ... 2020-02-28 23 ... 2020-03-01 16 2020-03-02 23 2020-03-03 16 ... 2020-03-31 7 Desired output: date value 2020-01-31 34 2020-02-28 23 2020-03-31 7 So far, I've managed to to this (But it involves quering the database alot, so I'd prefer a less database intensive solution) dates = MyModel.objects.annotate( month=TruncMonth('date') ).distinct() for date in dates: end_value = MyModel.objects.filter(date__month=date['month'].month).latest('date') print(end_value) -
Caching a whole page in PWA
While caching whole page in PWA using service worker, as we know we need to provide the route of that particular page. Here i am caching the home page of my website. Thus i pass / to be cached and it works fine. Then in my service worker, i wrote some code to first search in cache when a request is made for an asset and if is not found go to the server. Here is the code; self.addEventListener('fetch', evt => { evt.respondWith( caches.match(evt.request).then(casheRes => { return casheRes || fetch(evt.request); }) ) }); Everything works fine and i am 100% sure that there is no problem in the code but the problem is with what it returns. As my code first checks the cache to return something,here the home page, but the home page is completely different when a user is logged in and logged out. Cache stores the logged out home page which is completely correct but when i login, i get redirected to the / route as per my code but it again shows the same home page as that is stored in the cache. How to solve such problem? -
Call a function on Friday of every week and also filter a model by date range of next week in Django
I have a django application wherein I should call a mailer function on Friday of every week. Also I should get the data of a model based on the dates from saturday to next friday. How can I do this using python's in built functions? if today is "Friday": mailer_function() def mailer_function(): model_data = Model.objects.filter( birthday__range=["tomorrow(i.e., Saturday's date)", "next friday's date"], anniversary__range=["tomorrow(i.e., Saturday's date)", "next friday's date"] ) Here I should get the model_data whose birthday or anniversary dates are in the next week. How can I get the values of dates? -
No value for parameter
I'm currently coding a function that goes like this. def build_protein(self, request, phrase): protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 if len(phrase) % 3: messages.error(request, "DNA chain must be divisible by 3") return redirect('/') return protein To do the message.error, I've been following this tutorial https://docs.djangoproject.com/en/3.1/ref/contrib/messages/. It says that I have to put the request in order to make the code work. However, if I write the request parameter in the function, this error appears: No value for argument 'phrase' in method call. It looks like it's a pylint error no value for parameter. What this means, is that the phrase parameter isn't being detected somehow. How can I solve this error -
I just to fetch the updated status
Hey i have created a system where after payment it will show PAID. I have a button to proceed to payment but when the payment is successful the button will turn to hidden.Like when the status is paid the button will be hidden Here is my model.py class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.CharField( max_length=100, blank=True, null=True, default="Unpaid") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) Here is my Views.py : def get(self, request, id): user_orders = Order.objects.get(pk=id) args = {'user_orders': user_orders} return render(self.request, 'Home/invoice.html', args) def post(self, request, *args, **kwargs): customer = Customer.objects.get(id=request.session['customer']['id']) user_orders = Order.objects.get(pk=kwargs['id']) total = user_orders.total balance = request.session['customer']['coin'] if balance >= total: balance = balance - total customer.coin = balance customer.save() Order.objects.filter(pk=kwargs['id']).update( status='PAID' ) request.session['customer']['coin'] = balance request.session.save() return redirect('/orders') return HttpResponse("Insufficient Balance") -
Is there an alternative to Django crispy form for rendering Django form?
Since I started to develop Django apps one year ago, I've use Django crispy form for rendering my forms. For my new project, I want to change form rendering to look more like a 'desktop application'. This project will be a electronic data capture tool, with many forms with lots of fields. I have found this design on Codepen by Rijdzuan Sampoerna I found very elegant and professionnal. So I would like a form rendering closed to this design. I want to be able to have multiple fields in a same line (not only one column), with fields smaller,... Before defining all css by myself, I wonder if there is a django form rendering I could use as crispy? any suggestions? -
DRF wrong throttling trigger
I have a APIView where I have set throttling for staff users. I have added view name in the scope as well. Here is the code snippet: permissions.py class IsStaffUser(BasePermission): def has_permission(self, request, view): return request.user and request.user.is_authenticated and request.user.is_staff views.py from rest_framework.views import APIView from myprj.somewhere.permissions import IsStaffUser from myprj.somewhere.throttling import MyThrottleRate class BaseView(APIView): permission_classes = (IsStaffUser,) class MyView(BaseView): throttle_classes = (MyThrottleRate,) def get(self, request, pk): # some stuff throttling.py from rest_framework.throttling import UserRateThrottle class BaseThrottling(UserRateThrottle): cache_format = 'throttle_%(scope)s_%(ident)s_(view_name)s' def get_rate(self): """ Determine the string representation of the allowed request rate. """ try: return self.THROTTLE_RATES[self.scope] except KeyError: msg = "No default throttle rate set for '%s' scope" % self.scope raise ImproperlyConfigured(msg) def get_cache_key(self, request, view): if request.user.is_authenticated: ident = request.user.pk view_name = view.request.resolver_match.func.__name__ cache_format = self.cache_format % { 'scope': self.scope, 'ident': ident, 'view_name': view_name } return cache_format else: raise APIException('You are not authorised') class MyThrottleRate(BaseThrottling): THROTTLE_RATES = { 'user': '20/hour', } I have set the rate to be 20/hour, but I am getting status code 429 on the first request of the day itself. I looked for the solution but couldn't find solution. Please help me to locate the error. Note: We are using apache with mod_wsgi -
Combining radio-button with a dropdown form
How can I combine radio-button inside a dropdown select form. I'll be grateful for your help. My codes: index.html <div class="card-header"> <div class="container"> <div class="row"> <form class="col-md-4"> <select class="form-control select2" > <option>Select Major Head</option> {% for major in majors %} <option>{{ major.pk }}: {{ major.description }}</option> {% endfor %} </select> <button type="button">Display!</button> </form> </div> </div> </div> -
how do i run this filter in Django?
i want to write a filter that gets the days with highest order or purchase and get the result as Monday , Tuesday, Saturday etc. -
How to get a request in post_save function
Hello I am using Post_save signal for sending a notification from the model .... But I am getting an error like this "sending_notification() missing 1 required positional argument: 'request' " @receiver(post_save, sender=Plan) def sending_notification(request, sender, instance,created, **kwargs): if created: notify.send(request.user, recipient = request.user, verb = "Some messages") -
Djangos m2m_changed trigger doesn't trigger properly
I have a model that looks as follows and I wish to trigger a method every time the user_ids field get's changed. Using the post_save signal obviously didn't do anything, as ManyToMany relationships are special in that way. class Lease(models.Model): unit = models.ForeignKey(Unit, on_delete=models.CASCADE) user_ids = models.ManyToManyField('user.User') Using the m2m_changed trigger as follows also didn't do anything, which got me puzzled. I don't really understand what is wrong with this code also having tried to leave the '.user_ids' out. There are no errors or anything, it just doesn't trigger when the user_ids from the Lease model are changed. @receiver(m2m_changed, sender=Lease.user_ids) def update_user_unit(sender, instance, **kwargs): print('Test') -
Is there a way to add custom fields in Django Rest Framework
I am creating a rest API for my Django-blog project and I have models Post and Post like models as you below Create your models here. class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField() approved = models.BooleanField(default=False) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField( default=timezone.now, blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.text[0:100] class PostLike(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) And I have a post serialiser like class PostSerializers(ModelSerializer): likes_count = serializers.IntegerField(read_only=True) class Meta: model= Post fields = ['id','text','author', 'approved','created_date', 'likes_count' ] I wish the likes_count to be count for the PostLike objects with the post of the queried post. What is the right way to implement it? -
django signals pre_save when file is uploaded
Can I test in pre_save or post_save, if a file was uploaded / changed? Example: class Item(models.Model): name_123 = models.CharField(max_length=255) photo = models.ImageField() @receiver(pre_save, sender=Item) def my_callback(sender, instance, *args, **kwargs): if NEW photo was uploaded: resize it; I dont want to resize the image, if only the name_123 changed, but I want to resize it when a new Item was created and when the image changed (even when the same image with the same file name was uploaded. If I would use a front end CreateView or something similar, I could have check if the form_data contains file data but I want to use it in general (django admin too). Thanks -
Custom Django Logging Filter for a Particular API
In my app, there is this API named 'UserChangeWorkScheduleViewSet' where its uri is 'host/api/v1/workSchedule' I have been trying to make a custom logging filter that would send me an error log whenever a user causes 400 status code. Below is the UserChangeWorkScheduleViewSet in 'workschedule.py': class UserChangeWorkScheduleViewSet(viewsets.ModelViewSet): queryset = UserChangeWorkSchedule.objects.all() serializer_class = UserChangeWorkScheduleSerializer permission_classes = (IsAuthenticated,) def create(self, request, *args, **kwargs): UserChangeWorkSchedule.objects.filter(user=request.user.id).update(status=0) is_many = isinstance(request.data, list) if not is_many: request.data['user'] = request.user.id return super().create(request) else: for data in request.data: data['user'] = request.user.id serializer = self.get_serializer(data=request.data, many=True) if serializer.is_valid(raise_exception=True): self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) else: print('UserChangeWorkScheduleViewSet', request.user.id, serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is my customlog.py: import logging class UserChangeWorkScheduleViewSet400(logging.Filter): def filter(self, record): record.levelname == 400 record.filename == "workschedule.py" return True And here is the logging in the settings from api import customlog LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, 'only_400_from_workschedule': { '()': customlog.UserChangeWorkScheduleViewSet400 }, }, 'formatters': { 'simple_trace': { 'format': '%(asctime)s %(levelname)s %(filename)s %(funcName)s %(message)s', } }, 'handlers': { 'telegram': { 'class': 'telegram_handler.TelegramHandler', 'token': '1489551033:AAHbIvspcVR5zcslrbrJ9qNK2yZ1at0yIMA', 'chat_id': '-429967971', 'formatter': 'simple_trace', } }, 'loggers': { 'django.request': { 'handlers': ['telegram'], 'level': 'ERROR', 'propagate': True, }, }, } I intentionally sent a bad request to raise … -
Unknown column 'distance' in 'where clause'
I'm new to the Django rest framework. I want to find users in the database that have the shortest distance to the given coordinates. This is my code: User.objects.extra( select={ 'distance': "POW(69.1 * (latitude - %s), 2) + POW(69.1 * (%s - longitude) * COS(latitude / 57.3), 2)" }, select_params=[latitude, longitude], where=[ "is_superuser = false", "not id = %s", "latitude is not null", "longitude is not null", "distance < 25" ], params=[current_user_id] ) .values_list('id', 'distance') and exception: "Unknown column 'distance' in 'where clause" -
I have a URL Shortening Service, I want to track on which day the short url was clicked. Basically I Want To Track Views Per Day For Analytics
I have a URL Shortening Service, I want to track on which day the short_url was clicked. So I can get data of views per day. I am using django. I have created url shortener service. URL SHORTNERE MODEL: from django.db import models from django.contrib.auth.models import User # Create your models here. from authentication.models import Profile class ShortenURL(models.Model): user = models.ForeignKey( Profile, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=70, null=True, blank=True) original_url = models.URLField(max_length=2048, null=True, blank=True) short_url = models.CharField(max_length=7, null=True, blank=True) clicks = models.IntegerField(default=0, null=True, blank=True) date_created = models.DateTimeField( auto_now_add=True, null=True, blank=True) def __str__(self): return f"{self.name} By {self.user}" Profile Model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField( User, related_name='profile', on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) bio = models.TextField(max_length=1500, null=True, blank=True) location = models.CharField(max_length=30, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) limit = models.PositiveIntegerField(default=10, null=True, blank=True) # For Guest User device = models.CharField(max_length=50, null=True, blank=True) profile_picture = models.ImageField( upload_to='ProfilePic/', null=True, blank=True) def __str__(self): if self.user: return "%s's profile" % self.user else: return "%s's profile" % self.device @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.get_or_create(user=instance) user_profile, created = Profile.objects.get_or_create(user=instance) user_profile.save() Please … -
No value for argument 'phrase' in method call
I am currently working on a Django website. However, I am experiencing some errors with the parameters of the function. I know that self and request have to go in this order. However, the phrase parameter doesn't get recognized because when I run the program, it appears this error: No value for argument 'phrase' in method call Here's the code and where the error appears: def build_protein(self, request, phrase): #argument phrase doesn't get detected protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 if len(phrase) % 3: messages.error(request, "DNA chain must be divisible by 3") return redirect('/') return protein Does anyone know how to solve this? -
module 'django.db.models' has no attribute 'model'
enter image description hereI am very new to django and i just got an error (module 'django.db.models' has no attribute 'model') while creating a website for my project . can anyone help me to resolve these issue ? -
How to filter Django queryset by model property?
I have a method in my django app model like below : @property def invoice_id(self): """ Represent the invoice object in __str__ format BELLA-17-08-20-2 :return: """ day_list = [] invoice_list = Invoice.objects.filter(timestamp__year=self.timestamp.year, timestamp__month=self.timestamp.month, timestamp__day=self.timestamp.day).all() for invoice in invoice_list: day_list.append(invoice.id) position = 0 for i in day_list: if i == self.id: invoice_id = 'BELLA-' + self.timestamp.strftime("%d-%m-%y") + '-' + str(position + 1) return invoice_id position += 1 I want to filter in my views.py like : queryset = Invoice.objects.filter( Q(.......) ) How can I do this ?? Any Suggestion ?? -
ValueError: The view users.views.logout_user didn't return an HttpResponse object. It returned None instead
I am building a blog app in django. But, when I write a function for logging users out, I get this traceback error: Internal Server Error: /users/logout/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response self.check_response(response, callback) File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 309, in check_response "instead." % name ValueError: The view users.views.logout_user didn't return an HttpResponse object. It returned None instead. My logout_user view function is only two lines, so I can't seem to understand the error. Here is my view function: @login_required def logout_user(request): logout(request) Can anyone help me out? -
UNIQUE constraint failed: store_order.id
i have created a payment system so after successful payment the orders status will change to PAID Here is my models.py : class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.CharField(max_length=100, null=True, default="Unpaid") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) Here status field has been set to unpaid but when payment is successful it will show PAID For that i tried this : def post(self, request, *args, **kwargs): customer = Customer.objects.get(id=request.session['customer']['id']) print(customer) user_orders = Order.objects.get(pk=kwargs['id']) # index = Order.objects.get(customer=customer) # print(index.total) total = user_orders.total print(total) balance = request.session['customer']['coin'] print(balance) if balance >= total: balance = balance - total # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer.coin = balance customer.save() user_orders.status = "PAID" user_orders.save() request.session['customer']['coin'] = str(balance) return HttpResponse("Remaining balance: " + str(balance)) return HttpResponse("Insufficient Balance") But getting this error : UNIQUE constraint failed: store_order.id -
How to create instance with pre-populated ChoiceField in form
This is my forms.py. I want to create instance with default 'V' choice into my model. So instance was created, but with choice 'A', which i provided in model for default. class VideoForm(forms.ModelForm): theory_type = forms.ChoiceField(choices=quests.StageTheories.THEORY_TYPE) class Meta: model = quests.StageTheories fields = ['title', 'youtube', 'stage'] class StageTheories(models.Model): THEORY_TYPE = ( ('Q', 'Quiz'), ('A', 'Article'), ('V', 'Video'), ) stage = models.ForeignKey(to=Stages, on_delete=models.CASCADE, db_column="stage_id",verbose_name="Этап", ) title = models.CharField(max_length=47, db_column="title", verbose_name="Заголовок теории",) text = models.TextField(db_column="text", verbose_name="Текст теории", null=True, blank=True,) youtube = models.URLField(db_column="youtube", verbose_name="Ссылка на youtube", null=True, blank=True,) sortOrder = models.PositiveIntegerField(null=True, blank=True, db_column="sort_order", verbose_name="Порядковый номер", ) theory_type = models.CharField(max_length=1, choices=THEORY_TYPE, default='A') class AddVideoView(CreateView): model = quests.StageTheories form_class = VideoForm success_url = '/' template_name = 'add_video.pug' def get_initial(self): initial = super().get_initial() initial['stage'] = quests.Stages.objects.get(id=self.kwargs['pk']) initial['theory_type'] = 'V' return initial Is initial value not going for form data? -
Django/Python zlib Compress Json - Uncompress JS Client Size
I'm compressing json in Python using the following code: chartDataListJsonCompressed = zlib.compress(str.encode(chartDataListJson)) Then I send the data to client-side using Httpresponse (convert it to string as well): return(HttpResponse(str(chartDataListJsonCompressed))) On Ajax client side I'm trying to convert this compressed string data back to string using the pako library: success: function (data) { //Convert string data to char data var charData = data.split('').map(function(x){return x.charCodeAt(0);}); //Convert char data to array var binData = new Uint8Array(charData); // Pako - inflate bin data var d = pako.inflate(binData); // Convert gunzipped byteArray back to ascii string: var strData = String.fromCharCode.apply(null, new Uint16Array(d)); } Unfortunately I get the error: Uncaught incorrect header check Thus, I'm obviously doing something wrong. I just cannot get my finger on it. Any ideas? -
How to use create function instead of perform_create in ListCreateApiView in django rest framework
I am trying to create a booking api for a website. For this, I used perform_create function in ListCreateApiView. But, it was someone else who helped me and told me to use perform_create function. But, I was thinking, it should be possible using create function and is a right approach rather than perform_create function. Also, I don't really know the difference between these two functions and don't really know when to use which. Here is my view: class BookingCreateAPIView(ListCreateAPIView): permission_classes= [IsAuthenticated] queryset = Booking.objects.all() serializer_class = BookingSerializer def perform_create(self, serializer): # user = self.request.user package = get_object_or_404(Package, pk= self.kwargs['pk']) serializer.save(user=self.request.user,package=package) Here is my serializer: class BookingSerializer(serializers.ModelSerializer): # blog = serializers.StringRelatedField() class Meta: model = Booking fields = ['name', 'email', 'phone', 'bookedfor'] Here is my model: class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package') name = models.CharField(max_length=255) email = models.EmailField() phone = models.CharField(max_length=255) bookedfor = models.DateField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) -
Django / MySQL / Python Programming Error ( 1064)
when I run python manage.py migrate I keep getting the following error. django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'None) NOT NULL, user_id_id integer NOT NULL)' at line 1") I'm running Python 3.8.6, and mysqlclient 2.0.1 and Django 3.1.3. Model from ..assets.provinces import PROVINCE_CHOICES from ..assets.industries import INDUSTRY_CHOICES from django.contrib.auth.models import User class GrantProfile(models.Model): user = models.ForeignKey(User, models.SET_NULL, blank=True, null=True) province = models.CharField( max_length=2, choices=PROVINCE_CHOICES, help_text="Province your organization is based out of" ) company_size = models.IntegerField(help_text="Company size") industry = models.CharField( max_length=150, choices=INDUSTRY_CHOICES, help_text="Industry your organization is part of." ) class Meta: db_table = "grantprofiles" View # Grant Profile View from rest_framework import viewsets from ..serializers.grantprofile import GrantProfileSerializer from ..models.grantprofile import GrantProfile class GrantProfileView(viewsets.ModelViewSet): serializer_class = GrantProfileSerializer queryset = GrantProfile.objects.all() Admin from django.contrib import admin from ..models.grantprofile import GrantProfile # Grant Profile Admin class GrantProfileAdmin(admin.ModelAdmin): list_display = ('user_id', 'province', 'company_size', 'industry') admin.site.register(GrantProfile, GrantProfileAdmin) Serializer from django.contrib import admin from ..models.grantprofile import GrantProfile from rest_framework import serializers from ..models.grantprofile import GrantProfile class GrantProfileSerializer(serializers.ModelSerializer): class Meta: model = GrantProfile fields = ('user_id', 'province', 'company_size', 'industry') I'm not sure if I'm missing something?