Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting Django to CosmosDB
Currently in my settings i have: DATABASES = { 'default': { 'ENGINE': env.str("SQL_ENGINE"), # djongo is set here 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': env.str("SQL_HOST"), 'name': env.str("SQL_NAME"), 'port': env.int("SQL_PORT"), 'username': env.str("SQL_USERNAME"), 'password': env.str("SQL_PASSWORD"), }, 'SSL': True }, } I'm still not able to make migrations, the following error is thrown when i run makemigrations . Error: raise ServerSelectionTimeoutError pymongo.errors.ServerSelectionTimeoutError -
Detail of Order/Cart with annotate() [django]
I have a models: class Product(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) slug = models.SlugField() description = models.TextField() image = models.ImageField() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) products = models.ManyToManyField(Products, through='OrderItem', related_name='orders') being_delivered = models.BooleanField(default=False) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='order_items') quantity = models.IntegerField(default=1) And I have views for for creating Order and OrderItems attached to Order. I need views for cart/order_detail: what I do: def cart_detail(request): order = Order.objects.filter(user=request.user) order_item = OrderItem.objects.filter(order=order).annotate(???) return render(request, 'cart/cart_detail.html', {'order':order, 'order_item':order_item}) I need help on how to correctly display in the template - the quantity, units of the Product, the price per unit, the total price. Please, any help would be helpful. Any links or code snippets. -
Django ModelAdmin not working with custom field method
I'm trying to write a custom method to ovveride the default viewing of a field in ModelAdmin, a described here: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/ So this should work: @admin.register(Contract) class ContractDataAdmin(admin.ModelAdmin): list_display = ("name", "status", "date_end") list_filter = ('name','status', "date_end", "headquarters_access_list") fields = ("name", "status", "date_start", "date_end", "manager_list", "buyer", "get_document_list_field", "headquarters_access_list") @admin.display(empty_value='???') def get_document_list_field(self, obj): return "\n".join([c.name for c in obj.document_list.all()]) Where the model is: class Contract(models.Model): class Meta: verbose_name = _('Contract') verbose_name_plural = _('Contracts') name = models.CharField(max_length=255, help_text=_('Contract name'), verbose_name=_('contract name')) status = models.CharField(max_length=255, default=ContractStatus.OPEN, choices=ContractStatus.choices(), help_text=_('Status'), verbose_name=_('Status')) date_start = models.DateField(editable=True, help_text=_('Start date'), verbose_name=_('Start date')) date_end = models.DateField(editable=True, help_text=_('End date'), verbose_name=_('End date')) manager_list = models.ManyToManyField(User, blank=True, help_text=_('Manager list'), verbose_name=_('Manager list')) buyer = models.OneToOneField(CompanyData, # Committente related_name="buyer", on_delete=models.RESTRICT, default=None, null=True, auto_created=False, help_text=_('Buyer'), verbose_name=_('buyer')) headquarters_access_list = models.ManyToManyField(Headquarters, blank=True, help_text=_('Headquarters access list'), verbose_name=_('Headquarters access list')) contractor_list = models.ManyToManyField(CompanyData, blank=True, help_text=_('Contractors list'), verbose_name=_('Contractors list')) staff_list = models.ManyToManyField(UserData, blank=True, help_text=_('Staff list'), verbose_name=_('Staff list')) vehicle_list = models.ManyToManyField(VehicleData, blank=True, help_text=_('Vehicle list'), verbose_name=_('Vehicle list')) document_list = models.ManyToManyField(Document, blank=True, help_text=_('Document list'), verbose_name=_('Document list')) When going to the chagne page of the model (/admin/common/contract/1/change/) I get the following error: Traceback (most recent call last): File "C:\Users\gianluca.romanin\AppData\Local\pypoetry\Cache\virtualenvs\kdocweb-1PRTDUa5-py3.9\lib\site-packages\django\contrib\admin\options.py", line 710, in get_form return modelform_factory(self.model, **defaults) File "C:\Users\gianluca.romanin\AppData\Local\pypoetry\Cache\virtualenvs\kdocweb-1PRTDUa5-py3.9\lib\site-packages\django\forms\models.py", line 563, in modelform_factory return type(form)(class_name, (form,), … -
Django TypeError: got an unexpected keyword argument 'model_name'
While coding a Django signal, I am getting a TypeError: got an unexpected keyword argument 'model_name'. From the code, I expected to get the 'Payment_record' function triggered when a 'Payment' is made. Here is the code. models.py class Payment(models.Model): paid_by = models.CharField(max_length=200) student_name = models.ForeignKey(Student, on_delete=models.CASCADE) payable_towards = models.CharField(max_length=200, choices = payable_towards, default = "tuition_fee") payment_date = models.DateTimeField(default=timezone.now) amount_paid = models.IntegerField(blank=False, null=True) account_name = models.ForeignKey(Account, on_delete=models.CASCADE, default=70) receipt_number = models.IntegerField(blank=False, null=True, unique=True) name = models.ForeignKey(Staff, on_delete=models.CASCADE, related_name="pay_received_by",) def __str__(self): return str(self.student_name) # signal to add payment to account class Payment_record(models.Model): payment_date = models.DateTimeField(default=timezone.now) student_name = models.ForeignKey(Payment, on_delete=models.CASCADE, related_name="pay_date_record",) balance = models.IntegerField(blank=False, null=True) # record_history = payment_status = models.CharField(max_length=200, choices = payment_status, default = "underpaid") def __str__(self): return str(self.student_name) ..................................... apps.py from django.apps import AppConfig class FinancesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'finances' def ready(self): import finances.signals ...................................... signals.py from .models import Payment_record, Payment from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Payment) def create_payment_record(sender, instance, created, **kwargs): if created: Payment_record.objects.create(Payment=instance) @receiver(post_save, sender=Payment) def save_payment_record(sender, instance, **kwargs): instance.Payment_record.save ...................................... I have also attached the screenshots for the above code snippets. What could be the problem and how do I solve it? Or better still, with the 2 models, how can … -
How can I choose which choice to show up in django form field?
I am trying to dynamically change the viewable choices in a django form choice field depending on the user. Here is my form: SubmitForm(forms.ModelForm): class Meta: model = Lesson fields = ( "status", ) Here is my models.py for Lesson: CLASS_STATUS = ( ('Attended', 'Attended'), ('Absent', 'Absent'), ('Teacher Postponed', 'Teacher Postponed'), ('Student Postponed', 'Student Postponed'), ) status = models.CharField( max_length=30, choices=CLASS_STATUS, null=True, blank=True, ) So, basically I want to be able to select which choices to show for each type of user. In order to do this, I hope you guys could also show how I could access the request.user information in my form. Thank you, and please ask me any questions you have. -
post request 413 Error django with gunicorn
class test(BaseListView): def post(self,request): data=json.loads(request.body.decode('utf-8')) url = 'other server API' res=requests.post(url, json=json.dumps(data)) print(res.status_code) return 'ok' This is the code. 'data' i put as a request body to send this data to other server. and when i printed res.status_code i got 413 error. It's because the data size is big.(1GB) the size of the request body depends on the platform or webserver. I think this is the problem in gunicorn. i found this solution on docs but i don't know how to use it. https://docs.gunicorn.org/en/latest/settings.html#limit-request-line If anyone has other solution or how to use --limit-request-line INT command line i would be thankful. Currently, i put my gunicorn.service on /etc/systemd/system and to start the server i command "sudo systemctl restart gunicorn" this is how gunicorn.service looks like [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/django-boilerplate/mysite ExecStart=/home/ubuntu/django_env/bin/gunicorn \ --workers 3 \ --bind 0.0.0.0:8000 \ mysite.wsgi:application [Install] WantedBy=multi-user.target -
Django: how to access field attributes in a template
I have a form for updating an object with an image field styled with bootstrap. And right now it just looks ugly: is there a way to access individual html elements like form.image.label_tag, so i can style them? I would definitely like to remove this line break in the middle. django template: <div class="input-group"> <span class="input-group-text"> <label for="{{ form.image.auto_id }}"><i class="{{ form.image.label }}"></i></label> </span> {{ form.image|add_class:"form-control" }} </div> html i am getting: <div class="input-group"> <span class="input-group-text"><label for="id_image"><i class="bi bi-image"></i></label></span> Currently: <a href="/media/dishes/27.jpg">dishes/27.jpg</a> <input type="checkbox" name="image-clear" id="image-clear_id"> <label for="image-clear_id">Clear</label> <br> Change: <input type="file" name="image" accept="image/*" class="form-control" id="id_image"> </div> -
NginX location management with Django&Vue.js setup
I have a Django backend and Vue.js frontend served by the same machine. I want a specific path to be directed to the django API and admin panel, while the rest should load Vue index.html and be passed to Vue router. My problem is, that while the base path is passed on to Vue.js, and my selected path does go through to Django, any other path results in 404, which means that if I want to revisit a path generated though Vue router, it's impossible to do so. I figured the problem must be somewhere in the NginX config file: # the upstream component nginx needs to connect to upstream myproject { server unix:///tmp/myproject .sock; } server { listen 80; listen [::]:80; server_name serverurl.com; return 301 https://serverurl.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; ssl_certificate /home/projects/myproject/ssl/ANY.serverurl.com.crt; ssl_certificate_key /home/projects/myproject/ssl/ANY.serverurl.com.key; server_name serverurl.com www.serverurl.com; access_log /home/projects/myproject/logs/nginx_access.log; error_log /home/projects/myproject/logs/nginx_error.log; location / { root /home/projects/insights/vue/dist; try_files $uri $uri/ /home/projects/myproject/vue/dist/index.html =404; } location /backend/ { include /etc/nginx/uwsgi_params; uwsgi_pass myproject; } location /static/ { alias /home/projects/myproject/static/; } location /media/ { alias /home/projects/myproject/media/; } } So the "/" path results in correctly rendering Vue index.html And "/backend/" correctly loads django urls But, for example, if the … -
How to save file to particular folder?
I have the following code: urls.py: urlpatterns = [ ... url(r'^upload_file', FileFieldFormView.as_view(), name='upload_file'), url(r'^success', lambda request: HttpResponse('Hello World!'), name='hello_world'), ] upload_file.py: from django.views.generic.edit import FormView from ..forms import FileFieldForm import ipdb def handle_uploaded_file(f): ipdb.set_trace() with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) class FileFieldFormView(FormView): form_class = FileFieldForm template_name = 'reports/upload_file.html' # Replace with your template. success_url = '/reports/success' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: print("hello") handle_uploaded_file(f) return self.form_valid(form) else: print("invalidated") return self.form_invalid(form) forms.py: from django import forms class FileFieldForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) and upload_file.html template: {% extends "core/layout.html" %} {% block content %} <br/> <h3>{{ title }}</h3> <br/> {% block controls %}{% endblock %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form.as_table }} <button type="submit">Upload</button> </form> {% endblock %} In "files" variable in upload_file.py I get the list of temporary uploaded files and I just want to save them all to particular folder, preliminary checking their type. How can I do it in handle_uploaded_file function? -
How to make the integer field in django models accept float point numbers
Hey I am making an application but requires me to accept input ask percentages and floats. Currently I can only accept input as integers, but I wanted to make it accept floats as well. Thanks -
How to add pagination to a django ReadOnlyModelViewSet or ListAPIView?
I have a Django Restframework project. Here is my view: class JobView(viewsets.ReadOnlyModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer filter_backends = [filters.OrderingFilter, DjangoFilterBackend, filters.SearchFilter] search_fields = [...] ordering_fields = ['jobId'] ordering = ['-jobId'] filterset_fields = ['jobId', 'status'] pagination_class = StandardResultsSetPagination and my pagination class: class StandardResultsSetPagination(LimitOffsetPagination): page_size = 1 The view is registerd in a router: router.register(r'jobs', JobView) The problem is, it does not paginate at all. It just ignores the pagination_class attribute. I also tried: class JobView(generics.ListAPIView) And registered the view without the router. But the problem is the same. It does not paginate and just returns a json list with all jobs. How can achieve pagination in this view without defining it for the project in settings.py globally? -
show specific data in a table django
I have a webpage where it currently shows all the data in 1 page which I do not want it, I want to show a specific data based on the status, like if the status is reception, only the reception status will be shown. This is the current page that I have which it will show all the data which I do not want. What I wanted is this, all the status that is reception will only appear at the logistic page. views.py @login_required(login_url='login') def gallery(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q( Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q(status__icontains=search_post) | Q(serialno__icontains=search_post)) if not allusername: allusername = Photo.objects.all().order_by("-Datetime") else: allusername = Photo.objects.all().order_by("-Datetime") part = request.GET.get('sortType') valid_sort = ["partno", "serialno", "Customername", "status"] # Sort the data if (part is not None) and part in valid_sort: allusername = allusername.order_by(part) page = request.GET.get('page') paginator = Paginator(allusername, 6) try: allusername = paginator.page(page) except PageNotAnInteger: allusername = paginator.page(1) except EmptyPage: allusername = paginator.page(paginator.num_pages) context = {'allusername': allusername, 'query': search_post, 'order_by': part} return render(request, 'photos/gallery.html', context) gallery.html {% extends "logisticbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { … -
find users function of availabilities
I have an issue with my projet and related models. Suppose a really basic user model: class User(AbstractUser): """Default user model.""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None email = models.EmailField(unique=True) In my app, users have a calendar: class Calendar(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) and then define their availabilities: class Availability(models.Model): calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE) date = models.DateField() It was a kind model because in the profile page I can retrieve all availabilities function of a calendar. But, I have an issue when I want to find all users mathing a given availabities. How can I retrieve them ? When playing with others parameters, I use: users = User.petsitters.filter( Q(zipcode=selected_zipcode), Q(proposals__pk=selected_service) ) -
ValueError: Field 'bid' expected a number but got ' '
I am making an Auction website using Django. When is use Migrate command it gives an error "ValueError: Field 'bid' expected a number but got ''.". The code of the models.py file is: from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.base import Model from django.db.models.deletion import CASCADE from django.db.models.fields import CharField from django.utils import timezone class User(AbstractUser): pass class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return f'{self.category}' class AuctionListing(models.Model): item_name = models.CharField(max_length=100) item_image = models.ImageField(upload_to="products", null=True, blank=True) detail = models.TextField() price = models.IntegerField() last_bid = models.ForeignKey('Bid', on_delete=models.CASCADE, blank=True, null=True, related_name='lst') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='publisher_listing', null=True, blank=True) watchers = models.ManyToManyField(User, blank=True, related_name='watched_list') pub_date = models.DateTimeField(null=True) deadline = models.DateTimeField(null=True) list_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name='sortion') closed = models.BooleanField(default=False) def __str__(self): return f'{self.item_name} - {self.price}' class Bid(models.Model): p_bid = models.IntegerField() user = models.ForeignKey(User, on_delete=CASCADE) auction = models.ForeignKey(AuctionListing, on_delete=CASCADE) bid_date = models.DateTimeField(timezone.now) def __str__(self): return '%s' % (self.bid) class Comment(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) com = models.TextField() pub_date = models.DateField() com_item = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name='get_comment') def __str__(self): return f'{self.user} - {self.pub_date}' The code of views.py is: from django.contrib.auth import authenticate, login, logout # from django.contrib.auth.decorators import login_required from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, render … -
Heroku H12 Request timeout on Django application
I am running a Django application on Heroku. when i make a request longer than 30 seconds, it stopped and the request returns 503 Service Unavailable. These are the heroku logs 2021-10-20T07:11:14.726613+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/ajax/download_yt/" host=yeti-mp3.herokuapp.com request_id=293289be-6484-4f11-a62d-bda6d0819351 fwd="79.3.90.79" dyno=web.1 connect=0ms service=30000ms status=503 bytes=0 protocol=https I tried to do some research on that and i found that i could increase the gunicorn (i am using gunicorn version 20.0.4) timeout in the Procfile. I tried increasing to 60 seconds, but the request still stops after 30. This is my current Procfile: web: gunicorn yetiMP3.wsgi --timeout 60 --log-file - these are the buildpacks i'm using on my heroku app: heroku/python https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git How can i increase the request timeout? Did i miss some heroku configuration? -
Django heroku Programming Error after deployed
My Django site was working perfectly fine locally but after deploying my Django site on Heroku, I got this error. enter image description here This error belongs to the frontend and also I had another error in my admin site. I'm not sure they are related or not.enter image description here I searched on google and some people say I need to run this command and it will be fine. heroku run python manage.py migrate So I run that command and I got no error while running but still doesn't fix the error. But there is something weird. When I'm creating my site on local, I misspelled the word installation_record as installtion_record in my models.py and I migrated it. After a few days, I found my misspelled word and fixed it again in the models.py. And so on I finally push my code on heroku and when I open my heroku website, I got the error that said Programming Error at / column installation_record does not exist at LINE 1:.... Perhaps You means installtion_record . I can't precisely remember the error. I changed the word back to the misspelled word (installtion_record) as the Django suggestion said and it worked. I … -
Django CMS not changing child page slugs after parent slug is changed
I have a problem where the url slug for a section of a website has been changed using the CMS admin interface, and now the children pages which are descended from it still have the old (incorrect) slug in their urls, leading to 404 errors. How can the child page slugs be updated to reflect the new, correct parent page slug? -
postdetail() got an unexpected keyword argument 'post'
I have have error in django/python. I get this error when I enter the post list and try to open the post details: postdetail() got an unexpected keyword argument 'post' when i try views.py codes: from django.shortcuts import render, get_list_or_404 from django.http import HttpResponse from django.urls.base import reverse from django.urls.converters import SlugConverter from .models import post def index(request): tpost = post.objects.all() return HttpResponse("Welcome to the django website") def postlist(request): tpost = post.objects.filter(status = "published") return render(request, "blog/post/list.html", {"posts": tpost}) def postdetail(request, npost, pk): post = get_list_or_404(npost, slug = npost, id = pk) return render(request, "blog/post/detail.html", {"fpost": post}) models.py Codes: from django.contrib import auth from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class post(models.Model): STATUS_CHOICES = ( ("draft", "Draft"), ("published", "Published"), ) title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, unique_for_date = "publish") author = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "blog_post") body = models.TextField() publish = models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default = "draft") objects = models.Manager() class Meta: ordering = ("-publish",) def get_absolute_url(self): return reverse("blog:post_detail", args = [self.slug, self.id]) def __str__(self): return self.title … -
Hello. How can I add user automatically in Django when he/she creates new object?
I have simple model where user writes some text and saves it, I need to add current user to this created object. Right now I have such code where user can be chosen manually, how do I make it automatically? I know about user=self.request.user, but I don't know how to use it in Models. Sorry if this question is silly, I'm new to Django class SomeText(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) keyword = models.TextField(verbose_name='Add your text here') -
Why FormView misses ipdb.set_trace() for post request?
I have the following code: urls.py: urlpatterns = [ ... url(r'^upload_file', FileFieldFormView.as_view(), name='upload_file'), url(r'^success', lambda request: HttpResponse('Hello World!'), name='hello_world'), ] upload_file.py: from django.views.generic.edit import FormView from ..forms import FileFieldForm import ipdb def handle_uploaded_file(f): ipdb.set_trace() with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) class FileFieldFormView(FormView): form_class = FileFieldForm template_name = 'reports/upload_file.html' # Replace with your template. success_url = '/reports/success' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: print("hello") handle_uploaded_file(f) return self.form_valid(form) else: print("invalidated") return self.form_invalid(form) forms.py: from django import forms class FileFieldForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) and upload_file.html template: {% extends "core/layout.html" %} {% block content %} <br/> <h3>{{ title }}</h3> <br/> {% block controls %}{% endblock %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form.as_table }} <button type="submit">Upload</button> </form> {% endblock %} Instead of landing to ipdb.set_trace() in upload_file.py, I get success page. Why does django miss the breakpoint? -
How to add aggregate values in Django Rest Framework ModelViewSets
In my DRF app I have the following model, serializer and view. models.py class Log(models.Model): plant = models.ForeignKey(Plant, on_delete=models.CASCADE) date_time = models.DateTimeField() water_consumption = models.PositiveSmallIntegerField() elec_consumption = models.PositiveSmallIntegerField() serializers.py class ConsumptionSerializer(serializers.ModelSerializer): class Meta: model = Log fields = ("water_consumption", "elec_consumption") views.py class ConsumptionViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, ] serializer_class = ConsumptionSerializer def get_queryset(self): # Get params from url start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') # Make sure params are not null if start_date is not None and end_date is not None: queryset = queryset.filter(date_time__range=[start_date, end_date]) return queryset else: raise ValidationError({"ERROR": ["No params found in url"]}) This works and it outputs something like this in JSON: [ { "water_consumption": 1, "electrical_consumption": 1 }, { "water_consumption": 1, "electrical_consumption": 1 }, { "water_consumption": 1, "electrical_consumption": 1 }, ] What I would like to achieve is to receive some aggregated data alongside those data, like this: { "total_water_consumption": 3, "total_elec_consumption": 3, "detailed_logs": [{ "water_consumption": 1, "electrical_consumption": 1 }, { "water_consumption": 1, "electrical_consumption": 1 }, { "water_consumption": 1, "electrical_consumption": 1 }] } How should I customise the queryset to have the total values added? Thank you in advance. -
Django login not working. Page just refreshes a new login page
I have a project called django_swing. Within this project i have 2 different app. One is interface and the other is users. Within the django_swing folder for urls.py, I have the following: path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), Within the interface folder for urls.py, I have the following: path('', views.home, name='interface-home'), Within the interface folder for views.py, I have the following: def home(request): return render(request, 'interface/home.html', {'title':'Home'} ) I have the file for home.html. As it is very long, I cant paste here. When i run the project, 127.0.0.1 loads the page for home.html. Lastly, within the django_swing folder for settings.py, I have the following at the bottom of the file: STATIC_URL = '/static/' LOGIN_REDIRECT_URL='interface-home' LOGIN_URL = 'login' But when i access 127.0.0.1/login and key in with a account i just made followed by pressing the login button, the page refreshes with the same login page and the url becomes http://127.0.0.1:8000/login/?#. It is not jumping to interface-home as declared in settings.py. Can anyone advise me on how to solve this? I am a beginner at this. Thank you very much! -
error of the Query set error in REST framework
I from this code I get the query set error( because the query set method). previously I got the result when I define the queryset outside of the GET, but that action was not proper.... Now I want to define the DonorContactInfo.objects.filter(email__iexact=email) anywhere but in the GET method... what should I do? class DonorInformationDetailAPI(ListAPIView): """ A sample endpoint to list all donors in the system. * Requires token authentication. * Only admin users are able to access this view. """ serializer_class = DonorContactInfoSerializer queryset = DonorContactInfo.objects.all() permission_classes = [IsAuthenticatedOrReadOnly] # TODO change pagination_class = AdminPanelsPagination def get(self, request, *args, **kwargs): """return the list of the donor detail with that specific email""" # queryset = self.get_queryset() email = kwargs["email"] self.get_queryset = DonorContactInfo.objects.filter(email__iexact=email) serializer = self.get_serializer(self.get_queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) # def get_queryset(self): # return ?? here is my URL path( "donors/donor_information/<str:email>/", DonorInformationDetailAPI.as_view(), name="donors_information", ), this is the Error 'QuerySet' object is not callable -
How can i verify if the refer code is valid and sent by another user?
I am working on refer and earn module and been struck in on how to check if the refer code is valid and been sent by another user, so that i can give back commission to him. For the time being, I have created a model named Referral, which stores a random string, which is being generated within the model using a function as we can see below. Currently, I am generating referral code by the admin just by adding a refer user and automatically the unique string has been generated. Now I want to check to verify whether the code provided to the user has been the code referred by another user and grant him some rewards on each referrals. But I am thinking of how to achieve this solution. Please help me with the views part. Any kind of help would be appreciated. Thank you. Models.py: class Referral(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="referral_codes", null=True, blank=True) label = models.CharField(max_length=100, blank=True) code = models.CharField(max_length=40, unique=True, blank=True) comm_amount = models.PositiveIntegerField(max_length=20, null=True, blank=True) expired_at = models.DateTimeField(null=True, blank=True) redirect_to = models.CharField(max_length=512,blank=True) created_at = models.DateTimeField(default=timezone.now) def __str__(self): if self.user: return f"{self.user} ({self.code})" else: return self.code def generate_refer_code(self): return get_random_string(8).upper() def save(self, *args, **kwargs): if … -
Can anyone that how to convert Django Api's as websocket Api?
Please tell me the answer, I wondering since long but didn't get anything. I have the API's which are working correctly with flutter but now I want to connect all those API's with web socket. Can anyone tell me how to do it? Api's Example: path('editpinnames/', myapp_view.devicePinNames), Suppose this is the api and I want to use this work with web sockets. Please I am very thankful to you.