Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display html table using django python pyspark
I am very beginner in all of them. So my HTML code looks like this --> <table id="myTable" class="table table-dark table-striped"> {% for item in tnames %} <tr> <th scope="col">{{ item }}</th> </tr> {% endfor %} {% for values in datas %} <tr> <td scope="row"> {{ values }}</td> </tr> {% endfor %} </table> code for django to get lists for html is like that --> tnames = [] for n in df.columns: tnames.append(n) datas=[] for i in df.collect(): datas.append(tuple(i)) and output is like this How to fix it ? Yes I am doing something wrong. So what is right way to display them correctly. Thank you in advance. -
Defining an arbitrary function in Django class-based view and calling it from the frontend
I am making a React-Django web application, during which I had to call a function at the backend and get the returned value (namely, compute the average grade of all students in the database). However when I tried to define my own function in Django views.py, I ran into a problem. class TodoView(viewsets.ModelViewSet): model = Todo def head(self, request, path, *args, **kwargs): all_grades = self.get_queryset().values_list('grade', flat=True) all_units = self.get_queryset().values_list('units', flat=True) result = sum(all_grades) / sum(all_units) response = HttpResponse( headers={'gpa': str(result)}, ) return response This is my code on the frontend: axios .head("/api/todos") .then(res => { console.log(res.headers); }) .catch((err) => console.log(err)); I believe it is not a problem in the urls.py because in other parts of my code, axios.get on the same model works fine but not axios.head. Also I believe it may not be a problem in the "head" function since removing the def head function in views.py gives the same error. If there is any other way to define and call an arbitrary function from a class-based view on the Django backend (without using HEAD, for example), I would be thrilled to learn it. After days of search I didn't find anything that looks workable. Or would switching to … -
Django keeps redirecting to https in local environment
I'm trying to run my project in django in local without using https. I have added the following to the settings I'm using: SECURE_SSL_REDIRECT = False DEFAULT_HTTP_PROTOCOL = 'http' SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False # SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') (commented) I'm running the serve with the following command: python3 manage.py 0.0.0.0:8000. If I browse to 0.0.0.0:8000, it works (it uses http). Nonetheless, if I use localhost:8000 then it always redirects to https and the following error appears: I do not know if it helps, but I'm using django 1.11 version inside a docker container. -
Celery Django runing periodic tasks after previus was done. [django-celery-beat]
I want to use django-celery-beat library to make some changes in my database periodically. I set task to run each 10 minutes. Everything working fine till my task takes less than 10 minutes, if it lasts longer next tasks starts while first one is doing calculations and it couses an error. my tasks loks like that: from celery import shared_task from .utils.database_blockchain import BlockchainVerify @shared_task() def run_function(): build_block = BlockchainVerify() return "Database updated" is there a way to avoid starting the same task if previous wasn't done ? -
DateField bigger than most recent record
I have this DB table: models.py class Payment(models.Model): date = models.DateField(blank=False,verbose_name="Data") description = models.CharField(max_length = 300,blank=False,verbose_name="Descrizione") course_subscription = models.ForeignKey(CourseSubscription,null=True,on_delete=models.CASCADE,verbose_name="Sottoscrizione Corso") payment_method = models.CharField(max_length = 4,blank=False,verbose_name="Modalità di pagamento",choices=PAYMENTS) value = models.DecimalField(max_digits=7, decimal_places=2,blank=False,verbose_name="Importo") receipt= models.FileField(blank=False,verbose_name="Ricevuta") How can I add a constraint in model or form which allows the insertion of new payments only if the date is more recent than the most recent record? In other words, I want a new payment has always a more recent date than the last inserted one. I tried with: forms.py class AddPaymentForm(forms.Form): def __init__(self, max_value, min_date, *args, **kwargs): super(AddPaymentForm, self).__init__(*args, **kwargs) self.fields['value'] = forms.DecimalField( max_digits=7, decimal_places=2, required=True, label="Importo", min_value=0.01, max_value=max_value, help_text= f"Valore Massimo: {max_value}", widget = forms.NumberInput() ) self.fields['date'] = forms.DateField( required=True, label="Data", min_value=min_date, help_text= f"Data minima: {min_date}", widget=forms.TextInput( attrs={'type': 'date'} ) ) .... and views.py ... payments = Payment.objects.all().order_by('-date') initial = { 'date': datetime.date.today().strftime("%Y-%m-%d"), 'member':member, 'description': description, 'value': 1.00, 'subscription_type' :subscription_type, 'subscription_id' :subscription_id } if len(payments)>0 : min_date = payments[0].date.strftime("%Y-%m-%d") initial["date"] = min_date else: min_date = None form = AddPaymentForm( initial= initial, max_value = remaining_fee, min_date = min_date ) ... This way works with 'value' field, but forms.DateField doesn't have "min_value" attribute. -
Is there a reason I am not getting any Django output from gunicorn in Heroku?
I have a django project deployed to Heroku in a worker using gunicorn. I have included all flags/configurations that I am using below. The issue is that the logging in Heroku does not display any output from Django, and my project is running into some issues in the backend. I can access the logs, but there are no logs, just the message from gunicorn initialization. Procfile: release: python manage.py migrate backend web: bin/boot worker: gunicorn backend.wsgi:application -b 0.0.0.0:$PORT -c /app/gunicorn.conf.py --log-file - gunicorn.conf.py # gunicorn.conf.py # Non logging stuff workers = 3 # Whether to send Django output to the error log capture_output = True # How verbose the Gunicorn error logs should be loglevel = "debug" -
Raw SQL in order by in django model query
I've a simple query like this (I want 1 BHK to come first, then 2BHK, then anything else) select * from service_options order by case space when '1BHK' then 0 when '2BHK' then 1 else 2 end, space In Django, how to do it? I've a model named ServiceOption I tried this but no luck. ServiceOption.objects.order_by(RawSQL("case space when '1BHK' then 0 when '2BHK' then 1 else 2 end,space"), ()).all() I don't want to execute raw query with something like ServiceOption.objects.raw("raw query here") Any input will be appreciated. Thank you in advance. -
related name of a many to many relationship django
I have a model of user like this: class User(AbstractUser): following = models.ManyToManyField('self', related_name="followed") I'm trying to make a many to many relationship from a user to a user. I eed to access who the user is following, and who is following the user. the first requirement works nicely, but when I try to see who is following the user, with user.followed.all(), I see an error, AttributeError at /user/1: 'User' object has no attribute 'followed' How would I fulfill my second requirement? TIA, Ishaan -
I keep getting an "ModuleNotFoundError" with Django in Python
I know, this is a common problem, but no solution has yet worked for me. I have set up Django with an Virtual-Environment in Python (OS is Windows) but everytime I try to run django-admin startproject mysite I get an error Traceback (most recent call last): File "C:\Users\Max\Desktop\django_app\venv\Scripts\django-admin.py", line 5, in <module> from django.core import management ModuleNotFoundError: No module named 'django' Does anybody know a solution for this. Thanks in advance. -
How to get count of objects in database for a particular user
Right now my dashboard looks like this: The white box should show the number of complaints that are registered by the user. But right now it shows the number of complaints registered by all users. What should I do to only get the count for a particular user? views.py: def dashboard(request): count = Complaint.objects.all().count() context = {'count':count} return render(request, 'dashboard.html', context) template: <p>{{count}}</p> What should I do?? -
User should not be able to pay until he selects an address
I am Building an eccomerce webiste. So, the issue is that i wanna allow a user to pay only after he selects an address. I have tried required field of html but it seems like it didn't worked. When a user selects an address only then he will be able to pay. But currently when i click on pay button it directly redirects me to payment. This is buy now page {% extends 'app/base.html' %} {% load static %} {% block title %}Buy Now{% endblock title %} {% block main-content %} {% load humanize %} <div class="container"> <div class="row mt-5"> <div class="col-sm-4 offset-sm-1"> <h4>Select Shipping Address :</h4> <hr> <form action="/payment_done/"> {% if address %} {% for add in address %} <div class="card"> <div class="card-body"> <h5>{{add.name}}</h5> <p>{{add.locality}}, {{add.city}}, {{add.state}} - {{add.zipcode}}.</p> </div> </div> <div class="form-check mt-2 mb-5"> <input class="form-check-input" type="radio" name="custid" id="custadd{{forloop.counter}}" value="{{add.id}}" required> <label class="form-check-label fw-bold" for="custadd{{forloop.counter}}"> Address: {{forloop.counter}} </label> </div> {% endfor %} <!-- Paypal button --> <div class="text-end"> <div id="paypal-button-container"></div> </div> {% else %} <p class='mx-2 fw-bold'>Please add an <a href="/profile/">shipping address</a></p> {% endif %} </form> </div> </div> </div> {% endblock main-content %} {% block payment-gateway %} <!-- Include the PayPal JavaScript SDK --> <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script> <script> // … -
No 'Access-Control-Allow-Origin' error - font-awesome
Within the past couple of weeks, I've started to get an error that I haven't seen before. My project has not materially changed and so I believe that this may be a change that font-awesome has implemented. Access to CSS stylesheet at 'https://use.fontawesome.com/releases/v5.3.1/css/all.css' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Any thoughts on which CORS settings in Django I have to change in order to prevent this from happening? When I hit Ctrl+F5 to refresh the page, the error goes away. When I visit another page in my project, I get the error again. Thanks! -
Use PixiJS with Django
I'm new to django and didn't have the time to fully understand it so I'm hoping someone can help me fix this. I am using this page: Generative UI - Orb Animation [pixi.js] + Frosty Elements ❄️ with the same Javascript file in it. I can use it properly without django by typing <script type="module" src="script.js"></script> in my html file but when it comes to django, I don't actually know what to do. I tried to put it in static folder and load it. It works, but there is no animation! I guess it has something to do with the applications in the script, but again I'm a newbie so I don't know what to do. Any suggestions? -
Django: Return all nested Sub Model from a given Model (which isn't directly linked to given model)
I have my models.py as shown below: from django.db import models # Create your models here. class Category(models.Model): categoryType = models.CharField(max_length=100,blank = False, unique = True, null = False) def __str__(self): return self.categoryType class SubCategory(models.Model): subcategoryType = models.CharField(max_length=100) categoryType = models.ForeignKey(Category,on_delete=models.CASCADE, null = True, related_name='category_type') def __str__(self): return f'{self.categoryType} :: {self.subcategoryType}' class Product(models.Model): productName = models.CharField(max_length=50,blank = False, null = False) subCategoryType = models.ForeignKey(SubCategory,on_delete=models.SET_NULL, null=True,related_name='product_subcategories') #categoryType = models.ForeignKey(Category,on_delete=models.SET_NULL, null=True,related_name='product_categories') def __str__(self): return f'{self.productName} : {self.subcategoryType}' I have created a serializer to get all products within a given category as shown below: class ProductSerializerSpecific(serializers.ModelSerializer): class Meta: model = Product fields = ('id','productName') class SubCategoryProductsSpecific(serializers.ModelSerializer): products = ProductSerializerSpecific(source='product_subcategories', many=True) class Meta: model = SubCategory fields = ['products'] class CategoryProducts(serializers.ModelSerializer): products = SubCategoryProductsSpecific(source='category_type', many=True) class Meta: model = Category fields = ('id','products') My View goes like this: class ListAllCategoryProducts(viewsets.ReadOnlyModelViewSet): queryset = Category.objects.all() serializer_class = CategoryProducts And finally I registered by route like this: router.register(r"category_products", views.ListAllCategoryProducts, basename="categories_products") When I do a GET request to get all products with a given ID as shown below: GET http://localhost:8000/category_products/1 HTTP/1.1 The output comes as shown below: { "id": 1, "products": [ { "products": [] }, { "products": [] }, { "products": [] }, { "products": [ { … -
How to save MultipointField in django rest framework using createAPI View
Im using django Rest framework to make an api at some point I would like to save a multipointfield , Im expecting the frontend to send an array of point but that format is not supported by django-restframework how am I supposed to do it? -
Django autocomplete-light ModelSelect2Multiple select a valid choice error
I keep getting "Select a valid choice. 'X' is not one of the available choices." where 'X' is the primary key of the profile when I submit the create team form after filling in team name, selecting game and team members. I have been trying to create a form for a model that has ManyToMany Relationship with Profile model. I decided to use django-autocomplete-light after trying django-select2 package. Here is my code so far models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField(unique=False, null=True, blank=True) class Game(models.Model): name = models.CharField(max_length=128, unique=True) is_team_game = models.BooleanField(default=False) def __str__(self): return '{}'.format(self.name) class Team(models.Model): name = models.CharField(max_length=100) game = models.ForeignKey(Game, on_delete=models.CASCADE) players = models.ManyToManyField(Profile, related_name='player_profiles') views.py class ProfileAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Profile.objects.all() if self.q: qs = qs.filter(user__username__istartswith=self.q) return qs urls.py from django.urls import path from . import views urlpatterns = [ path('autocomplete/profile/', views.ProfileAutocomplete.as_view(), name='profile-autocomplete'), ] forms.py from django import forms from .models import Game, Profile, Team from dal import autocomplete class TeamForm(autocomplete.FutureModelForm): players = forms.ModelMultipleChoiceField(label='Team Members', queryset=Profile.objects.none(), widget=autocomplete.ModelSelect2Multiple(url='profile-autocomplete')) class Meta: model = Team fields = [ 'name', 'game', 'players' ] def __init__(self, *args, **kwargs): super(TeamForm, self).__init__(*args, **kwargs) self.fields['game'].queryset = Game.objects.filter(is_team_game=True) create_team.html template {% extends "website/base.html" %} {% load crispy_forms_tags %} {% block … -
Django cron job error when pulling the new code
I'm running the Django website with some cron jobs. One of them is running every 3 mins. When I made an update, I will pull the new code: Example for my update code: # my_a.py class MyClass: pass # my_b.py from my_a import MyClass I just notice that sometimes I have an error on this cron job, some files have new code, some files do not. It raises an error: cannot import name MyClass. Does anyone face this problem? I guess the job is running at the time I pull the code but I'm not sure. -
CK-Editor in django not working in production
CK-editor works fine in development but its not working in production. In the console tab it shows error: Failed to load resource: the server responded with a status of 404 (Not Found) ckeditor.js -
Reusing old options from pagination and filter Django
view : def subcategory(request, category_url): category = get_object_or_404(Category, category_url=category_url) subcategories = Subcategory.objects.filter(category=category) products_list = Product.objects.filter(product_category=category) subcatid = request.GET.getlist('subcategory') print(subcatid) if subcatid: ids = [int(id) for id in subcatid] subcategories1 = Subcategory.objects.filter(category=category, id__in=ids) products_list = Product.objects.filter(product_category=category, product_subcategory__in=subcategories1) else: subcategories1 = None products_list = Product.objects.filter(product_category=category) page = request.GET.get('page', 1) paginator = Paginator(products_list, 12) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) if request.user.is_authenticated: wishlist = get_object_or_404(Wishlist, user=request.user.profile) else: wishlist = None reqget = request.GET.copy() reqget.pop('page', None) ctx = {'products':products, 'products_list':products_list, 'wishlist':wishlist, 'subcategories':subcategories, 'category':category, 'subcategories1':subcategories1, 'reqget': reqget, } return render(request, 'products/subcategory.html', ctx) template : {% extends "blog/base.html" %} {% load static %} {% load ratings %} {% load humanize %} {% block title %}ماهوت کالکشن | دسته بندی محصولات {% endblock title %} {% block content %} <main class="main"> <div class="page-header text-center"> <div class="container"> <h1 class="page-title">{{category.category_name}}<span>دسته بندی</span></h1> </div><!-- End .container --> </div><!-- End .page-header --> <nav aria-label="breadcrumb" class="breadcrumb-nav mb-2"> <div class="container"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="">{{q}} فروشگاه</a></li> <li class="breadcrumb-item"><a href="/products/">دسته بندی</a></li> <li class="breadcrumb-item active" aria-current="page">{{category.category_name}}</li> </ol> </div><!-- End .container --> </nav><!-- End .breadcrumb-nav --> <div class="page-content"> <div class="container"> <div class="row"> <div class="col-lg-9"> <div class="toolbox"> <div class="toolbox-left"> <div class="toolbox-info"> محصولات این دسته : <span>{{products_list.all|length}}</span> محصول </div><!-- End .toolbox-info … -
Django : Do you need to name a tag library (templates, static, etc) with a specific folder name?
So, I'm currently learning Django. And I got confused when I started creating, for example, 'templates' folder. So templates folder is where we can actually store templates for the web application. Do we actually need to name the folder 'templates'? Or could we name it something else? -
Django Queries for related models
I have these two models, product and comment. class Product(VoteModel, models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=False, on_delete=models.CASCADE, related_name="%(class)s_listings") product_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False) product_title = models.CharField(max_length=150, null=False) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) product_description = tinymce_models.HTMLField() num_vote = models.IntegerField(default=0) The Comment Model class Comment(VoteModel, models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ip_address = models.GenericIPAddressField(_('IP address'), unpack_ipv4=True, blank=True, null=True) rating = models.CharField(max_length=3, default=1.0) # Content-object field content_type = models.ForeignKey(ContentType, verbose_name=_('content type'), related_name="content_type_set_for_%(class)s", on_delete=models.CASCADE) object_pk = models.TextField(_('object ID')) content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk") Then, I have a serializer, in which I am trying to get the rating for the comments to come out with an average rating for each Item class ProductSerializer(ModelSerializer): product_rating = SerializerMethodField(read_only=True) class Meta: model = Product fields = [ "product_rating" ] def get_product_rating(self, obj): comments = Comment.objects.filter(object_pk=obj.pk, content_type=ContentType.objects.get_for_model(obj)) .... return {'rating': str(float("%.1f" % average)), 'views': views} This seems to be creating duplicate queries comments = Comment.objects.filter(object_pk=obj.pk, content_type=ContentType.objects.get_for_model(obj)) How can I rewrite the query better to avoid duplicate queries? -
Why does my favicon and video not appear after I run build my react app?
When I build my react app, the video and favicon do not appear. This is my folder structure before npm run build: This is my folder structure after npm run build (frontend folder placed in django backend folder): This is my code when linking the favicon in index.html: <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> This is my code when linking the video in one of my components: <video src='/videos/video.mp4' autoPlay loop muted /> Images from products on my website load properly, but they are retrieved from the django backend. E.g. a product image url pattern is /images/scan1.jpg My Django url pattern: urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) My Django settings static file structures: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ BASE_DIR /'static', BASE_DIR /'frontend/build/static' ] MEDIA_ROOT = 'static/images' The error im getting: Any help would be much appreciated, Thanks -
How to solve UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I'm trying to use Black to format my Django code. It works fine in most directories. However, I get the Unicode decode error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte on the .py files in one directory in particular. The files are in UTF-8, but I have tried multiple different other encodings and have tried deleting and recreating files which hasn't resolved the issue. I'm working in an Anaconda environment, but deactivating that doesn't make any difference. I've also disabled most of my VS Code extensions. I have looked at many SO postings on this, but none of the suggestions thus far have helped. I'm using VS Code on a Mac and have a feeling it is something to do with the fact that in the past I have edited the same code on a Windows machine using VS Code with WSL (code synced with a GitHub repo), but can't figure out how to address it. I've put a sample Traceback call below. Any help would be much appreciated! (base) ➜ healthtic git:(master) ✗ black pages/views.py Traceback (most recent call last): File "/Users/jh/opt/anaconda3/bin/black", line 8, in <module> sys.exit(patched_main()) File "/Users/jh/opt/anaconda3/lib/python3.8/site-packages/black/__init__.py", line 1130, in patched_main … -
Sending a message to inclusion tag Django
Does anyone know how send a message from a main view to an inclusion tag . Application Main View: def post(self, request): name = request.POST.get('name', 'Anonymous') email = request.POST.get('email', 'Anonymous') subject = request.POST.get('subject', 'Anonymous') message = request.POST.get('message', 'Anonymous') contact = Contact.objects.create(name=name, email=email, subject=subject, message=message) contact.save() success(request,"Message Sent") return redirect(reverse('portfolio:home') + '#contact') Main Template with custom tags {% get_introduction_data %} {% get_about_data %} {% get_expertise_data %} {% get_client_data %} {% get_skill_data %} {% get_education_data %} {% get_experience_data %} {% get_work_data %} Supposing I wanted to pass my message from the view into my main template that is then redirected to one of my main view tags. How would I be able to pass the message considering that the message framework requires a request to store a message which is passed on to the next request . The main issue is inclusion tags do not possess their own individual request object and maybe there is a way to pass data from a main template to an included partial. Here is a github link to the opensource repo for further inspection: https://github.com/Munalula-Sikazwe/Django-Personal-Portfolio -
How to solve this strange error in the admin site?
I am working on a project with countries, regions, counties, municipalities and cities. Each of these has its own model and the model is registered using a ModelAdmin. Here's my admin.py. from django.contrib import admin from .models import Country, Region, County, Municipality, City @admin.register(Country) class CountryAdmin(admin.ModelAdmin): model = Country list_display = ["name", "continent", "capital", "area", "population", "regions"] list_filter = ["continent", "area", "population"] search_fields = ["name", "capital", "description"] @admin.register(Region) class RegionAdmin(admin.ModelAdmin): model = Region list_display = ["name", "country", "area", "population"] list_filter = ["country", "area", "population"] search_fields = ["name", "description"] @admin.register(County) class CountyAdmin(admin.ModelAdmin): model = County list_display = ["name", "capital", "area", "population", "abbreviation", "verbose_neighbours"] list_filter = ["region", "area", "population"] search_fields = ["name", "capital", "description", "abbreviation"] @admin.register(Municipality) class MunicipalityAdmin(admin.ModelAdmin): model = Municipality list_display = ["name", "county", "area", "population"] list_filter = ["county", "area", "population"] search_fields = ["name", "county", "description"] @admin.register(City) class CityAdmin(admin.ModelAdmin): model = City list_display = ["name", "county", "area", "population"] list_filter = ["county", "area", "population"] search_fields = ["name", "description"] And here are my models. from django.db import models from django.forms.models import model_to_dict from django.dispatch import receiver from django.db.models.signals import pre_save, post_save from django.utils.translation import gettext_lazy as _ class ModelDiffMixin(object): """ A model mixin that tracks model fields' values and provide some useful api …