Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Prefetch queryset when related_name="+"
Is it possible without related name (related_name="+") to prefetch objects on the target instance? Sure I know it's not a problem with the related name, but I'm not really sure if it's possible without it. Here is the example code: from django.db import models class Parent(models.Model): name = models.CharField(max_length=50) class Child(models.Model): parent = models.ForeignKey(to=Parent, related_name="+", on_delete=models.CASCADE) Parent.objects.all().prefetch_related('child_set') Maybe it's possible using the Prefetch(lookup, queryset=None, to_attr=None) object, because it takes the queryset in the argument list? -
Django type error: excepted string or byte types like object?
When I tried to publish blog an exception occurs "excepted string or bytes type object".I tried a lot but I don't know how to fix this . What I understand is that it is occuring because DateTimeField(default=timezone.now). I'm correct? This is the error I m getting on writing py maname.py runserver: File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\db\models\fields\__init__.py", line 1318, in to_python parsed = parse_datetime(value) File "C:\anaconda\envs\virblogEnv\lib\site-packages\django\utils\dateparse.py", line 107, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object [] "GET / HTTP/1.1" 500 139276 Not Found: /favicon.ico [] "GET /favicon.ico HTTP/1.1" 404 4283 Here is models.py:- from django.db import models from django.utils import timezone from django.urls import reverse class Post(models.Model): author=models.ForeignKey('auth.User',on_delete=models.CASCADE) title=models.CharField(max_length=200) text=models.TextField() created_date=models.DateTimeField(default=timezone.now) published_date=models.DateTimeField(blank=True,null=True) def publish(self): self.published_date=timezone.now self.save() def approve_comments(self): return self.comments.filter(approve_comments=True) def get_absolute_url(self): return reverse('post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post=models.ForeignKey('blog.Post',related_name='comments',on_delete=models.CASCADE) author=models.CharField(max_length=200) text=models.TextField() created_date=models.DateTimeField(default=timezone.now) approve_comment=models.BooleanField(default=False) def approve(self): self.approved_comment=True self.save() def get_absolute_url(self): return reverse('post_list') def __str__(self): return self.text Here is views.py:- from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from blog.forms import PostForm,CommentForm from blog.models import Post,Comment from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView,DetailView, CreateView,UpdateView,DeleteView) class AboutView(TemplateView): template_name='about.html' class PostListView(ListView): model=Post #generating a query to db (so this means that grab all … -
uwsgi static files loading error form django (react and webpack)
My app consists of django and react, which at the end is bundled to static (.js) file. My goal is to setup a nginx for it, but for now I just want to run in uwsgi to see if it works. Aaaaand it does not work at all. I belive there is a issue with loading this bundle file which webpack is compiling. Connection to uwsgi works, server is up and running, but when connecting to 127.0.0.1:8080 I get (in Mozilla): The resource from “http://127.0.0.1:8080/static/frontend/main.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). # and another GET http://127.0.0.1:8080/static/frontend/main.js HTTP/1.1 404 Not Found Content-Type: text/html X-Frame-Options: DENY Content-Length: 3277 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Vary: Origin Similar topic I found: Difference between static STATIC_URL and STATIC_ROOT on Django and this: Django + React The resource was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff) But messing with python manage.py collectstatic resolved nothing. I have this lines of code to manage static files: STATIC_URL = '/static/' STATIC_ROOT = os.path.join('/app/label_it/front/static/frontend/') And this is how I start my uwsgi connection: python manage.py collectstatic --no-input uwsgi --http 0.0.0.0:8080 --master --enable-threads --module label_it.wsgi Beside collectstatic I've tried messing with <script src"static_file_path"></script> this static path … -
Django - Submit data from a HTML table into database
I am creating a restaurant application and I am currently trying to implement 'confirm order' functionality. I have rendered objects from my database onto a template, as each item is rendered, I assign a "Add to Basket" button that will do exactly that. The add to basket functionality works perfectly. Now, I am wondering how I can pass the data within my 'basket' (html table) to my database. I have found that I need to assign unique 'names' to each object that is being rendered in order to get them in views.py. I have done so. But how can I know which unique values that user has selected within the table? Is it possible to get the quantity and price fields as well? I believe forms will have to be used, but I am not sure how to go about it. takeaway.js function addToBasket(selected) { const itemDiv = selected.parentElement.parentElement; const itemName = itemDiv.getElementsByClassName("food-item-name")[0].innerText; const itemPrice = itemDiv.getElementsByClassName("food-item-price")[0].innerText; // check if item already in basket if (check(itemName)) { updateQuantity(itemName); updateItemPrice(itemName); } else { const basketTable = document.getElementById("basket"); const rowCount = basketTable.rows.length; const row = basketTable.insertRow(rowCount); const basketRowName = row.insertCell(0); const basketRowQuantity = row.insertCell(1); const basketRowPrice = row.insertCell(2) const basketRowTotalPrice = row.insertCell(3); … -
Can I change to a CustomUser model after the initial migration? Or I should've done it at the start of the project?
I'm trying to add custom user model mid project, and I might remember reading somewhere that you can't do that or that it isn't easy to do so, is that true? What can I do now? -
Can someone explain how to deploy django application on linux server inside my organization?
Can someone help me with the step by step process to be followed using nginx and gunicorn / or some other easier method,or some usefull links so that i can follow. Thanks in advance ! -
Django: Iterate on inlineformset_factory - update existing model's fields
I have a project that includes several "list" models, and multiple "list item" models for each list. Here are my models: class List(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class ListItem(models.Model): team_list = models.ForeignKey(List, on_delete=models.CASCADE) content = models.TextField() list_index = models.IntegerField() def __str__(self): return f"{self.team_list} [{self.index}]" the "list index" field is for use in another feature of my project. Essentially, each item in the list will have an index number 1 - whatever the total number of items in the list are. This list index number is where I'm running into trouble. I am working on a list edit view where the user can add additional items to the list. Here is my urls: urlpatterns = [ path('edit_list/list<int:list_pk>/', views.edit_list, name='edit_list'), ] and here is the corresponding view: def edit_list(request, list_pk): theList = List.objects.get(pk=list_pk) listForm = EditListForm(instance=theList) listItemForm = inlineformset_factory(List, ListItem, fields=('content',)) context = { 'title': 'Edit List', 'list_form': listForm, 'list_item_form': listItemForm(instance=theList), } if request.method == 'POST': listForm = EditListForm(request.POST) listItemForm = listItemForm(request.POST, instance=theList) if listForm.is_valid and listItemForm.is_valid: listItemInstance = listItemForm.save(commit=False) index = 1 for form in listItemInstance: form.list_index = index index += 1 listItemForm.save() listForm.save() messages.success(request, "List has been updated!") return redirect('home') else: messages.error(request, 'Something went wrong...') return render(request, … -
javascript and django views not updating shipping cart if user not logged in
Following a YouTube tutorial on making an ecom app and everything seems ok except that when I sign out it won't add items to cart although the logic is there for anonymous users. Once user is logged in everything works great. when I call the url on chrome it gives me this error: JSONDecodeError at /update_item/ Expecting value: line 1 column 1 (char 0) here is the javascript snippet: for(var i = 0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action', action ) console.log('USER:', user) if(user == 'AnonymousUser'){ console.log('Not logged in') }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is logged in, sending data...') var url = '/update_item/' fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId': productId, 'action': action}) }) .then((response) =>{ return response.json(); }) .then((data) =>{ console.log('data:', data) location.reload() }) } I get this on firefox console when I try to add items to cart manually (user not logged in): productId: 1 action add cart.js:8:17 USER: AnonymousUser cart.js:10:17 Not logged in The django view responsible for this part: def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('action:', action) print('productId:', productId) customer = request.user.customer … -
SyntaxError in Python3.9 datetime.py
I have Python 3.9 (/usr/bin/python3.9) with Django 3.1.6 and with Apache2 want to run my application. But on the browser is error 500 Internal Server Error and in log of Apache I'm getting SyntaxError in datetime.py: mod_wsgi (pid=25852): Target WSGI script '/path/to/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=25852): Exception occurred processing WSGI script '/path/to/wsgi.py'. Traceback (most recent call last): File "/path/to/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application File "/usr/lib/python3.9/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/usr/lib/python3.9/site-packages/django/utils/version.py", line 1, in <module> import datetime File "/usr/lib/python3.9/datetime.py", line 889 raise ValueError(f'Invalid isoformat string: {date_string!r}') ^ SyntaxError: invalid syntax I'm already desperate. -
PageNotAnInteger at /products/ That page number is not an integer
So I'm trying to use pagination in django, When I click on previous it takes me to localhost:8000/thatpage/?page= when it is supposed to take me to the previous page, It also gives me error on that page. I have tried handling it in my views.py but it doesn't work. I have also tried using books_obj.previous_page_number but that doesn't work too. I'm using Django 3.1 views.py def showproducts(request): oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True) lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True) hehe = CartItem.objects.filter(user=request.user) category = Category.objects.all() haha = Paginator(Book.objects.all(), 2) page = request.GET.get('page') if page is None or "": page = 1 fianlprice = 0 for item in hehe: fianlprice += item.book.price # books = Book.objects.all() books = haha.page(page) return render(request, 'main/products.html', {'books':books, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category}) products.html <h1>Products</h1> <h1>{{ error }}</h1> {% if user.is_authenticated %} <h1>Your cart currently costs ${{ price }}</h1> {% else %} <h1>Please login to view your cart</h1> {% endif %} <form method="GET" action="/search/"> <label>Choose a category</label> <select name="category" id="category"> <option value="All" selected>All</option> {% for name in category %} <option value="{{ name.name }}">{{ name.name }}</option> {% endfor %} </select> <input type="text" placeholder="Search here" name="search" id="search"> <button type="submit">Search</button> </form> {% for book in books %} <a href="{% url 'detailview' book.id %}"><h3>{{ book.name … -
Get a django instance that is selected with the mouse
I define in django a class called Scenario. The view of Scenario is this: If you want to use the button called "Check Issues", you have to click with your mouse on one scenario, in this case you only can click on "s1" or "s2". The button call a python function called gen_issues, here is the code: def get_urls(self): urls = super().get_urls() my_urls = [ django.urls.path('issue/', self.gen_issues), django.urls.path('duplicate/', self.gen_duplicate), ] return my_urls + urls def gen_issues(self, request): if len(request.user.username) > 0: queryset=super().get_queryset(request) #scenarios = Scenario.objects.filter(user=request.user.username) if len(queryset) == 1: sv = ScenarioVerifier(queryset[0]) sv.verify() return HttpResponseRedirect("../") else: self.message_user(request,len(queryset) ,level=messages.ERROR) return HttpResponseRedirect("../") But It doesn't work because I don't know how to get the clicked scenario, so the queryset in the function "gen_issues" is wrong beacuse it has two elements, i.e, all the scenarios, not the selected with the mouse. So my question is how can get the selected scenario with the mouse in order to can use it inside my function. -
In Django, what is the difference between Trunc and Extract Django database functions?
In Django what is the difference between using Trunc and Extract functions on datetime fields in queries? For example, is there a difference between TruncYear() and ExtractYear()? Are the edge cases handled the same? When should one be preferred over the other? -
csrf_exempt set but CSRF Failed: Referer checking failed - no Referer
I have a backend API, it's in django and deployed on Google Endpoint. I have a post request that insert data to my DB. I created a script to use this endpoint but I got this error: {"detail":"CSRF Failed: Referer checking failed - no Referer."} Regarding over posts I added the crsf_exempt decorator to my class but it did not change. I try to add the decorator two ways: class AddUser(APIView): """ Create user and company from csv """ @method_decorator(csrf_exempt) def post(self, request): @method_decorator(csrf_exempt, name='dispatch') class AddUser(APIView): """ Create user and company from csv """ def post(self, request): But both failed. This is how I contact my endpoint: resp = requests.request( method, url, headers={'Authorization': 'Bearer {}'.format( open_id_connect_token)}, **kwargs) Any ideas ? Thanks -
How to store password of user id (from user model) in another separate table and maintain one to one relation between those table based on userid
How to store password of user id (from user model) in another separate table(say password_table) and maintain one to one relation between those table based on userid # -
get django variable by javascript variable
I want to get variable stored in Django admin by using JavaScript variable for ex: var x = 2; console.log("{{product.0}}") //by this I get data from admin console.log( "{{product." + x + "}}" ) //but by this it shows couldn't parse reminder +x+ I want that I get my data by using that x variable -
how to get user based on username?
How can i get the user profile based on his username not id , i tried with only slug_filed it shows me that there is no username choice , and i made this get object method but it didn't work views.py class ProfileDetail(DetailView): model = Profile template_name = 'profile.html' slug_field = "username" def get_object(self): username = self.kwargs.get('username') return get_object_or_404(User, username=User.username) models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField() picture = models.ImageField(upload_to='profile_pics') def __str__(self): return str(self.user) def save(self, *args, **kwargs): super().save(*args, **kwargs) urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from users.views import register, UpdateUserView, ProfileDetail from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), path('register', register, name="register"), path('accounts/', include('allauth.urls')), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('settings', UpdateUserView.as_view(), name='settings'), path('profile/<slug>', ProfileDetail.as_view(), name='profile'),] -
How to set a string value to django model Id?
I am new to web development. I want to manually define the identifiers of a model. So I add "id = models.AutoField (primary_key = True)" in my model class: mymodel class (models.Model): id = models.AutoField (primary_key = True) When trying to set a string id I got the following error: The "id" field was expecting a number but got "Activity_0m91i8s". Activity_0m91i8s is the string id Is there a way to define the id string? Thank you -
Cannot see blog posts in index.html
I am trying to make a simple blog website. I have created my files and models. The page shows up fine, and the admin works. However, the blogs do not reflect on index.html from the admin page. I included the app in settings.py. All the other pages work, so I don't think the issue is with the file structure. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone class Todo(models.Model): title = models.CharField(max_length=100) memo = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) important = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=200, default='', unique=True) first_name = models.CharField(max_length=50, default='', editable=False) last_name = models.CharField(max_length=50, default='', editable=False) body = models.TextField(default='') def __str__(self): return self.title urls.py (Project) from django.contrib import admin from django.urls import path, include from todo import views urlpatterns = [ path('admin/', admin.site.urls), # Auth path('signup/', views.signupuser, name="signupuser"), path('logout/', views.logoutuser, name='logoutuser'), path('loginuser/', views.loginuser, name='loginuser'), # Todos path('', views.home, name='home'), path('', include('todo.urls')), path('index/', views.index, name="index"), path('detail/', views.detail, name="detail"), path('current/', views.currenttodos, name="currenttodos"), path('create/', views.createtodo, name='createtodo'), path('completed/', views.completedtodos, name="completedtodos"), path('todo/<int:todo_pk>', views.viewtodo, name='viewtodo'), path('todo/<int:todo_pk>/complete', views.completetodo, name='completetodo'), path('todo/<int:todo_pk>/delete', views.deletetodo, name='deletetodo'), path('hotel/', views.hotel, name="hotel"), path('things/', views.things, name="things"), path('restaurant/', views.restaurant, name="restaurant"), path('review/', views.review, name="review"), … -
HTML operators in django
I'm trying to compare actual_time and taken_seconds, but less than operators (<) show in red color, and it actually not compare the numbers.As per image, 6<12, it should say Time taken is higher than actual time of gesturing <h5>Actual time: {{ actual_time }} seconds</h5> <h5>Taken time: {{ taken_time }} seconds ({{ taken_seconds }} seconds)</h5> <h5>Point: {{ point }}</h5> {% if actual_time < taken_seconds %} <div class="alert alert-warning" role="alert"> Time taken is higher than actual time which may lead to fatigue. </div> {% elif actual_time > taken_seconds %} <div class="alert alert-success" role="alert"> Time taken is lower than actual time of gesturing. </div> {% endif %} -
How do I build like functionality using django and djangorestframework?
I'm using Django and DjangoRestFramework to build a social media app, and I am having some issues building the functionality for the like button on the backend. Here is a walkthrough of my current code and the error I am getting: models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True) class Meta: ordering = ('-created_at',) class Like(models.Model): post = models.ForeignKey(Post, related_name='likes', on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='likes', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) serializers.py from rest_framework import serializers from apps.feed.models import Post, Like class PostSerializer(serializers.ModelSerializer): class Meta: model = Post read_only_fields = ( "id", "created_at", "created_by", ) fields = ( "id", "created_at", "created_by", "content", ) class LikeSerializer(serializers.ModelSerializer): class Meta: model = Like read_only_fields = ( "id", "created_at", "created_by", ) fields = ( "id", "created_at", "created_by", "post" ) views.py from rest_framework import viewsets from apps.feed.models import Post from apps.feed.serializers import PostSerializer, LikeSerializer from django.contrib.auth import get_user_model from .models import Post User = get_user_model() class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() def perform_create(self, serializer): serializer.save(created_by=self.request.user) def get_queryset(self): return self.queryset.filter(created_by=self.request.user) class LikeViewSet(viewsets.ModelViewSet): serializer_class = LikeSerializer def perform_create(self, serializer): serializer.save(created_by=self.request.user) The error when I press the like button: # This is … -
display images in select option for selection -Django Python
I am working on a PRoject and I am stuck on order page. Here, I want to display list of product images in options tag so that a user can select one image from all or can upload an image functionality of uploading image is working correctly but the selection is not working. I want to show images to user so that user can select one of them. models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) class ImageTemplate(models.Model): temp_id = models.AutoField("Template ID", primary_key=True, auto_created=True) temp_img = models.ImageField("Template Image", null=False) class ImageTemplateProductMapping(models.Model): imageTemp_p_map_id = models.AutoField("Template Image & Product Map ID", primary_key=True, auto_created=True) temp_id = models.ForeignKey(ImageTemplate, null=False, on_delete=models.CASCADE, verbose_name="Image Template ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") views.py def order(request, id): products = Product.objects.all() ImageTemplateProductsList = [] try: ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id) ImageTemplateProductsList = [data.temp_id.temp_img for data in ImageTemplateProductsMap] except AttributeError: pass context = {'products': products, "ImageTemplateProductsList": ImageTemplateProductsList } return render(request, 'user/order.html', context) order.html {% extends 'user/layout/userMaster.html' %} {% block title %}Order{% endblock %} {% block css %} form { position:relative; } .tasksInput { margin-right:150px; } label { vertical-align: top; … -
How to delete django dynamic formset with java script - issue with index?
In my template i'm using a formset to add a "Raum"-form dynamic. In each row of my table, there is a button "delete row", so that i can delete the row again. the java script code is as far as i can say is working quite well... Adding and saving the forms works fine. Also deleting with the java script code works fine. Even when i delete the last row of the table, saving the forms works fine. But when f.e. i add 3 rows (rooms), row1-row2 and row3, and i delete row 1 or row 2, i can not save my forms, because i think in view.py the is_valid method = false... maybe i have to update some kind of index of my forms??? and how ?? any help is really apprecheated... html template for adding rooms with the table and forms: <table id="tableHeadToModify" class="table table-bordered"> <thead class="hg-rot schrift-weiss"> <tr> <th colspan="2">Räume</th> </tr> {% for raum in raum_formset %} {% if forloop.first %} <tr> <th>{{ raum.name.label_tag }}</th> <th>{{ raum.name.label_tag }}</th> </tr> {% endif %} {% endfor %} </thead> <tbody id="tableToModify"> {{raum_formset.management_form}} {% for raum in raum_formset %} <tr id="rowToClone"> <td> {{ raum.name }} </td> <td><button type="button" value="Delete" onclick="deleteRow(this)"></td> </tr> … -
How to get username at end of url using slug
I'm trying to get the users username at the end of the 'my-profile' url , I have used autoslug on url ("users/") and this is working fine for 'profile_view' , but it's not working with 'my_profile' , can you tell me what I'm doing wrong. At the moment i'm getting error: NoReverseMatch at / Reverse for 'my_profile' with no arguments not found. 1 pattern(s) tried: ['my\-profile/(?P[^/]+)$'] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('feed.urls')), path('users/', user_views.users_list, name='users_list'), path('users/<slug>/', user_views.profile_view, name='profile_view'), path('friends/', user_views.friend_list, name='friend_list'), path('users/friend-request/send/<str:username>/', user_views.send_friend_request, name='send_friend_request'), path('users/friend-request/cancel/<str:username>/', user_views.cancel_friend_request, name='cancel_friend_request'), path('users/friend-request/accept/<str:username>/', user_views.accept_friend_request, name='accept_friend_request'), path('users/friend-request/delete/<int:id>/', user_views.delete_friend_request, name='delete_friend_request'), path('users/friend/delete/<int:id>/', user_views.delete_friend, name='delete_friend'), path('edit-profile/', user_views.edit_profile, name='edit_profile'), path('my-profile/<slug>', user_views.my_profile, name='my_profile'), path('search_users/', user_views.search_users, name='search_users'), ] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') slug = AutoSlugField(populate_from='user') bio = models.CharField(max_length=255, blank=True) friends = models.ManyToManyField('Profile', blank=True) def __str__(self): return str(self.user.username) def get_absolute_url(self): return "/users/{}".format(self.slug) views.py @login_required def profile_view(request, slug): p = Profile.objects.filter(slug=slug).first() u = p.user sent_friend_requests = FriendRequest.objects.filter(from_user=p.user) rec_friend_requests = FriendRequest.objects.filter(to_user=p.user) user_posts = Post.objects.filter(user_name=u) friends = p.friends.all() # is this user our friend button_status = 'none' if p not in request.user.profile.friends.all(): button_status = 'not_friend' # if we have sent him a friend request if len(FriendRequest.objects.filter( from_user=request.user).filter(to_user=p.user)) == 1: button_status = 'friend_request_sent' # if we have received … -
How are you able to extract a count within a StructValue in Django framework?
My html code in Django is {{ self }} and it will output as follows StructValue([('Title', 'Product 30'), ('Image', None), ('Cards', [StructValue([('Document', <Document: blah>)])])]) How am I able to manipulate this HTML to get the number of documents within {{ self.cards }}? For example i have tried {{ self.cards.document.count }} with no success. Am I even just looking at this the wrong way? -
How to point django form to pk?
I am trying to make a form that is dynamically selected by a DetailView object. I want to click the DetailView link and be taken to a form whose primary key is the same as the primary key from my detail view. When I attempt to do this I get an error. How can I do this? Is their a prebuilt library that will assist me? My Model: ''' class MemberStudent(models.Model): instructor = models.ForeignKey(Teachers, on_delete=models.CASCADE) name = models.CharField(max_length=50, default="Doe") age = models.IntegerField(default=99) def __str__(self): return self.name def get_absolute_url(self): return reverse('student_detail', args=[str(self.id)]) class BehaviorGrade(models.Model): SEVERITY = [ ('Bad','Bad Behavior'), ('Good','Good Behavior'), ('Danger','Dangerous'), ] LETTER_GRADE = [ ('A','A'), ('B','B'), ('F','F'), ] studentName = models.ForeignKey(MemberStudent, on_delete=models.CASCADE) #need a link to student name eventGrade = models.CharField(max_length=1, choices=LETTER_GRADE) eventSeverity = models.CharField(max_length=15, choices=SEVERITY) eventTitle = models.CharField(max_length=15) eventDescription = models.TextField() def __str__(self): return self.eventTitle ''' My Views: ''' class StudentDetailView(FormMixin,DetailView): model = MemberStudent template_name = 'student_detail.html' form_class = BehaviorForm def get_success_url(self): return reverse('student_detail', kwargs={'pk':self.object.pk}) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): form.save() return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): return super().form_valid(form) ''' my forms.py: ''' class BehaviorForm(ModelForm): class Meta: model = BehaviorGrade fields = ['eventGrade', 'eventSeverity','eventTitle', 'eventDescription'] ''' my url: …