Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using optional **kwargs in python
I am in process of refactoring a codebase in Python where I am still learning their syntactical sugar so hopefully I can get some help from the experts here. I want to write a generic function that takes list of optional arguments using **kwargs and makes a call to DB model using the list of arguments present. So for eg 5 out of 8 column entries are present in the function call, make a create call using those 5 (rest 3 are already accept null in DB). However if I send 7 values in function, I should be able to use the same function again. So here is something I am thinking of : Controller Class .... create(arg1=x, arg3=y, arg4=z, arg6=a, arg7=b) create(arg1=x, arg2=x2, arg3=y, arg4=z, arg6=a, arg7=b, arg8=b2) .... Model Class arg1 = models.CharField(max_length=255, null=True, blank=True) arg2 = models.CharField(max_length=255, null=True, blank=True) arg3 = models.DateTimeField(null=True, blank=True) arg4 = models.DateTimeField(null=True, blank=True) arg5 = models.CharField(max_length=255, blank=True, null=True) arg6 = models.CharField(max_length=255, blank=True, null=True) arg7 = models.CharField(max_length=255, blank=True, null=True) arg8 = models.BooleanField(null=True, blank=True) def create(**kwargs): DBMODEL.objects.create( arg1=kwargs['arg1'], arg2=kwargs['arg2'], arg3=kwargs['arg3'], arg4=kwargs['arg4'], arg5=kwargs['arg5'], arg6=kwargs['arg6'], arg7=kwargs['arg7'], arg8=kwargs['arg8'] ) Is that something which can be done using my code above or if there is any other suggestion? End … -
Unable to populate select option from database in Django
I am a beginner to Django and unable to populate the items from my database table to <option></option>. From models.py: from django.db import models from django.db.models.fields.related import ForeignKey # Create your models here. class Tbl_Category(models.Model): cat_Id = models.AutoField(primary_key=True) cat_Name = models.CharField(max_length=20, unique=True) # def __str__(self): # return [self.cat_Id, self.cat_Name] class Tbl_Item(models.Model): item_Id = models.AutoField(primary_key=True) item_Name = models.CharField(max_length=30, unique=True) cat_Idf = models.ForeignKey(Tbl_Category,on_delete=models.CASCADE) item_Price = models.IntegerField() From views.py: from django.shortcuts import render from orderapp.models import Tbl_Item # Create your views here. def displayMain(request): return render(request,'index.html') def ct(request): options = Tbl_Item.objects.filter(cat_Idf=1) context = {'alloptions' : options} return render(request, 'index.html', context) From index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css.css' %}"> <title>DATA COLLECTION</title> </head> <body> <div class="container"> <div class="order-screen"> <div class="element"> <label for="coffee-tea">Coffee-Tea</label> <select name="coffee-tea" id="coffee-tea"> {% for opt in alloptions %} <option value="{{opt.item_Id}}">{{opt.item_Name}}</option> {% endfor %} </select> </div> <div class="cart-screen">CART-SCREEN</div> </div> </body> </html> I assure you that my database connection is working absolutely fine and there was no problem while running makemigrations and migrate commands. My tables contain values that I have hardcoded. Please guide me with what is wrong with my approach. Thank you. -
type object 'Post' has no attribute 'filter'
Every time I attempt to write a comment on a post, I get an AttirbuteError at the post number. e.g- 'AttributeError at /post/54/', and below this it says 'type object 'Post' has no attribute 'filter''. It then directs me to my views.py line 58, which reads: post = self.get_object(Post). It is a part of my PostDetailClass: class PostDetailView(DetailView): model = Post form = CommentForm def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): post = self.get_object(Post) form.instance. user = request.user form.instance.post = post reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) reply = comment_qs, reply=None form.save() form.save_m2m() return redirect(reverse("post", kwargs={ 'content': Post.content })) Can anyone point out what is wrong with my code? Thank you. -
Django SortedManyToManyField does not save order in reverse relation
I am using the SortedManyToManyField field from django-sortedm2m as in the following in my models: import uuid from django.db import models from sortedm2m.fields import SortedManyToManyField class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parent = models.ForeignKey( to="self", on_delete=models.SET_NULL, null=True, blank=True, related_name="subcategories", ) name = models.CharField(max_length=250) class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) categories = SortedManyToManyField(to=Category, blank=True, related_name="product_items") Now, lets create and add some data to both the fields: # create some categories c1 = Category.object.create(name="C1") c2 = Category.object.create(name="C2") c3 = Category.object.create(name="C3") # create some products p1 = Product.object.create(name="P1") p2 = Product.object.create(name="P2") p3 = Product.object.create(name="P3") # add categories to product P1 p1.categories.add(c1, c2, c3) # add products to category C1 c1.product_items.add(p1, p2, p3) Now, what happens is that the categories are inserted and retrieved in the correct order, where as products added to product_items are not. When I checked the underlying class type of the field p1.categories, it says that its <class 'sortedm2m.fields.create_sorted_many_related_manager.<locals>.SortedRelatedManager'> where as when I do the same for the reverse relation (product_items) it says <class 'django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager'> Does this mean that the order is saved explicitly for the field that defines the SortedManyToManyField field and not the related_name/ reverse relation? Do I have to explicitly define the … -
Adding data to linked table from link on page
Within my Django application, I have two models: Event and Game The Event model has a ForeignKey to the Game model. I have a page that lists all the games using a {% for game in game_list %}, and I'm trying to create a button that will take me to the Events Form to allow me to add an event to the game. The event form only has 3 fields. project , event_name and event_date. When you land on the event form page I'd like to have the project name populated with the game name from the previous page. But when I create the link to form my page breaks. Im using: <a class="dropdown-item" href="{% url 'add-event' game.id %}">Add Key Event</a> to take to the event form. Models class Event(models.Model): project = models.ForeignKey(Game, to_field='project_name', on_delete=models.CASCADE) event_name = models.CharField(max_length=20) event_date = models.DateTimeField(blank=True, null=True) def __str__(self): return str(self.event_name) class Game(models.Model): project_name = models.CharField(max_length=255, blank=False, unique=True) project_website = models.URLField(max_length=255, blank=True) project_description = models.TextField(blank=True) def __str__(self): return str(self.project_name) View def add_event(request,game_id): event = Event.objects.get(pk=game_id) form = addEventForm(request.POST or None, instance=event) return render(request, 'pages/add_event.html', {'event': event, "form" : form}) URL path('add_event/<game_id>', view=add_event, name="add-event"), Error DoesNotExist at /apps/add_event/13 Event matching query does not exist. Request Method: … -
Django Unique together With abstract class inheritance
I have two models class BaseModel(models.Model): class Meta: abstract = True created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) obj_status = models.BooleanField(default=True, null=True) and class Client(BaseModel): class Meta: unique_together = ( ('obj_status', 'document') ) document = models.IntegerField() But when a try to run makemigration a recieve HINT: This issue may be caused by multi-table inheritance. How can I resolve this problem without write obj_status in every model that I have? -
Django Products model for e-commerce site
I am trying to build a sample e-commerce site with Django and I am trying to figure out as to how can I model the relationship between a product having multiple sizes and each of those sizes having their individual stocks this my products/products varied models: from django.db import models from colorfield.fields import ColorField # Create your models here. class Color(models.Model): Color = models.CharField(max_length=120,null=True,blank=True) value = ColorField(default='#FF0000') def __str__(self): return self.Color class Size(models.Model): Size = models.CharField(max_length=120,null=True,blank=True) def __str__(self): return self.Size class Product(models.Model): title = models.CharField(max_length=120,null=True,blank=True) def __str__(self): return self.title class ProductVaraiant(models.Model): product =models.ForeignKey(Product,on_delete=models.CASCADE,null=True,blank=True) slug = models.CharField(max_length=120,null=True,blank=True) Color = models.ForeignKey(Color,on_delete=models.CASCADE,null=True,blank=True,) Size = models.ManyToManyField(Size) def __str__(self): return self.slug -
Django , linking three models
I have a question. I have a Bb model that includes the rubric and sub_rubric parameters. There are also Rubric and Sub_rubric models, one-to-many related. Question: how to link rubric and sub_rubric to each other in the Bb model, so that when a new instance of the Bb model is created, when the rubric changes, the subrubruc list changes too. Code: class Rubric(models.Model): name = models.CharField(max_length=50, db_index=True) class Sub_Rubric(models.Model): rubric = models.ForeignKey(Rubric, null=True, on_delete = models.PROTECT) name = models.CharField(max_length=50, db_index=True, unique = True) class Bb(models.Model): title = models.CharField(max_length=50) content = models.TextField(null=True, blank=True) price = models.FloatField(null=True,blank=True) published = models.DateTimeField(auto_now_add=True, db_index=True, ) rubric = models.ForeignKey(Rubric, null=True, on_delete = models.PROTECT, related_name='name') sub_rubric = models.ForeignKey(Sub_Rubric, null=True, on_delete = models.PROTECT) -
Returning a scalar from a Django function
I have a silly question I really want the below to return a single number, but it still returns an iterable object. Do you know how I can get it to return a scalar? pts = skills.objects.filter(creator=request.user).raw('''SELECT sum(cast(points as int)) as id FROM myapp_skills WHERE status = 'closed' and creator = %s ''',[request.user.username]) Here is my skill model: class skills(models.Model): skill_name = models.CharField(max_length=400, default="data") points = models.CharField(max_length=400, default="data") time_required = models.CharField(max_length=400, default="data") target_date = models.CharField(max_length=400, default='none') category = models.CharField(max_length=400, default="data") status = models.CharField(max_length=400, default="data") skill_id = models.CharField(max_length=400, default="data") creator = models.CharField(max_length=400, default="data") syllabus = models.CharField(max_length=40000, default="data") -
Error while using createdb command postgresql on windows 10
I am a new user of PostgreSQL, and I am learning it so that I can use it with Django, so I am trying to use createdb command to create a new database, but even though I am entering the correct password for my account, I am getting this error. I reinstalled everything and checked everything I could think of but I was not able to solve this error. So, if I can get some help regarding this issue it would be nice. Even using the command psql, and submitting the correct password, gives the same error. As far as I checked, I needed to enter the password I used while installing PostgreSQL. By the way, I am using the latest version of PostgreSQL 14.0.1 Thank You in advance. command I used: createdb testdatabase createdb: error: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "<username_placeholder>" -
App not compatible with buildpack, django Heroku
Using buildpack: heroku/python but still it says not compatible. I am a beginner in Django please help. Here is build log : -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed -
Create sub directories within django?
I'm trying to create a simple website that contains entries (blog posts) organized in the url by example.com/category_id/post_id However what I'm currently doing only resolves example.com/category_id. Can someone show me how to change the code to make it: List all blog posts when going to example.com/blog List all blog posts of a particular category when going to example.com/blog/category_id List a particular blog post when going to example.com/blog/category_id/post_id Thank you! If I need to provide more information please let me know. blog.urls.py from django.urls import path from . import views app_name = "blog" urlpatterns = [ path('', views.index, name='index'), path('<int:welcome_id>/', views.welcome_detail, name='welcome_detail'), path('blog/<int:category_id>/', views.category, name="category"), path('blog/<int:category_id>/<int:blog_id>/', views.category, views.blog_post_detail, name="blog_detail"), ] blog/models.py from django.db import models class WelcomePage(models.Model): greeting_text = models.TextField(max_length=2000) def most_recently_published(self): return Status.objects.order_by('id')[0] def __str__(self): return self.greeting_text class Categories(models.Model): name = models.CharField(max_length=200) category_title = models.CharField(max_length=200, default='') def get_categories(self): return Status.objects.order_by('id') def __str__(self): return self.name class BlogPost(models.Model): blog_title = models.CharField(max_length=200) blog_text = models.TextField(max_length=10000) pub_date = models.DateTimeField('date published') categories = models.ForeignKey(Categories, null=True, on_delete=models.SET_NULL) def most_recently_published(self): return Status.objects.order_by('id')[:5] def __str__(self): return self.blog_title blog/views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse, Http404 from .models import WelcomePage, BlogPost, Categories def index(request): latest_welcome_message = WelcomePage.objects.order_by('id') latest_blog_posts = BlogPost.objects.order_by('id') categories = Categories.objects.order_by('id') … -
Django Static Files - CSS File doesnt load
I'm learning Django. I am trying to load a static css file, but it doesn't work. That's part of my base.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- css --> <link rel="stylesheet" type="text/css" href="{% static 'HomePage/style.css' %}"> </head> and that's part of my settings.py file: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', ] STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "static_root") Where did I make mistake ? I have already used python manage.py collectstatic in command prompt -
Can the code in django be made to read by the javascript?
what happens is that I already have the behavior to add rows (JS and HTML) with my plus sign, however I have the problem that the form that is duplicated (with the formset) does not have the code in django, and obviously what I want is that I add the rows with the HTML, JS and Django. I wish I could recycle my code so that cell1.outerHTML (and the others) could contain something like this: {% render_field form.code class = "form-control"%} I just don't know if it can be done, hopefully because my knowledge of JS is minimal :( presupuestos-forms.html <table class="table table-bordered table-nowrap align-middle" id="childTable1"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_price}} </td> <td> <div> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn btn-block btn-default" id="addrow" onclick="childrenRow()" value="+" /> </td> </tr> <tr> {{ formset.management_form }} {% for form in formset %} <td> {% render_field form.codigo class="form-control" %} </td> <td> {% render_field form.descripcion class="form-control" %} </td> <td> {% render_field form.quantity class="form-control" %} </td> <td> {% render_field form.unit_price class="form-control" … -
getting errolist when using htmx and tinymce
Im trying to implement post request with htmx and for rich text editor using tinymce. my form : <!--<form method="POST"> {% csrf_token %}--> <form onsubmit='copyContent()' method= "post" hx-post= "{% url 'forum:forum-detail' post.pk %}" hx-swap="innerHTML" hx-target = "#comment-list"> <div class="modal-body"> <div class="form-group"> <label for="threadTitle">Your Answer</label> <textarea name="reply" class="form-control summernote" placeholder="Input your answer here"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" id="cancelForm">Cancel</button> <button type="submit" class="btn btn-primary" name="btn-post-question">Post</button> </div> </form> The error I get : <ul class="errorlist"><li>reply<ul class="errorlist"><li>This field is required.</li></ul></li></ul> it works just ok when I used the traditional post request with TinyMCE. when I used htmx without TinyMCE its work just ok too. it just when I combine htmx and TinyMCE. -
Manager isn't available; 'auth.User' has been swapped for 'accounts.User'
I have created a custom user model 'User' and have declared in settings.py as AUTH_USER_MODEL Also i have two other models consumer and workman which has an onetoone relation with my custom user. i created two forms for registering customer and workman but as i fill form(it doesnt even check validation) and submit, it says: Manager isn't available; 'auth.User' has been swapped for 'accounts.User' models.py: from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model # Create your models here. class User(AbstractUser): class Types(models.TextChoices): CONSUMER = "CONSUMER" , "Consumer" WORKMAN = "WORKMAN" , "Workman" type = models.CharField(max_length=20,choices=Types.choices,default=Types.WORKMAN) is_consumer = models.BooleanField(default=False) is_workman = models.BooleanField(default=False) class Consumer(models.Model): user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,primary_key=True) location = models.CharField(max_length=100) class Workman(models.Model): user = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,primary_key=True) contact = models.CharField(max_length=100) views.py: from .forms import ConsumerCreationForm, WorkmanCreationForm from .models import Workman,Consumer class consumersignupview(CreateView): model = Consumer form_class = ConsumerCreationForm template_name = 'accounts/register.html' success_url = '/' class workmansignupview(CreateView): model = Workman form_class = WorkmanCreationForm template_name = 'accounts/register.html' success_url = '/' forms.py: from django.contrib.auth.forms import UserCreationForm from django import forms from .models import Consumer,Workman class ConsumerCreationForm(UserCreationForm): location = forms.CharField( max_length=100, required=False) class meta(UserCreationForm.Meta): model = Consumer class WorkmanCreationForm(UserCreationForm): contact = forms.CharField(max_length=100) class meta(UserCreationForm.Meta): model = Workman error: -
How to pass an array from django views to external JS file for chart
I am designing a dashboard where i need to pass labels and data to my chart from django views to Variables in Java Script. This below code is not displaying lables or data in chart. Django Views def chartd(request): labelss=['JANS', 'FEBS', 'MARS', 'APRS', 'MAYS', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] datas = [120, 123, 125, 90, 92, 70, 75, 60, 90, 80, 110, 100] context = {"labelss":labelss, "datas": datas} return render(request, 'charts.html',context) Java Script for charts.html var chart_labels ={{labelss}}; var chart_data ={{datas}}; var ctx = document.getElementById("chart1").getContext('2d'); var gradientStroke = ctx.createLinearGradient(0, 230, 0, 50); gradientStroke.addColorStop(1, 'rgba(72,72,176,0.1)'); gradientStroke.addColorStop(0.4, 'rgba(72,72,176,0.0)'); gradientStroke.addColorStop(0, 'rgba(119,52,169,0)'); //purple colors var config = { type: 'line', data: { labels: chart_labels, datasets: [{ label: "dataset", fill: true, backgroundColor: gradientStroke, borderColor: '#d346b1', borderWidth: 2, borderDash: [], borderDashOffset: 0.0, pointBackgroundColor: '#d346b1', pointBorderColor: 'rgba(255,255,255,0)', pointHoverBackgroundColor: '#d346b1', pointBorderWidth: 20, pointHoverRadius: 4, pointHoverBorderWidth: 15, pointRadius: 4, data: chart_data, }] -
Django-pay pal IPN response not receiving
I am trying to integrate a payment gateway for my Project , but I am having trouble understanding how to handle the IPN listener part of it, I am really confused about whether to create a new view for it , or where should form reside and also how to implement the signals which it sends , I have spent hours looking for an answer but no avail ! thanks in advance class PaymentProcess(View): def get(self,request): host = request.get_host() payment = PaymentRecords.objects.get( order_id = request.session['order_id'] ) print(payment.total_amount) print(host) paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': payment.total_amount, 'item_name': 'Item_Name_xyz', 'invoice': 'Test Payment Invoice'+'INV12323244'+str(randint(10,5000)), 'currency_code': 'USD', # 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), <--- how to deal with this one # 'return_url': 'http://{}{}'.format(host, reverse('payment_done')), # 'cancel_return': 'http://{}{}'.format(host, reverse('payment_canceled')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request , 'restprac/index.html',{'form':form}) signals.py def show_me_the_money(sender, **kwargs): ipn_obj = sender print(sender) if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != "receiver_email@example.com": # Not a valid payment return # ALSO: for the same reason, you need to check the … -
python-socketio How to support Socket.IO-Client-Swift
I'm using Socket.IO-Client-Swift for my iOS app and am using python-socketio for my Django server. However, when I try to connect to the server as a client from the iOS app, python-socketio gives this error: The client is using an unsupported version of the Socket.IO or Engine.IO protocols (further occurrences of this error will be logged with level INFO) Thanks in advance. -
Extended the User model, but not quite sure how to serialize fields for both User and UserExtended
I extended my User model with a new model just called UserExtended: # Django imports from django.db import models from django.contrib.auth.models import User class UserExtended(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) crm_guid = models.UUIDField(unique=True) security_q1 = models.CharField(max_length=255, blank=True, null=True) security_a1 = models.CharField(max_length=255, blank=True, null=True) security_q2 = models.CharField(max_length=255, blank=True, null=True) security_a2 = models.CharField(max_length=255, blank=True, null=True) attempts = models.SmallIntegerField(blank=False, null=False, default=0) key = models.CharField(max_length=255, blank=True, null=True) key_expires = models.DateTimeField(blank=True, null=True) method = models.CharField(max_length=4, blank=True, null=True) class Meta: db_table = 'auth_user_extended' I was hoping by just doing that some Django magic would take care of the rest and I wouldn't have to change my views.py or serializers.py. But when I send a request to the end-point I get: [api] django.core.exceptions.ImproperlyConfigured: Field name `guid` is not valid for model `User`. So it does apparently need to be specified. I've been looking at the documentation and similar SO questions to find an answer. This is what I have for my views.py: # Django imports from django.contrib.auth.models import User # Third party imports from rest_framework import generics from rest_framework.permissions import IsAdminUser # App imports from users.serializers import UserSerializer class UsersListCreateView(generics.ListCreateAPIView): permission_classes = [IsAdminUser] serializer_class = UserSerializer def get_queryset(self): queryset = User.objects.all() email = self.request.query_params.get('email') username = self.request.query_params.get('username') if … -
Which files are binaries in a python wheel?
The documentation says that Python Wheel is a binary distribution format. To understand the difference between the source code and binaries distributed within a Python wheel, I am manually inspecting a .whl file from the package django. The specific .whl I am looking at is this. I decompressed the wheel file and the top-level directory of the file looks like this: . ├── Django-3.2.9.data ├── Django-3.2.9.dist-info └── django The Django-3.2.9.data file contains a script called admin.py. The directory structure for Django-3.2.9.dist-info looks like this: . ├── AUTHORS ├── LICENSE ├── LICENSE.python ├── METADATA ├── RECORD ├── WHEEL ├── entry_points.txt └── top_level.txt The WHEEL file in this directory seems to contain information of the WHEEL version that was used to build this .whl. The top-level directory structure for the django file looks like this: . ├── __init__.py ├── __main__.py ├── apps ├── bin ├── conf ├── contrib ├── core ├── db ├── dispatch ├── forms ├── http ├── middleware ├── shortcuts.py ├── template ├── templatetags ├── test ├── urls ├── utils └── views Here, except the bin folder, all the other files are source code files that are present on the django repository. Therefore, my guess was that the bin folder … -
Django: Why my objects do not add database correctly?
I am working on a simple Django project and suffice to say I am just a beginner. I have 2 classes in models.py: from django.db import models from django.db.models.deletion import CASCADE class Category(models.Model): category_name=models.CharField(max_length=225,null=True) def __str__(self): return f"ID: {self.category_name}" class Book(models.Model): cover_img = models.URLField(max_length=200, null=True) author=models.CharField(max_length=128,null=True) summery=models.TextField(max_length=1000,null=True) category = models.ForeignKey(Category,related_name="book_categories",on_delete=CASCADE,null=True) def __str__(self): return f"{self.cover_img} ,{self.author},{self.summery}" On the first page of my website(Menu.html), I create a button for each category using jinja: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> <title>Menu</title> </head> <body> {% for cat in categories %} <a type="button" class="btn btn-danger" href="{% url 'cat_detail' cat.id %}"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-book" viewBox="0 0 16 16"> <path d="M1 2.828c.885-.37 2.154-.769 3.388-.893 1.33-.134 2.458.063 3.112.752v9.746c-.935-.53-2.12-.603-3.213-.493-1.18.12-2.37.461-3.287.811V2.828zm7.5-.141c.654-.689 1.782-.886 3.112-.752 1.234.124 2.503.523 3.388.893v9.923c-.918-.35-2.107-.692-3.287-.81-1.094-.111-2.278-.039-3.213.492V2.687zM8 1.783C7.015.936 5.587.81 4.287.94c-1.514.153-3.042.672-3.994 1.105A.5.5 0 0 0 0 2.5v11a.5.5 0 0 0 .707.455c.882-.4 2.303-.881 3.68-1.02 1.409-.142 2.59.087 3.223.877a.5.5 0 0 0 .78 0c.633-.79 1.814-1.019 3.222-.877 1.378.139 2.8.62 3.681 1.02A.5.5 0 0 0 16 13.5v-11a.5.5 0 0 0-.293-.455c-.952-.433-2.48-.952-3.994-1.105C10.413.809 8.985.936 8 1.783z"/> </svg>{{cat.category_name}} </a> {% endfor %} </body> </html> Then If the user clicks on one of these … -
Annotating specific attributes of a Datetime Field - Cannot resolve keyword 'toordinal' into field. Join on 'created_at' not permitted
I'm developing a scoring system for posts on a website. It considers other relational fields (comments, views, and reactions_emojis) to have a more insightful way to order the results. But since it's not desirable to have popular posts, but too old, on the front page, I decided to consider the post creation time. The problem is, the DateTime value is too precise, and ordering by it would completely ignore the scoring system and return a simple chronological feed. While testing some solutions, I tried the toordinal built function to have a single value representing the days passed since January 1 of year 1. My idea was to concatenate this value with the post_hour and the result of (post_minute // 14). This way, there would be a 14 minutes window in which all posts would be ordered exclusively by their scores. It looks good enough, and any adjustments would be simple to make. Looking along with some SO posts and Django documentation, I found that I could do this by passing the attribute I was trying to access with a dunder inside an F expression: posts = Post.objects.all().annotate( score=((F("view_count")/20) + (Count("post_emojis")/10) + (Count("post_comments")/5)), ordinal_time=(F('created_at__toordinal')) ) This returns the following error: Cannot … -
Display multiple views in single page
I have a Django Webapp which has a few forms for adding data to the database. Once this data has been added, I want to present this on a dashboard. So I have views that were written that add the logic for the data to be presented, but as far as i can work out you only map 1 view to a template otherwise the data won't be displayed on the template. I think there is a way to pass the data as a context, but I can't get my head around how to write this for my view. A really simple view i have to display events def all_events(request): event_list = Event.objects.all() return render(request, 'pages/event_list.html',{'event_list': event_list}) I'm passing this to event_list which works fine. But if I % include % on the dashboard I get the HTML but not the data, which I now understand is right. But being an absolute bigger with Django, I could really do with an example of the above which I can then apply to all my other views. Thanks -
Python/Django looping over request object and display in a table
Hi so I have a file called b2c2.py where I am making a request to return my balances this request returns b'{"LTC":"0","DOG":"0","USD":"51075.676738623","ADA":"9493.1937","ETH":"3.4E-9","UST":"2977","LNK":"42.422","XLM":"0","GBP":"-58153.761361914","USC":"0.9999995","XRP":"78448.38","EOS":"0","BNB":"0","BTC":"-0.250000004644","EUR":"0.0026082","BCH":"0","DOT":"0","UNI":"0","AUD":"0","CAD":"0","CHF":"0","CNH":"0","ETC":"0","ICP":"0","JPY":"0","KSM":"0","MXN":"0","NZD":"0","SGD":"0","TRX":"0","XAU":"0","XMR":"0","XTZ":"0","ZEC":"0"}' I then pass this into my views.py called b2c2_response_content and pass it into the context, in my template I am then trying to loop through it to show the balance name and balance holdings in a table. But I am unsure on how I can do this for example I want it to display as bitcoin name in a column with its quantity in the column next to it and Ethereum in the row below with its name in one column and its quantity in the next column. Thank you for your help in advance.