Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I resolve Django takes no arguments error I get when I plug in external api to project
I am a bit new to Django and Python in general I am trying to consume an external API (alpacas get account) and return the result as json /rest I tested the code in a simple python project without Django and it works perfectly, but when I plug it into Django, I get the takes no arguments error After writing my code and running it, When I invoke the API in postman I see the takes no arguments error see error details below Django Version: 3.1.5 Exception Type: TypeError Exception Value: AccountView() takes no arguments Internal Server Error: /alpaca/v1/alpaca_account/ Traceback (most recent call last): File "/Users/xxxx/PycharmProjects/xxxx/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/xxxx/PycharmProjects/xxxx/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: AlpacaAccountView() takes no arguments [27/Jun/2021 21:24:12] "GET /alpaca/v1/alpaca_account/ HTTP/1.1" 500 56001 Honestly, I have no idea what this error is talking about Please help me resolve this See My code below View import requests, json from .config import * BASE_URL = BASE_URL ACCOUNT_URL = "{}/v2/account".format(BASE_URL) ORDERS_URL = "{}/v2/orders".format(BASE_URL) HEADERS = {'APCA-API-KEY-ID': API_KEY, 'APCA-API-SECRET-KEY': SECRET_KEY} # Create your views here. class AccountView: def get_account(self): r = requests.get(ACCOUNT_URL, headers=HEADERS) return json.loads(r.content) see urls.py from django.urls import path, … -
Associate a Django Bool FormField with a submit button in a ModelForm and CBV
The view has a Boolean Field which will define if a question is OK or needs correction. The template will load two buttons to act as submit to the form, "Question is OK" and "Question needs correction". I need to pass the value of this button as the Boolean Field value. I found the answer when using Function-based views, but I'm using Class-based views, so I don't know how to pass the request.POST values. Here's my views.py and forms.py: views.py class QuestionValidation(PermissionRequiredMixin, UpdateView): permission_required = 'users.validator' model = Question form_class = ValidationForm template_name = 'question_validation.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) context['question'] = Question.objects.filter( question_order=self.kwargs['order']).get(id_by_order=self.kwargs['id_by_order']) context['order'] = self.kwargs['order'] context['id_by_order'] = self.kwargs['id_by_order'] return context def get_object(self, *args, **kwargs): question_order = Q(question_order__id=self.kwargs['order']) question_id = Q(id_by_order__contains=self.kwargs['id_by_order']) q = Question.objects.get(question_order & question_id) return get_object_or_404(Question, pk=q.id) def get_success_url(self, *args, **kwargs): view_name = "order-detail" return reverse(view_name, kwargs={'pk': self.kwargs['order']}) forms.py class ValidationForm(forms.ModelForm): class Meta: model = Question fields = ['revision_report', 'revision_approval'] widgets = { 'revision_report': forms.HiddenInput(), 'revision_approval': forms.HiddenInput(), } and part of the template that this code will be loaded: <form action="" method="POST">{% csrf_token %} {{ form.as_p }} <button class="btn btn-success" name="question_approved">Questão aprovada</button> <button class="btn btn-danger" name="question_refused">Questão não foi aprovada</button> </form> <br><br> <script src="{% static 'js/hoverValidatorTextbox.js' … -
Use is_authenticated using OneToOneField relation with User
I have built a model which have a OneToOne relation with the User object in Django like this : class Student(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) But in the HTML file, the filter {% if user.student.is_authenticated %} does not work but the filter {% if user.is_authenticated %} works. I thought that the Student class inherits the attributes from the User class. Is there an other possibility to create custom users from the User class with the possibility to use {% if user.student.is_authenticated %} ? I want also to have the possibility to use for example {% if user.teacher.is_authenticated %}. -
FIlter table using CBV ListView that has pagination
I'm trying to do a ListView from a Class Based View that has filtering, and pagination I was able to get the table showing and the pagination working as I want, this gives me a basic list of all invoices that I need to show: but I'm not able to make the filtering work, for what I understand I need to override the "get_queryset" method and this would return a queryset, (in this cased called "invoices_filtered_list") however I don't know how should I render this in the .html page so it will have the textbox in which I should type. These are my files: views.py from django.views.generic import (TemplateView, ListView) from .models import WoodhistAzolveInvoices from .filters import WoodhistAzolveInvoicesFilter class InvoicesListView(ListView): model = WoodhistAzolveInvoices template_name = 'home.html' context_object_name = 'invoices' ordering = ['suppliername', 'invoicenumber'] paginate_by = 50 def get_queryset(self): qs = self.model.objects.all() invoices_filtered_list = WoodhistAzolveInvoicesFilter(self.request.GET, queryset=qs) return invoices_filtered_list.qs urls.py from django.urls import path from .views import InvoicesListView app_name = 'web' urlpatterns = [ path('', InvoicesListView.as_view(), name='home'), ] filters.py import django_filters from .models import * class WoodhistAzolveInvoicesFilter(django_filters.FilterSet): class Meta: model = WoodhistAzolveInvoices fields = ['suppliername'] models.py from django.db import models class WoodhistAzolveInvoices(models.Model): docid = models.CharField(db_column='DocId', primary_key=True, max_length=50) # Field name made lowercase. … -
Django. TemporaryUploadedFile
I upload a file through the form, check it, and only after checking it I want to add it to my database. form = BookForm(request.POST, request.FILES) file = form.files path = file.get('book_file').temporary_file_path() in path - '/tmp/tmpbp4klqtw.upload.pdf' But as soon as I want to transfer this file from the temporary storage to some other folder, I get the following error: path = os.replace(path, settings.MEDIA_ROOT) IsADirectoryError: [Errno 21] Is a directory: '/tmp/tmpbp4klqtw.upload.pdf' -> '/home/oem/bla/bla' Can't understand why this file is not in reality? What can I do about it? Is it possible to set some special path for the "temporary file"? -
Access Users from Group model Django
I'm trying to access the users inside the group model of django. For now i can only access it the other way, the groups from the user model. I want to be able to do multiple action from the Group endpoints: Retreive the users inside the group and return them inside the view create a group and add user directly in the request update the group to add or remove a user from it I've done the same thing for the permissions, i can add them inside the groupe, but i can't do it for the user because there isn't a field for the users inside the group model. To do it for the permission i made a serializer I would like to do the same as the Permissions field, but for the users, is there any way ? I looked to override the Group model and add a field so a could use it in the serializer but i didn't find how to do so. class GroupSerializer(serializers.ModelSerializer): Id = serializers.IntegerField(source='id', required=False) Name = serializers.CharField(source='name') Permissions = PermissionSerializer(source='permissions', many=True, required=True) class Meta: model = Group fields = ('Id','Name','Permissions',) def create(self, validated_data): print(validated_data) permissions_data = validated_data.pop('permissions') permissions = [] for permission … -
Django Admin panel unable to retrieve and show image(already uploaded through model)
As you can see in SS i am unable to view the image in admin panel; under the image tag error from CMD: Not Found: /upload/images/How-to-buy-a-desktop-PC-header.jpg [27/Jun/2021 13:00:51] "GET /upload/images/How-to-buy-a-desktop-PC-header.jpg HTTP/1.1" 404 2605 I already checked the upload folder and image is in the folder. settings.py MEDIA_URL = '/upload/' MEDIA_ROOT = os.path.join(BASE_DIR, 'upload') urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py # under the Product class def image_tag(self): return mark_safe('<img src="{}" height ="50"/>'.format(self.image.url)) image_tag.short_discription = 'Image' last admin.py class ProductAdmin(admin.ModelAdmin): list_display = ['title', 'category', 'status', 'image_tag'] list_filter =['category'] readonly_fields = ('image_tag',) inline = [ProductImageInline] screenshot: -
Best way to serialize object dynamically based on parameter using Django Rest Framework
I want to render a dynamically selected object using an intermediate model and a custom query_param. For instance,I want to make a query like this: http://api.url/v1/recipes/19/?location=1 and obtain a serialized Recipe object with it's ingredients based on the location send as query_params: Recipe object: { "id": 19, "ingredients": [ { "id": 35, # Product id "name": "Tomato", # Product name "price": 2.0, # Product price "quantity": 3, "supplier": 12, # Supplier at location=1 }, { "id": 36, # Product id "name": "Cheese", # Product name "price": 5.0, # Product price "quantity": 2, "supplier": 12, }, ], "title": "Pizza" } If I change the ?location= query param I want to obtain the same recipe but getting the products of another Supplier. This is my current schema. But any suggestion is very appreciated: class Recipe(models.Model): title = models.CharField(max_length=255) class IngredientRecipe(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) quantity = models.FloatField(default=0.0) product_name = models.CharField(max_length=255) class Meta: unique_together = ['product_name', 'recipe'] class Supplier(models.Model): name = models.CharField(_('Name'), max_length=255) location = models.ForeignKey(Location, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=255) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) price = models.FloatField() I'm trying to serialize Recipe objects with its related ingredients based on supplier's location: class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' … -
Django 3.2 `get_asgi_application` is not a replacement for channels AsgiHandler
I'm upgrading from Django 3.0/Channels 2 to Django 3.2/Channels 3. In channels 3.0 release notes, it is stated that instantiating a ProtocolRouter without the http key is deprecated, and that one should use django.core.asgi.get_asgi_application as value. However, when I'm explicit on the http protocol using get_asgi_application, my middlewares don't work anymore: the app is complaining that I'm using sync middleware in an async context. This is the Django error popping up: SynchronousOnlyOperation at /graphql/ You cannot call this from an async context - use a thread or sync_to_async. ... Here is the content of asgi.py # my_project/asgi.py import os from channels.routing import ProtocolTypeRouter, URLRouter import django from django.core.asgi import get_asgi_application assert os.environ.get('DJANGO_SETTINGS_MODULE') is not None, \ 'The `DJANGO_SETTINGS_MODULE` env var must be set.' django.setup() from core.urls import ws_routes application = ProtocolTypeRouter({ # If the following line is not commented out, I get the above error. # 'http': get_asgi_application(), 'websocket': URLRouter(ws_routes) }) I do not want to use async logic in my HTTP handlers/middleware, as I prefer the simplicity of synchronous patterns. I use Channels only to deal with websockets. I'm looking for advice on how to follow Channels guidelines (ie, be explicit about the http protocol application). In the meantime, … -
Get User id from class based view
I have a class based view: class PostListViewMojeReported(ListView): def get_username(self, **kwargs): login_username = request.user.username context = {'login_username': login_username} return context model = Post template_name = 'blog/filter_moje_reported.html' context_object_name = 'posts' queryset = Post.objects.filter(Q(status='Otvorena') & (Q(res_person_1_username=username) | Q(res_person_2_username=username))) ordering = ['-date_posted'] paginate_by = 30 I don't know how to get username from the current logged in user to use as a filter in my queryset. I need to compare the current logged in user with 'res_person_1_username' and 'res_person_2_username'. -
ListView in Django
I am using Class Based views and want to display data on a webpage using ListView. Am using for loop to display many objects data. In my models, the items have a category field which is ForeignKey where the category is either Bags, Tshirts or Shoes. I want to display items whose Category is Shoes only. I have tried using the if condition which isnt working with the ForeignKey field. How do I filter the Category field to display Bags only? models.py from django.db import models # Create your models here. class Category(models.Model): title = models.CharField(max_length=30) createdtime = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Categories" class Product(models.Model): mainimage = models.ImageField(upload_to='product') name = models.CharField(max_length=264) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') previewtext = models.TextField(max_length=200, verbose_name='Preview Text') detailstext = models.TextField(max_length=1000, verbose_name='Description') price = models.FloatField() oldprice = models.FloatField(default=0.00) createddate = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ['-createddate',] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from shopapp.models import Product # Create your views here. class Home(ListView): model = Product template_name = 'shopapp/home.html' html file <div class="container my-5"> <h2 class="my-5">Handbags</h2> <div class="row"> {% for product in object_list %} {% if product.category == 'Bags' %} <div class="col-md-6 col-sm-12 col-lg-3"> … -
Django Images not showing when DEBUG=False on Heroku
I am trying to get images show up on website whenever a user uploads it, but they do not show up when DEBUG=False. The site got deployed successfully on Heroku. I am using Whitenoise and Gunicorn too. Here are my configurations:- settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Procfile web: gunicorn appname.wsgi --log-file - requirements.txt asgiref==3.3.4 astroid==2.5.6 colorama==0.4.4 Django==3.2.4 gunicorn==20.1.0 isort==5.8.0 lazy-object-proxy==1.6.0 mccabe==0.6.1 Pillow==8.2.0 pylint==2.8.3 pytz==2021.1 sqlparse==0.4.1 toml==0.10.2 whitenoise==5.2.0 wrapt==1.12.1 -
Export multiple Django models into one file
Is there a way to export your objects from different models to a csv file? I can add all the objects from a model one by one, but I need multiple objects from different models next to each other instead of under each other. for doc_uren in DocentUren.objects.all().values_list('docent', 'periode', 'studiejaar', 'uren'): writer.writerow(doc_uren) for data in PeriodeData.objects.all().values_list('studiejaar', 'periode_1', 'periode_2', 'periode_3', 'periode_4'): writer.writerow(data) This results in the objects from DocentUren, with the objects from PeriodeData the line under the last objects from DocentUren. I need it next to each other. Thanks! -
Showing extra field on ManyToMany relationship in Django serializer
I have a ManyToMany field in Django, like this: class Dictionary(models.Model): traditional = models.CharField(max_length=50) simplified = models.CharField(max_length=50) pinyin_numbers = models.CharField(max_length=50) pinyin_marks = models.CharField(max_length=50) translation = models.TextField() level = models.IntegerField() frequency = models.IntegerField() idiom = models.BooleanField() child_char = models.ManyToManyField('Dictionary', through='DictionaryChildChar', null=True) class Meta: db_table = 'dictionary' indexes = [ models.Index(fields=['simplified', ]), models.Index(fields=['traditional', ]), ] class DictionaryChildChar(models.Model): class Meta: db_table = 'dictionary_child_char' from_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="from_dictionary") to_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="to_dictionary") word_order = models.IntegerField() Currently, I have a serializer like this: class FuzzySerializer(serializers.ModelSerializer): pinyin = serializers.CharField( required=False, source="pinyin_marks") definition = serializers.CharField( required=False, source="translation") hsk = serializers.CharField(required=False, source="level") class Meta: model = Dictionary fields = ["id", "simplified", "pinyin", "pinyin_numbers","definition", "hsk", "traditional", "child_char"] depth = 1 This gives me a dictionary entry, as well as the child dictionary entries associated with it (as a Chinese word is made up of several Chinese characters) However, I need to know what order these child characters are in, and hence why I have word_order. I would like this word_order field to appear on the individual child_char - how do I write my serializer in such a way that this additional field is present? Would I need to make a separate serializer for child_char? -
Grouping (not ordering) objects into alphabetical list on a single Django page
I’m trying to display a list of objects in an alphabetic list for a directory page. Something that looks like this: https://en.wikipedia.org/wiki/List_of_film_and_television_directors To avoid having to click on the link, the list would be: Surname starts with A • Anderson, Wes Surname starts with B • Burton, Tim Surname starts with C • Coppola, Sofia A simplified version of the model would be: class Person(model.Models): first_name = model.CharField last_name = model.CharField def __str__(self): return "{}, {}".format(self.last_name, self.first_name) Route 1. In the view? If not filtering in the template, after that I thought it would be possible to filter the objects within the view and send each portion separately. def person_list(request): startswith_a = Person.objects.filter(last_name__startswith="a") startswith_b = Person.objects.filter(last_name__startswith="b") startswith_c = Person.objects.filter(last_name__startswith="c") etc. etc. return render(request, "directory/person-list.html", {"startswith_a": startswith_a, "startswith_b": startswith_b}) But that feels wrong as I’d have to hard code the alphabet into the view definition, and then pass all 26 (or more) sets into the view. Route 2. In the model? Finally I thought it might be possible to have a new field in the model which would affix its location in the directory. This could be updated manually or (I guess?) by customising the save function on the model to … -
Error setting up Postgresql on Django Heroku?
For reference this is how I set up Postgresql on Django Heroku: https://blog.usejournal.com/deploying-django-to-heroku-connecting-heroku-postgres-fcc960d290d1 When I "import dj_database_url" I get a "ModuleNotFoundError: No module named 'dj_database_url'" error. My requirements.txt file has a line though that says dj-database-url==0.5.0. Is anybody familiar with this sort of error/ how to get around it? -
How to make endpoint view in django to get queryset for autocomplete?
I am trying to make queryset for autocomplete search using jquery UI. I wrote a function based view which according to me should work ,but its not working as it should. when i type valid word it redirects me where search results should be shown but there i get error AttributeError: 'Branches' object has no attribute 'FIELD' Branches is my model class Branches(models.Model): ifsc = models.CharField(primary_key=True, max_length=11) bank = models.ForeignKey(Banks, models.DO_NOTHING, blank=True, null=True) branch = models.CharField(max_length=250, blank=True, null=True) address = models.CharField(max_length=250, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=26, blank=True, null=True) my views.py def search_ifsc(request): if request.is_ajax(): q = request.GET.get('q', '').capitalize() search_qs = Branches.objects.filter(ifsc__startswith=q) results = [] print(q) for r in search_qs: results.append(r.FIELD) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) urls.py path('ajax/search/' , views.search_ifsc, name='search_view') template <div class="position-absolute top-50 start-50 translate-middle"> <nav class="navbar navbar-light bg-light"> <div class="container-fluid" class="ui-widget"> <form id="search" method="POST" action="http://127.0.0.1:8000/ajax/search/"> <!-- {% csrf_token %} --> <input type="text" class="form-control" id="q" name="q"> <button type="submit" class="btn btn-default btn-submit">Submit</button> </form> </div> </nav> </div> <script type='text/javascript'> $(document).ready(function(){ $("#q").autocomplete({ source: "http://127.0.0.1:8000/ajax/search/", minLength: 2, open: function(){ setTimeout(function () { $('.ui-autocomplete').css('z-index', 99); }, 0); } }); }); I get this error when i … -
AttributeError Implementing First Serializer: 'QuerySet' object has no attribute 'name'
I've just built a Item (product) model for my project's eCommerce page, an ItemDetailsView which returns individual items and an ItemApiView which is meant to create/retrieve/update/delete. When I make a get request to get ItemApiView I expect it to return a full list of items in my database. However, I am getting the following error: AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `ItemSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'name'. "name" is a field in my Item model. Here is the full model: class Item(BaseModel): """ Item that can be purchased """ name = models.CharField(max_length=150) description = models.TextField(blank=True) price = models.DecimalField(max_digits=4, decimal_places=2) image = models.ImageField(upload_to="images/", default="images/default.png") category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True) is_active = models.BooleanField(default=True) quantity = models.IntegerField(null=True, blank=True, default=0) discount = models.FloatField(default=0.0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Products" ordering = ("-created",) def get_absolute_url(self): return reverse("store:product_detail", args=[self.slug]) def __str__(self): return "{}".format(self.name) Here is the ItemApiView. Only the "Get" method corresponds to my specific problem but I included the full view because I am open to critiques on the … -
Problem in creating Custom Model Django superuser
Iam using Django 3.2.4 with rest_framework. I have been trying to create a custom user model for my project, which successfully migrates. But while creating a super user Iam getting a error TypeError: create_superuser() missing 1 required positional argument: 'username' My models looks like this: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True, max_length=254, ) first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) contact = models.IntegerField(unique=True) date_joined = models.DateTimeField(default=datetime.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] since I want my custom user model, why django is asking for default username as its default? Where am I going wrong here? -
Hi Django Community, I am facing issue on deleting individual comments from blog posts as superuser?
I am facing issue on deleting individual comments from blog posts as superuser? I have Cross Icon which i want functionality in to delete comment. It would be great if someone help me with the flow i am doing other tasks.As I want be stay in Simple. This is my blog's models.py code class Post(models.Model): Title=models.CharField(max_length=50) slug = models.SlugField(unique=True,null=True,blank=True) Meta_Tags = models.CharField(max_length=200,null=True) Description=models.TextField() Category=models.CharField(max_length=50) Body=RichTextUploadingField() Date=models.DateField(auto_now_add=True) Views=models.IntegerField(default=0,null=True) Likes=models.IntegerField(default=0,null=True) Dis_Likes=models.IntegerField(default=0,null=True) CommentsCounts=models.IntegerField(default=0,null=True) def __str__(self): return self.Title + " | " + str(self.Date) def createslug(instance,new_slug=None): slug=slugify(instance.Title) if new_slug is not None: slug=new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists=qs.exists() if exists: new_slug = "%s-%s" %(slug,qs.first().id) return createslug(instance,new_slug=new_slug) return slug def pre_save_post_receiver(sender,instance,*args, **kwargs): if not instance.slug: instance.slug=createslug(instance) pre_save.connect(pre_save_post_receiver,Post) class Comment(models.Model): Post=models.ForeignKey(Post, on_delete=models.CASCADE,null=True) Name=models.CharField(max_length=50,null=True) Body=models.TextField(null=True) Time=models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return str(self.Post) + " | " + self.Body + " | " + self.Name + " | " + str(self.Time) This is my blog's views.py code def blogdetail(request,slug): post=Post.objects.get(slug=slug) comment=Comment.objects.filter(Post=post).order_by('-id') post.Views +=1 if 'Like' in request.POST: post.Likes +=1 if 'DisLike' in request.POST: post.Dis_Likes +=1 if 'Comment' in request.POST: post.CommentsCounts +=1 Name=request.POST.get('name',default="Anonymous") Body=request.POST.get('comment') Comments=Comment(Name=Name,Body=Body,Post=post) Comments.save() post.save() context={ 'post':post, 'comment':comment, } return render(request,'blogdetail.html',context) This is my blog's template code {% for comment in comment %} <div class="comment-card my-3"> <span><i class="fas fa-user text-secondary"></i></span> … -
Need assistance in designing Django model for a school management system app
I am trying to create a school management app, and I want to have place where a school admin can create a weekly schedule for a class. I have the below structure in mind for this. { "grade": 1, "shortBreak": "10:00am - 10:15am", "longBreak": "1:00pm - 2:00 pm", "monday": [ { "time":"09:00am - 09:30am", "subject":"English" }, { "time":"09:30am - 10:00am", "subject":"Math" },{ "time":"10:15am - 10:45am", "subject":"Science" }, ], "tuesday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Sciene" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], "Wednesday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Sciene" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], "Thursday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Sciene" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], "Friday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Sciene" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], "Saturday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Science" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], } The challenge I am facing is that I don't know how to add array fields in Django models and how to have multiple objects in an array and store it in … -
Download zip folder using ajax and celery task
I have a view (see below) that enable users to download zip folder with filetered data and it works. To improve performances, I want to change to an asynchronous task using ajax and celery task with celery-progress to display a progress bar. But I can not return Httpresponse (with zip file attached) using celery task as I do with the 'classical view' so I do not really know how to proceed. I thought about making and storing zip folder on server and when task is finished, the view return the zip folder. But I do not want to store multiple zip folders on server. I also thought about another scheduled task that could remove zip folders on a regularly basis... but this sound very 'complicated' process... What would be the best approach to do this? def export(request): ... # path to study directory to be pass in argument path = './exports/'+ study_name +'/' + database_name + '/archives/' + selected_import + '/' # retrieve the list of all files in study directory excluding 'archives' directory listOfFiles = getListOfFiles(path) # Create zip buffer = io.BytesIO() zip_file = zipfile.ZipFile(buffer, 'w') # if Data checkbox is checked, zip include the data files if data … -
Average of DateTimeField Django
class Foo(models.Model): ... a=models.IntegerField() timestamp=models.DateTimeField(auto_now_add=True) I want the average of timestamp field and when making a query Foo.objects.filter(a=1).values('timestamp','a').aggregate(Avg('timestamp')) its giving me error 'decimal.Decimal' object has no attribute 'tzinfo'. Can anyone help me how can I fix this or tell me a way how can I take the average of DateTimeField? -
Django, how to run a command through Windows Task Scheduler
How to schedule and run a specific command in django using Windows Task Scheduler. My django project is not currently local server deployed but using the manual set up just like activating the virtual environment and then typing the python manage.py runserver on terminal rather deploying through xampp or laragon. But i am bit confused on how to achieve to schedule and run a command like python manage py get_source through the use of Windows Task Scheduler. -
How to overrite the admin change_view Django
I want to overrite the admin change_view so I can add more items to the context. Apparently, my attempted solutions give me an error that says: if not response.has_header('Expires'): AttributeError: 'NoneType' object has no attribute 'has_header' My attempted solution is below. Any help will def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = dict( name='John' ) super().change_view(request, object_id,extra_context=extra_context)