Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inheritance in class based views
I am currently working on my first website and I'm working with class-based views because I've been told their inheritance is outstanding. Here's the code so you can make yourselves an idea of what I'm trying to do before I tell you the error I'm having. class TranslatorView(View): def translate_amino(self, codon): return self.amino_mapper.get(codon, "") def build_protein(self, 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 return protein def error_1(self, request): amino_1= self.build_protein if len(amino_1) % 3: messages.error(request, "DNA chain must be divisible by 3") return redirect('/') Basically, what I'm trying to do is to inherit the function build_protein to the def error_1. Specifically, I want to inherit the phrase parameter in the error_1 def so that the message error appears. However, it appears it's not inheriting anything at all. -
Django 3.1+: has background_task become obsolete?
With Django 3.1 finally supporting async views, has the library "Django Background Task" (pip install django-background-tasks) become obsolete? I have been using it extensively for time consuming, overnight tasks. Do you advice to migrate them? Recommendations or pitfalls? -
How to stop loading the page after clicking on an href link in html?
so this code <a href="" onclick="alert('ITEM ADDED TO WATCHLIST')">Add to your watchlist</a> When i click on the link, an alert pops up from the upper side and when i clicks the OK button, it reloads the page .I want it, not to reload the page after clicking and just stays right where the page currently is. -
django Cast function always sets UTC timezone
When I use: annotate(new_datetime=Cast( TruncHour('old_datetime) + timedelta(days=1), output_field=DateTimeField() )) TruncHour return a datetime in my timezone and after Cast, new_datetime's value will be in my timezone but with UTC tzinfo. How can I set custom tzinfo for Cast function in this case? -
ValueError: Cannot assign must be an instance in Django
I am new to django and I'm trying to insert some data into the database through a form but I am getting an error while inserting the data. How can I solve this issue? I have these models which are connected together: models.py class Major(models.Model): major_cd = models.IntegerField(primary_key=True) description = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'major' class Percentages(models.Model): # major_cd = models.IntegerField(primary_key=True) major_cd = models.OneToOneField( Major, on_delete=models.CASCADE, primary_key=True, db_column='major_cd' ) perc = models.FloatField() class Meta: managed = False db_table = 'percentages' this is my from: per.html <form id="addPercentage" action=""> <div class="form-group row"> <div class="form-group col-md-2"> <input class="form-control" type="number" name="major_cd" placeholder="Major Code" required min=1000 max=9999> </div> <div class="form-group col-md-2"> <input class="form-control" type="number" name="perc" placeholder="Percentage" required> </div> </div> <div class="form-group col-md-2" style="padding-right: 2%;"> <button class="btn btn-info form-control" type="submit">ADD</button> </div> </form> script: $("form#addPercentage").submit(function() { var majorCodeInput = $('input[name="major_cd"]').val().trim(); var perc_Input = $('input[name="perc"]').val().trim(); if (majorCodeInput && perc_Input) { // Create Ajax Call $.ajax({ type: 'POST', url: '{% url "create-percentages" %}', enctype: 'multipart/form-data', data: { 'major_cd' : majorCodeInput, 'perc' : perc_Input, }, dataType: 'json', success: function (data) { if (data.Perc) { appendToPerTable(data.Perc); // Funcion to append data } } }); } else { alert("All fields must have a valid value."); … -
Failed to deploy my django project on heroku
I was going to deploy my django project on heroku, but I meet the error, I really have no idea how to do, please help, thank you a lot for your checking and answer in advance! -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_696b7f56_/lonelyisland/settings.py", line 24, in <module> SECRET_KEY = os.environ['SECRET_KEY'] File "/app/.heroku/python/lib/python3.7/os.py", line 681, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you … -
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 ??