Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get_object_or_404 only for DetailView
Im new to programming, im working on a app to study a given topic, and after I read the topic, im showing some flashcards, but I want to show only the flashcards related to the topic, but I always get more then one Deck of flashcards, probably because I'm not getting the correct deck_id. Here is the code: models.py: class Topic(models.Model): author = models.ForeignKey( User, related_name="topic", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100) body = RichTextUploadingField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=120) class Meta: ordering = ["title"] def __str__(self): return self.title def get_absolute_url(self): return reverse('topic:topic-detail', kwargs={ "topic_slug": self.slug,}) class Deck(models.Model): deckTopic = models.ForeignKey( Topic, null=True, blank=True, on_delete=models.CASCADE) description = models.CharField(max_length=510, null=False, blank=True) is_active = models.BooleanField(default=False) def __str__(self): return self.description def get_number_of_cards(self): ''' Returns the number of cards in the decks related card_set ''' return self.card_set.count() get_number_of_cards.short_description = 'Card Count' class Card(models.Model): parentDeck = models.ForeignKey(Deck, on_delete=models.CASCADE) front = models.TextField() back = models.TextField() def __str__(self): return self.front def has_prev_card(self): ''' Returns true if card is not thee first card in the deck. ''' first_card_in_deck = self.parentDeck.card_set.first() if self == first_card_in_deck: return False return True def get_prev_card(self): ''' Return previous card in deck ''' return self.parentDeck.card_set.filter(id__lt=self.id).last() def has_next_card(self): ''' Returns true if card is … -
Clearing out redis from celery tasks that has finished
I'm using celery task queue which use Redis as a message broker to run some background tasks that save results to Redis. I wanted to clear out Redis from task results that did finish because i no longer need them and so in case of having a big spike I shouldn't worry. I came across CELERY_RESULT_EXPIRES which indicates that a task result will automatically clean up after X seconds. Consider the following code: from celery import Celery CONFIG = { 'BROKER_URL': 'redis://localhost:6379/0', 'CELERY_RESULT_BACKEND': 'redis://localhost:6379/0', 'CELERY_RESULT_EXPIRES': 15, # 15 secs 'BROKER_POOL_LIMIT': 0, # redis connection get closed once task is done.. } celery = Celery('tasks', config_source=CONFIG) @celery.task(name='tasks.say_hello') def say_hello(): return "Helloooooo i just came out from the background!" say_hello.delay().get() When running the code above and having celery beat -A tasks -l info running too, then checking Redis after a while (more than 5mins) I see this: 127.0.0.1:6379> KEYS * 1) "_kombu.binding.celery" 2) "_kombu.binding.celery.pidbox" 3) "_kombu.binding.celeryev" 4) "celery-task-meta-854543d8-14ad-4bf8-9725-edcf64131bb2" 5) "celery-task-meta-fa3e267e-46d0-4488-a766-d3276b6abdeb" 6) "celery-task-meta-86c2d83c-cadd-41b9-b4ff-426607786299" Tasks 4 to 6 which were completed still there! Isn't the results supposed to clear out after 15 seconds, Am I missing something here? Thanks in advance. -
my error message is not displaying on my web site using python, Django, and html
I am using Django to make a website similar to wiki for a project. The code below is where I'm having some trouble. I want it to display an error message that I made, but it keeps saying "no item" when I put a title that isn't on the web site. I have another part that uses this error in my "create" page that displays the correct error when putting the same name for a title that already exists. def entry(request, title): entries = util.list_entries() if title in entries: page = util.get_entry(title) page_converted = markdowner.convert(page) return render(request, "encyclopedia/entry.html", {"page": page_converted, "title": title, "form":SearchForm()}) else: return render(request, "encyclopedia/error.html", {"form": SearchForm(), "error": "The requested page could not be found or doesn't exist" }) this is the error html {% extends "encyclopedia/my-layout.html" %} {% block title %} Error {% endblock %} {% block body %} <h1 class="errors" style="padding: 30px;">{{ error }}</h1> {% endblock %} this is the entry html {% extends "encyclopedia/my-layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <div style="border: 1px solid black; padding: 20px; margin-right: 16px;"> {{ page | safe }} <a href=/edit/{{title}}>Edit Page</a> </div> {% endblock %} and this is the working … -
django-oscar2.1 giving errors on is_public field. Its a model loading issue
I am migrating to django-oscar2.1 I have forked catalogue app, it has some existing migrations. Newly added field is_public is in migration #10. I have a custom migration #5 which is using create_from_breadcrumbs method. So when I tried to run migrate on fresh db migration#5 trigger error is_public field not exists in db. create_from_breadcrumbs Oscar loads a model with latest state which contains is_public in models but not in db. In migration #5 I am loading model like this Category = apps.get_model("catalogue", "Category") -
I am having problem installing wkhtmltopdf on my docker container for a Django application?
I am using pdfkit in my django application and it seems to be working fine after I installed wkhtmltopdf on my machine. But when I build a docker image of my application for production and run it locally, it gives me OS Error for docker image. I have tried everything I found on the web but can't seem to install wkhtmltopdf on my docker container. Here's my Docker File for building an image, this gives error while installing the package. FROM python:3.6.9 RUN wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.1/wkhtmltox-0.12.1_linux-wheezy-amd64.deb RUN dpkg -i ~/Downloads/wkhtmltox-0.12.1_linux-wheezy-amd64.deb WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Here's the error I get in the terminal while building the image Here's the error without wkhtmltopdf in docker -
Django setting initial dropdown value from current instance?
I am trying to set the initial choices in a dropdown, on profile edit for selecting Business type. But I want the dropdown to already have the current instance' selections already chosen. But I just cant figure out how to render this on the frontend. I heard of a select option that jinja template offers, to do this? I will take a code snippet from my app, def edit_profile(request): request_user = request.user # FOR SENDING USER TO SERVER if request.method == 'POST': template_name = 'business/profile_view.html' first_name = request.POST['first_name'] business = request.POST.getlist('business_type', '') if business == '': pass try: user_obj = Account.objects.get(email=request.user) """ Loop over business types and assign to user """ user_obj.business.clear() for _business in business: user_obj.business.add(_business) return redirect('/auth/edit_profile/') except Exception as e: message = {"message": "Profile edit ERROR"} return render(request, template_name, message) # FOR SERVER TO USER if request.method == 'GET': template_name = 'business/profile_view.html' context = dict() user_obj = Account.objects.get(email=request.user) context['business_type'] = user_obj.business if request.path == '/auth/edit_profile/': return render(request, template_name, context) elif request.path == '/auth/edit_profile_edit/': return render(request, 'business/profile_edit.html', context) And my Template <select class="selectpicker" name="business_type" multiple="multiple"title="Select a category"> {% for business in business_types %} <option value="{{ business.id }}">{{ business.name }}</option> {% endfor %} </select> -
Why is my django unittest failing a constraint?
I have this model: class TestopiaEvent(Model): event_id = AutoField(primary_key=True) name = CharField(max_length=255) start_date = DateField() end_date = DateField() testers_required = IntegerField() class Meta: constraints = [ CheckConstraint( check=Q(start_date__lte=F('end_date'), start_date__gte=datetime.now().date()), name='correct_datetime' ) ] And this test: class TestopiaEventTestCase(TestCase): def setUp(self): self.default_values = { 'name': 'Testopia 1', 'start_date': datetime.now().date(), 'end_date': datetime.now().date() + timedelta(days=1), 'testers_required': 1 } self.testopia_event = TestopiaEvent(**self.default_values) def test_save_with_valid_model_check_database(self): self.assertIsNone(self.testopia_event.save()) And it fails with this error: django.db.utils.IntegrityError: new row for relation "webserver_testopiaevent" violates check constraint "correct_datetime" DETAIL: Failing row contains (1, Testopia 1, 2020-07-24 00:00:00+00, 2020-07-25 00:00:00+00, 1). I don't understand why it is failing as it should only fail if today's date is less than the start date and the start date or/and the start date is greater than the end date, which it isn't? What have I done wrong? Thanks -
Resources for designing document management system (dms) [closed]
This is pretty open-ended, but I'm looking for guidance in designing a simple file management system, preferably in Python, though React is sufficient. The goal at the start is just a simple web app where users can sign in, upload files, and manage all of the files they've uploaded. So far, I've done a fair bit of research, and already tried using Django-Filer, though on its own I found it was too difficult to transition its admin widget to a standalone app. I've come across plenty of options, like Mayan DMS, but no options, both open source and commercial, seem reliable. I appreciate any advice. I'd rather not design it all from scratch, but with each passing day it's beginning to feel like that's what I'll have to do :( -
How to add property to Django self.request
I am using DRF and token based auth and need to frequently access a property called request.user.organization_id in my views. The organization_id is not stored in my user table, so I need to find a way to add it to the request.user object. I tried but failed at adding this property via middleware. How should I go about this? Here is my middleware code: class UserOrganizationMiddleware(MiddlewareMixin): def process_request(self, request): primary_organization = OrganizationUser.objects.get(user=request.user).first() request.user.organization_id = primary_organization.organization With my current middleware, request.user comes back as an anonymous user, even when I am logged in. My middleware is placed AFTER my authentication middleware in my settings file, but this still happens. user model: class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True) uuid = models.UUIDField(primary_key=False, unique=True, default=uuid4, editable=False) first_name = models.CharField(_('First Name'), max_length=50) last_name = models.CharField(_('Last Name'), max_length=50) email = models.EmailField(_('Email address'), unique=True) -
Django: passing a URL parameter to every instance of a reverse URL lookup in a template tag
Sorry if the title is unclear, I'm not sure the best way to describe the issue. I have an application with a Ticket model and a Team model. All Tickets are associated with a single Team. The issue I'm having is a problem of URL reversing. I'm trying to set it up my URLs like so: /<team_pk>/tickets/ displays a list of tickets associated with the Team specified by team_pk. So /1/tickets/ would display all of the tickets for the first Team. Both of these objects are in the app tracker. To do this, I've set up my project/urls.py files like so: project/urls.py urlpatterns = [ path('<team_pk>/', include('tracker.urls', namespace='tracker')), ] tracker/urls.py urlpatterns = [ path('tickets/', views.TicketTable.as_view(), name='ticket_list'), ] Then, inside my html templates, I have the following URL tag: href="{% url 'tracker:ticket_list' %}" This results in a NoReverseMatch error: NoReverseMatch at /1/tickets/ Reverse for 'ticket_list' with no arguments not found. 1 pattern(s) tried: ['(?P<team_pk>[^/]+)/tickets/$'] What I would like is for the reverse match to just use the current value for the team_pk URL kwarg. What I have tried to fix it: I have found the following solution to the problem, but it involves a lot of repetition, and I feel like … -
Extend django.rest_framework.serializers.ModelSerializer to model property fields?
I am using this serializer to query and return some json objects. class MyModelPathSerializer(serializers.ModelSerializer): class Meta(): model = MyModel fields = ('setup', 'path') depth=1 I am interesting in returning a property of of my model rather than a field though. class MyModel(models.Model): setup = models.ForeignKey(Setup, on_delete=models.CASCADE) @property def path(self): return '/some/path/' Is there a way to modify the serializer class so that also properties are returned? -
all comments are linked to all posts
I was trying to make a blog where some user could post and then comment to it. But now I am seeing that my comments are connecting to all the posts. I mean that when I am clicking on a post normally I should only see the comments to it but I am seeing all the comments. Thank you very much. models.py from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify # Create your models here. class PostModel(models.Model): post = models.TextField(max_length=256, unique=True) slug = models.SlugField(max_length=20, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='post_author') created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.post) super().save(*args, **kwargs) def __str__(self): return self.post class CommentModel(models.Model): post = models.ForeignKey('dictionary.PostModel', on_delete=models.CASCADE, related_name='post_comment') comment=models.TextField(max_length=256,unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='comment_author') created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def get_absolute_url(self): return reverse("comment_detail",kwargs={'pk':self.pk}) def __str__(self): return self.comment views.py from django.shortcuts import render,redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.views import generic from django.views.generic.edit import FormMixin from .models import PostModel,CommentModel from .forms import PostForm,CommentForm # Create your views here. class PostList(LoginRequiredMixin,generic.CreateView): template_name = 'home.html' form=PostForm model = PostModel fields=['post'] success_url="/home" def form_valid(self, form): form.instance.author=self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context … -
Follow/following system Django - how to check if user is already following
Trying to build a follow/following system with Django. The model seems to be working but I'm running into issues trying to perform an "already-following" check in my view. Here is the view: class FollowView(View): model = UserRelationships def get(self, request, username=None): user = self.request.user viewed_user = User.objects.get(username=username) if user not in viewed_user.followers.all(): UserRelationships.objects.create(user_id=user, following_user_id=viewed_user) data = {} return HttpResponse(data) At this point, a new object gets created each time I hit the "Follow" button regardless if the user is already following. Here is the UserRelationships model: class UserRelationships(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="following") following_user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followers") created = models.DateTimeField(auto_now_add=True) And the two relevant URLs (base and specific app): path('accounts/<username>/', include('accounts.urls')) path('follow/', FollowView.as_view(), name='follow') And then I pass in the current user's username via a template tag for the HTML button. Any idea what I'm doing wrong here? Much appreciated! -
I want to add registeration to my web by django. I did all things right:
from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Tutorial from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User def register (request): form = UserCreationForm(request.POST) if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect("main:homepage") else: for msg in form.error_messages(): print(form.error_messages[msg]) return render(request, 'main/register.html', context={'form':form}) but still I get this error " 'dict' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: 'dict' object is not callable " -
python the if statement is executed even if the condition is false [duplicate]
this function goal is to count the vowels but the if statement is being executed in all the cases this is the code: def count_vowels(txt): count=0 txt = txt.lower() for char in txt: if char == "a" or "e" or "i" or "o" or "u": count = count+1 print(count) count_vowels(mark) it has to print 1 but it's printing 4 -
Can't retrieve data from POST in django view
I have issue with retrieving data from POST in my django view. I send React form values with axios to my django backend. I believe data gets put into POST but somehow it seems that there isn't any data in POST and i can't access it in my django view. What could be issue here? (I can also see in my console that values are successfully submitted) Source code: Django views.py: @csrf_exempt def send(request): if request.method == "POST": data = request.body('name') send_mail('Test 1', data, 'austin.milk1@gmail.com', ['lowoko9513@gomail4.com',], fail_silently=False) return redirect('/api/') React form handling: handleFormSubmit = (event) => { const name = event.target.elements.name.value; const email = event.target.elements.email.value; event.preventDefault(); axios.post('http://127.0.0.1:8000/api/send', { name: name, email: email }) .then(res => console.log(res)) .catch(error => console.err(error)); }; New error: File "C:\Users\austi\PycharmProjects\Fitex#1\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\austi\PycharmProjects\Fitex#1\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\austi\PycharmProjects\Fitex#1\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\austi\PycharmProjects\Fitex#1\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\austi\PycharmProjects\Fitex5\backend\src\training\api\views.py", line 78, in send data = request.body('name') TypeError: 'bytes' object is not callable -
Real life implementation of HybridDetailView that can return both HTML and JSON
Hey everybody! I want to implement AJAX to my filter results in my ListView (CBV). I discovered that I can return both HTML and JSON response with one view. I found a useful snippet in Django Documentation but lack of my Django experience didn't help me to understand how to implement in in real life project. Could you please help me by showing explanation or how can I implement it in my code? I am also getting this error when I add JSONResponseMixin to funtion argument as in their snippet, why?: /programs/views.py", line 62, in class ProgramListView(JSONResponseMixin, SingleObjectTemplateResponseMixin, ListView): NameError: name 'JSONResponseMixin' is not defined Is it better choice for filtering with ajax? What do you recommend to me? Below is the link and the snippet from Django Docs: The last snippet in the link from django.views.generic.detail import SingleObjectTemplateResponseMixin class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView): def render_to_response(self, context): # Look for a 'format=json' GET argument if self.request.GET.get('format') == 'json': return self.render_to_json_response(context) else: return super().render_to_response(context) My Code: Views.py from programs.models import Program from django.views.generic import ListView, DetailView from django.views.generic.detail import SingleObjectTemplateResponseMixin from django.http import JsonResponse import json from django.shortcuts import render from django.http import HttpResponse class ProgramListView(SingleObjectTemplateResponseMixin, ListView): model = Program template_name = … -
How to resolve Django crispy-forms Template Syntax Error
Hey I am trying to learn the Django crispy forms, so when I try putting/injecting the {load crispy_forms_tags %} I get the error below Error Message TemplateSyntaxError at /login/ 'crispy_form_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils i18n l10n log static tz Code Below: HTML {% load crispy_form_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0 /css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <title>Login</title> </head> <body> {% crispy form %} </body> </html> MODELS.PY from django.db import models from phonenumber_field.modelfields import PhoneNumberField class Accounts(models.Model): name = models.CharField(max_length=100, null=False, blank=False) last_name = models.CharField(max_length=100,null=False, blank=False) phone = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField(null=False, blank=False, unique=True) password = models.CharField(null=False, blank=False, max_length=100) verify_password = models.CharField(null=False, blank=False, max_length=100) def __str__(self): return self.name FORMS.PY class UserAccount(forms.Form): class Meta: terms = ( ('agree', 'Agree'), ('disagree', 'Disagree') ) model = Accounts password = forms.CharField(widget=forms.PasswordInput()) verify_password = forms.CharField(widget=forms.PasswordInput()) terms_and_conditions = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=terms) fields = ( 'name', 'last_name', 'phone', 'email', 'password', 'verify_password', 'terms_and_conditions' ) def __init__(self, *args, **kwargs): super().__init__(self, *args, **kwargs) self.helper = FormHelper self.helper.form_method = 'POST' self.helper.layout = ( 'name', 'last_name', 'phone', 'email', 'password', 'verify_password', 'terms_and_conditions', Submit('submit', 'Submit', css_class='btn-success') ) How can I resolve this error? -
Convert SQL query set into Django Model Query-set?
I want to convert the following query of SQL into Django Query-set:- select sum(amount) from accounts_order where status='Pending' and customer_id=1; -
How to pass request, request data and kwargs (all) to serializer in django
Hi, i was trying to pass the request and request data (both) in serializer . As my request contain other data ( like Authheader-Token, current domain info, etc). That i have to use in serialiazer. view.py @api_view(['POST']) def test(request): if request.method == 'POST': data = {'request': request, 'data': request.data} serializer = test_serializer(data=data) serializer.validate(data) return Response(status=status.HTTP_200_OK) serializer.py def validate(self, attrs): email = attrs['data'].get('email', '') try: user = User.objects.get(email=email) current_site = get_current_site(request=attrs['request']).domain {This is a part of code}. This code work fine , but it doesn't return exceptions , so try to use. serializer.is_valid(raise_exception=True) {for exception handling} But it always throws an validation exception. fields is required.(after passing data). Is There is any way, i can pass the both request and request.data with serializer.is_valid(raise_exception=True). Or any other way. -
(Django) RQ scheduler - Jobs disappearing from queue
Since my project has so many moving parts.. probably best to explain the symptom I have 1 scheduler running on 1 queue. I add scheduled jobs ( to be executed within seconds of the scheduling). I keep repeating scheduling of jobs with NO rq worker doing anything (in fact, the process is completely off). In another words, the queue should just be piling up. But ALL of a sudden.. the queue gets chopped off (randomly) and first 70-80% of jobs just disappear. Does this have anything to do with: the "max length" of queue? (but i dont recall seeing any limits) does the scheduler automatically "discard" jobs where the start time is BEFORE the current time? -
Django 3 ModelSerializier().data returns {}
I would like to create a route that returns some model properties as a JSON with the Django REST framework and filter them based on some properties. But I don't get the serializer to working properly. class MaxQuantPathSerializer(serializers.ModelSerializer): class Meta(): model = MaxQuantRun fields = ('project', 'raw_file', 'setup') depth = 2 class MaxQuantPathsAPI(generics.ListAPIView): def get(self, request, format=None): """ Return a list of all users. """ get_data = request.query_params print(get_data) queryset = MaxQuantRun.objects.all() print(queryset) data = MaxQuantPathSerializer(queryset).data print(data) return JsonResponse(data, status=201) >>> <QueryDict: {}> <QuerySet [<MaxQuantRun: SA | SA010-R1-blank-200425-R2.raw>, <MaxQuantRun: SA | SA002-R3-B-2ulf.raw>, <MaxQuantRun: SA | SA001-R3-H-2ulf.raw>, <MaxQuantRun: SA | SA010-R1-C-200425-R2.raw>, <MaxQuantRun: SA | SA1-fake.raw>]> {} The queryset returns some values but the serializer returns an empty dictionary. -
How to fix No Reverse Match error for Django
I am having this error any time i want to view posts that belong to a group NoReverseMatch at /groups/posts/in/python/ Reverse for 'user-posts' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['user/(?P[^/]+)$'] Below is my urls.py codes from django.urls import path from .views import (PostListView, PostCreateView, PostUpdateView, PostDetailView, PostDeleteView, UserPostListView) from . import views app_name = 'posts' urlpatterns = [ path('', PostListView.as_view(), name="blog-home"), path('user/<str:username>', UserPostListView.as_view(), name="user-posts"), path('post/<int:pk>/', PostDetailView.as_view(), name="post-detail"), path("post/<int:pk>/", views.post_comment, name="comments"), path('post/new/', PostCreateView.as_view(), name="post-create"), path('post/<int:pk>/update', PostUpdateView.as_view(), name="post-update"), path('post/<int:pk>/delete', PostDeleteView.as_view(), name="post-delete"), path('about/', views.about, name="blog-about"), ] The problem seems to be coming from my _posts.html file, but I cant resolve it, here is the _posts.html codes <div class="media"> <h3 class="mr-5"><a href="{% url 'posts:user-posts' username=post.user.username %}">@{{ post.user.username }}</a></h3> <div class="media-body"> <strong>{{ post.user.username }}</strong> <h5>{{ post.message_html|safe }}</h5> <time class="time"><a href="{% url 'posts:post-detail' username=post.user.username pk=post.pk %}">{{ post.created_at }}</a></time> {% if post.group %} <span class="group-name">in <a href="#">{{ post.group.name }}</a></span> {% endif %} </h5> <div class="media-footer"> {% if user.is_authenticated and post.user == user and not hide_delete %} <a href="{% url 'posts:post-delete' pk=post.pk %}" title="delete" class="btn btn-simple"> <span class="fa fa-remove text-danger" aria-hidden="true"></span> <span class="text-danger icon-label">Delete</span> </a> {% endif %} </div> </div> </div> Once I click on the group's list page to take me to posts … -
My Boolean Field is showing blank in django-admin list_display
I have a boolean field in my model, named paid_status and I want this field to be editable in list display. My model looks like this: class InvoiceInfo(BaseModel): invoice_number = models.CharField(max_length=100, unique=True, null=False, blank=False, default="") delivery_date_time = models.DateTimeField() net_payable_amount = models.FloatField(default=0, null=False, blank=False) paid_status = models.BooleanField(default=False) ONLINE_PAYMENT = 'SSLCOMMERZ' CASH_ON_DELIVERY = 'CASH_ON_DELIVERY' PAYMENT_METHOD = [ (ONLINE_PAYMENT, 'SSLCommerz'), (CASH_ON_DELIVERY, 'CashOnDelivery'), ] payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD, default=CASH_ON_DELIVERY) order_number = models.ForeignKey(Order, related_name='invoice', blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return 'OrderId: ' + str(self.order_number) + " " + "InvoiceNumber: " + str(self.invoice_number) And my admin.py looks like this: class InvoiceInfoAdmin(MaterialModelAdmin): list_display = ['id', 'invoice_number', 'order_number', 'delivery_date_time', 'paid_status', ] search_fields = ['invoice_number', 'order_number__pk'] list_editable = ('paid_status',) list_filter = ['created_on', 'delivery_date_time'] def save_model(self, request, obj, form, change): if obj.id: obj.modified_by = request.user obj.created_by = request.user obj.save() return super().save_model(request, obj, form, change) but when I do this, the paid_status field becomes blank in my admin panel; how can I fix this? Screenshot for reference: P.s. I am using material admin -
Django Get Foreign Key Value in Many-to-Many
relatively new to Django, so this is probably straightforward and just missing something. Given these models: class Manager(models.Model): mgrname = models.CharField(max_length=100) class Salesperson(model.Model): name = models.CharField(max_length=100) mgr_name = models.ForeignKey(SalesMgr,on_delete=models.CASCADE) class SalesList(models.Model): list_description = modesl.CharField(max_length=100) list_members = models.ManyToManyFiels('Salesperson') Each salesperson is assigned a manager (only one - managers have many salepeople). My user can create an arbitrary contact list ("SalesList") which contains any number of salespeople (salespeople can belong to many lists. A list may contain many sales people). I'm able to retrieve a list of salespeople on a selected list, but I need to include the sales manager name. How can I retrieve the manager name when the list is selected? Thank you!