Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
1 time of 10 get error json.decoder.JSONDecodeError: Expecting ','
i have this ugly noob func: def run_prog(compile_container, user_input, container_file_path): # bash doesnt support single quotes or quotes inside double quotes so @# = ' time_check_command = '/usr/bin/time -f "@# , @#memory@#:@#%M@# , @#time@#:@#%e@#"' result = compile_container.exec_run( f"/bin/bash -c 'echo {user_input} | {time_check_command} ./a.out'", workdir=container_file_path)[1].decode('utf-8') result = '{"result":"' + result + ',}' result = result.replace('@#', '"') result_dict = json.loads(result) if result_dict['time'] == '0.00': result_dict['time'] = '<0.01' return result_dict Most of time it retrun json like this: { "result": "888", "memory": "1792", "time": "<0.01" } But one time of 10 or mb 20 it raise an error and i dont know why. Same input always. Can u please tell what is wrong? -
Django run function periodically in background
I have a function that fetches data and needs to be run periodically. All I care about is running it every 30 seconds. I searched and found the following options - celery django-apscheduler Apscheduler I have tried Apscheduler using BackgroundScheduler and it has this problem that it'll run a new scheduler for each process. I am completely new to scheduling functions and have no idea which one I should use or if there is a better way. -
How to serialize a related object Django Rest Framework
class Flight(models.Model): field_1 field_2 field_3 class Approach(models.Model): flight_object(models.ForeignKey, 'Flight') approach_type number Approach is related as an InlineFormset. How can I serialize Approach nested into Flight with the ability to create new approach objects. I'm unsure of the correct terminology which is making this more difficult to realize. My goal is to create a new Flight object with Approach as a related object in the FlightForm from a React Native project. -
I want to get data from the user without them using a form
I'm currently working on a website which posts a web novel. I need a system to make user send the chapter id and get the chapter which uses that id maybe like: <a href="chapters/1">Chapter1</a> <a href="chapters/2">Chapter2</a> <a href="chapters/3">Chapter3</a> I don't want to create a specific html page for every novel chapter that we posts and use a system to maybe get the links "/chapter/id" part or send the id when clicked to an element and pull data from the database using the id given. I searched up in the net and couldn't find anything useful. Note: The database is like this; class Chapter(models.Model): chapter_id = models.IntegerField(primary_key=True, default=None) chapter_title = models.CharField(max_length=100, default=None) chapter_text = RichTextField(default=None) chapter_footnotes = RichTextField(default=None, blank=True) -
How to convert image from django template?
I have some HTML code. I have added some dynamic data from DB to the HTML code in Django/FastAPI. How can I generate an image of that template? Also, how can do the same in FastAPI> -
With Django REST framework, how do I parse a RESTful string parameter?
I'm using Python 3.9 with Django==3.1.4 djangorestframework==3.12.2 I want to pass a restful param ("author" string) to my GET method. In my urls.py file I have urlpatterns = [ ... path('user/<str:author>', views.UserView.as_view()), And then in my UserView class (defined in my views.py file), I have class UserView(APIView): def get(self, request): ... author = self.kwargs.get('author', None) but when i execute GET http://localhost:8000/user/myauthor I get the error TypeError: get() got an unexpected keyword argument 'author' What else do I need to do to properly access my RESTful param in the URL? -
django: how to display ManyToManyField in html file?
I want to display ManyToManyField in Django in html page. This code is in the models.py file: class Keyword(models.Model): keyword = models.CharField(max_length=20, null=True) rank = models.IntegerField(null=False) dateCreated = models.DateField(auto_now_add=True) def __str__(self): return '#' + self.keyword class Article(models.Model): CATEGORY = ( ('programming', 'programming'), ('language', 'language'), ('other', 'other') ) title = models.CharField(max_length=200, null=False) image = models.ImageField(null=True) content = models.TextField(null=False) category = models.CharField(max_length=45, null=False, choices=CATEGORY) dateCreated = models.DateField(auto_now_add=True) keyword = models.ManyToManyField(Keyword) def __str__(self): return self.title and in the views.py: def articles(request): article = Article.objects.all() keyword = Keyword.objects.all() context = { 'keyword': keyword, 'article': article } return render(request, 'articles.html', context) and in the html file: {% for item in article %} <tr> <th scope="row">{{item.id}}</th> <td>{{item.title}}</td> <td>{{item.image}}</td> <td>{{item.content}}</td> <td>{{item.category}}</td> {% for key in item.keyword.all %} <td>{{key}}</td> {% endfor %} </tr> {% endfor %} But nothing is shown in the keyword section in the html output. what do I do? -
Cannot assign "'Test'": "BlogPostComment.blog_post" must be a "BlogPost" instance
I am trying to create an REST API for posting comments. I am not using normal ```request.POST`` views as I don't want a new page redirect to submit a comment. My plan is to AJAX to comment. But I am getting this error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/blog/test/create_comment Django Version: 3.2.6 Python Version: 3.9.6 Installed Applications: ['blog', 'whitenoise.runserver_nostatic', 'rest_framework', 'django_summernote', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\My_Stuff\Blogistan\blog\views.py", line 44, in CreateComment serializer.create(request.data) File "C:\My_Stuff\Blogistan\env\lib\site-packages\rest_framework\serializers.py", line 939, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\My_Stuff\Blogistan\env\lib\site-packages\django\db\models\query.py", line 451, in create obj = … -
how to use js variable in Django template tag through a JS call to update html content?
I am trying to update the html content of a with id "samples-list" with a Django template tag that includes an html file with two parameters ({% include "measures/sample_list_rows.html" with object_list=classifier.samples search_filter=search %}). the first parameter object_list is populated by the Django object classifier.samples, the second parameter search is retrieved by the id of the clickable object that will generate the update (id="search=device:{{ device.serial_number }}, labsubstance:{{ classifier.substance.slug }}") $("[id^=search]").click(function () { var keys = $(this).attr('id').split('=') var search = keys[keys.length-1] $('#samples-list').html(`{% include "measures/sample_list_rows.html" with object_list=classifier.samples search_filter=search %}`) how can I use the javascript variable search in the search_filter parameter of the Django template tag? -
the first model is the price of the product and the second model is the input of the first model, multiplied by 4
I wanted to make 2 models for the price of my products, the first model is the price of the product and the second model is the input of the first model, multiplied by 4, how can I do the same, thank you -
Django admin object change action
I am developing a courier management service using Django. So far, I have made three models, Customer DelveryAgent Parcels Here is the Parcel model: class Parcel(models.Model): type = models.CharField(max_length=20) city = models.CharField(max_length=20) street = models.CharField(max_length=100) zip = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) status = models.CharField(max_length=100, choices=STATUS, default='pending') booked_by = models.ForeignKey(Customer, on_delete=models.CASCADE) delivery_agent = models.ForeignKey(DeliveryAgent) Initially, the parcel status is pending, and the delivery agent is None. When the admin assigns a delivery agent to the parcel from the admin site, I want the relative customer to get notified with the details of the delivery agent. How can I do that? -
Macbook Air M1 mysql issues
(base) touresouleymane@192 Prions Projects % python3 prions/manage.py runserver Exception in thread django-main-thread: Traceback (most recent call last): File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/init.py”, line 18, in from . import _mysql ImportError: dlopen(/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so Expected in: flat namespace in /Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/threading.py”, line 932, in _bootstrap_inner self.run() File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/threading.py”, line 870, in run self._target(*self._args, **self._kwargs) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/utils/autoreload.py”, line 53, in wrapper fn(*args, **kwargs) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/core/management/commands/runserver.py”, line 110, in inner_run autoreload.raise_last_exception() File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/utils/autoreload.py”, line 76, in raise_last_exception raise _exception[1] File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/core/management/init.py”, line 357, in execute autoreload.check_errors(django.setup)() File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/utils/autoreload.py”, line 53, in wrapper fn(*args, **kwargs) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/init.py”, line 24, in setup apps.populate(settings.INSTALLED_APPS) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/apps/registry.py”, line 114, in populate app_config.import_models() File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/apps/config.py”, line 211, in import_models self.models_module = import_module(models_module_name) File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/importlib/init.py”, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File “”, line 1014, in _gcd_import File “”, line 991, in _find_and_load File “”, line 975, in _find_and_load_unlocked File “”, line 671, in _load_unlocked File “”, line 783, in exec_module File “”, line 219, in _call_with_frames_removed File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/contrib/auth/models.py”, line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/contrib/auth/base_user.py”, line 48, in class AbstractBaseUser(models.Model): File “/Users/touresouleymane/opt/anaconda3/lib/python3.8/site-packages/django/db/models/base.py”, line 122, in … -
Unable to delete object from Django admin panel with MongoDB
I have a Django project using a MongoDB connected by Djongo. I created a simple model which looks like: from django.db import models # Create your models here. class Property(models.Model): name = models.CharField(max_length=128, blank=False) property_type = models.CharField(max_length=24, blank=True) include_on = models.CharField(max_length=256, blank=True) format_example = models.TextField(blank=True) notes = models.TextField(blank=True) After registering the model by using the line admin.site.register(Property) in the admin.py file I end up seeing my model appear. After adding a test Property I see the line The property “Property object (61226db9f4f416b206c706e5)” was added successfully. Which tells me the item was added. It also appears on the admin panel but it looks like: Property object (None) If I select the property I get an error that says: Property with ID “None” doesn’t exist. Perhaps it was deleted? If I try to delete the property I get a ValueError with error of: Field 'id' expected a number but got 'None'. Since I am currently learning Django/MongoDB I actually ran across the ValueError once before. The fix was to delete the entire database and start over. The issue is I don't want to run into this in the future and want to know what I have to do to fix it, or … -
Pass the same randomly generated list to both POST and GET views in python/django
I'm developing a quiz app which pulls a random subset of 3 questions the queryset Trivia. I can generate the random subset without issue and display 3 multiple choice questions. But when the user makes selections and submits, the trivia view generates a new random subset. Thus, user answers are then compared to correct answers of a new random subset rather than the initial subset that the user viewed. How can I create this random subset and use it in both the GET and POST methods of my view? That is, I want the queryset "trivia" to be identical in both GET and POST methods. Ideas? def trivia(request): trivia_id_list = Trivia.objects.values_list('id', flat=True) random_trivia_id_list = random.sample(list(trivia_id_list), min(len(trivia_id_list),3)) trivia = Trivia.objects.filter(id__in=random_trivia_id_list) if request.method == 'POST': correct = 0 incorrect = 0 total = 0 for t in trivia: print(request.POST.get(t.question)) print(t.answer) print() if t.answer == request.POST.get(t.question): correct = correct + 1 else: incorrect = incorrect + 1 total = total + 1 result = correct/total return render(request, 'ColdBlooded/result.html', { "Incorrect": incorrect, "Correct": correct, "Total": total, "Trivia": trivia, "Result": result, }) else: return render(request, "ColdBlooded/trivia.html", { "Trivia": trivia }) -
django DeleteView - how to pass a parameter to use for success_url?
I am using a DeleteView where the I want to the success_url to be the view that called the DeleteView. This success_url requires two parameters to be passed to it. urls.py path('listparts/<uuid:company_pk>/<uuid:worker_pk>/', views.listparts, name='listparts'), path('deletepart/<uuid:part_pk>/', views.PartDeleteView.as_view(), name='deletepart'), view def listparts(request, company_pk, worker_pk): ... ... class PartDeleteView(DeleteView): model: Part success_url = reverse_lazy('listparts' company_pk worker_pk) partslist template <a href="{% url 'deletepart' part_pk %}">Delete this part</a> How do I pass company_pk and worker_pk to the DeleteView? I think the href becomes <a href="{% url 'deletepart' part_pk company_pk worker_pk %}">Delete this part</a> But I don't know how to deal with that in the DeleteView. I'm sure it has to do with dealing with kwargs but I'm still learning on how kwargs work in something like def get_success_url(self) -
Customize viewset to get an item id combine of slug and uuid Django Rest Framework
I want to get each single item from my database by a id combine of slug and uuid. In my model I have: class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(max_length=250, unique_for_date='published') name = models.CharField(max_length=250) def get_absolute_url(self): return reverse('name-of-the-view', kwargs={'uuid': self.id, 'slug': self.slug}) In my view I am using ModelViewSet: class ProductList(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer def get_object(self, queryset=None, **kwargs): item = self.kwargs.get('pk') return generics.get_object_or_404(Product, id=item) def get_queryset(self): return Product.objects.all() In my urls I am using router: from rest_framework.routers import DefaultRouter from .views import ProductList app_name = 'products' router = DefaultRouter() router.register('', ProductList, basename='product') urlpatterns = router.urls How can I customize it so I can get not just the self.kwargs.get('pk') but also the slug from the link. I mean that I want to have links to each iteam like this: "item-name-25b6e133" and "item-name-11ac4431", where the first part is the slug and the second is the uuid. The slug should be automatically created of name field by the POST request. Using path it would look like this: urlpatterns = [ path('<slug:slug>-<uuid:uuid>/', some_view, name='name-of-the-view'), ] -
upload 10000's of images to github?
I have created a server using the Django framework in python and it has more than 1000 photos, should I upload all of them to the git hub, as I want to upload the server and its data. -
Redis Server inside Docker Container with nginx + redis_pass
I'm developing a simple Chat application (based on django-private-chat2 ) with django & django-channels. I want the application to be fully Containerized and use nginx for routing inside the container. So I'm trying to connect through a web-socket to a redis-server running inside a docker container. I've tried many things (see below) but still can't get it to work. It is not unlikely that my general approach is wrong. Here is what I've got so far. Redis-Server and websocket connection works outside Docker container. Inside the docker container I compile and run nginx with the 'HTTP Redis' here this module is loaded via 'load_module *.so' inside nginx.conf, I've verified that the module is loaded. I've configured the redis-server inside the Docker-container to use 'bind 0.0.0.0 and protected-mode no' Inside nginx then I route all the '/' traffic to a django application running on port 8000. I route all traffic to 'chat_ws/' ( from the web socket ) to 127.0.0.1:6379 the redis-server ( with nginx reverse_proxy ). I've verified that routing works properly ( return 404 with nginx on chat_ws addresses works ) I can connect to the redis-server through redis-cli on my machine, when I use 'redis-cli -h DOCKER_CONTAINER_IP' so … -
Django and MongoDB - how to debug database error for password reset email?
I've connected my Django app with MongoDB, register/login/logout are all working fine. But when I use the Django default password reset email it throws a database error. url.py path('pw_reset/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('pw_done/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('pw_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('pw_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), I was able to land on the Django password reset page, but when I hit confirm it return the error DatabaseError at /pw_reset/ No exception message supplied -
Access to XMLHttpRequest response to preflight request doesn't pass access control check
I am trying to upload file using FilePond (with Svelte) to Google Storage signed URL. When Chrome is making preflight it gets 200, but than it seams not to get Access-Control-Allow-Origin header on this response. There is an error in JS console: Access to XMLHttpRequest at 'https://storage.googleapis.com/...' from origin 'https://***.appspot.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I generate signed URL in Python: bucket = storage_client.bucket(settings.PRIVATE_GCP_BUCKET) blob = bucket.blob(f'upload/video_{obj.id}.mp4') # Get the time in UTC ini_time_for_now = datetime.now(timezone.utc) # Set the expiration time expiration_time = ini_time_for_now + timedelta(minutes=15) signed_url = blob.generate_signed_url(expiration=expiration_time, method='POST', version='v4') this works and URL is returned to JS client, properly set on FilePond configuration. My CORS config is: [ { "origin": [ "https://***.appspot.com" ], "method": [ "GET", "PUT", "POST" ], "responseHeader": [ "Content-Type", "Content-Length", "Access-Control-Allow-Origin", "x-goog-resumable" ], "maxAgeSeconds": 604800 } ] I tried multiple variations of headers etc. How to properly setup my bucket to allow to upload file? Is this GCP bucket configuration mistake or something else is wrong? I tried passing as well content_type='application/octet-stream', to generate_signed_url. -
Django app using Graphql and Channels package throws Exception inside application: 'NoneType' object has no attribute 'replace'
I've got a Django app that uses graphene to implement GraphQL and I've got everything setup and working but I now have an error in the console which has popped up suddenly and although it doesn't break anything, at least from as far as what I can tell, it does keep showing up in the console and I'd like to fix it. I'm quite new to Django so I'm not able to figure out where this is coming from. It looks like it's coming from the channels package. This is the error in its entirety that happens immediately after the server runs and then again after every request is made. Django version 3.2.3, using settings 'shuddhi.settings' Starting ASGI/Channels version 3.0.3 development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. WebSocket HANDSHAKING /graphql/ [172.28.0.1:60078] Exception inside application: 'NoneType' object has no attribute 'replace' Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/channels/security/websocket.py", line 35, in __call__ if self.valid_origin(parsed_origin): File "/usr/local/lib/python3.8/site-packages/channels/security/websocket.py", line 54, in valid_origin return self.validate_origin(parsed_origin) File "/usr/local/lib/python3.8/site-packages/channels/security/websocket.py", line 73, in validate_origin return any( File "/usr/local/lib/python3.8/site-packages/channels/security/websocket.py", line 74, in <genexpr> pattern … -
Why is Entry.objects.filter returning an empty query
I am reading an article on django about making queries over here. I have the following snippets. >>> Entry.objects.first().pub_date datetime.date(2021, 8, 18) >>> Entry.objects.first().mod_date datetime.date(2021, 8, 18) But if I try the following I get an empty queryset. Entry.objects.filter(pub_date__year=F('mod_date__year')) Why is it not working. Is this a bug? -
How to move files into another directory django-storage s3
I'm working on a news blog where you can add as many files to news as you want. For files storing properties, I'm using amazon s3 and django-strorage. But after I've added news-update view, I got some problems with files management. As you can see, here my files model class FileStorage(models.Model): file = models.FileField(upload_to=uploadFile) upload_path = models.TextField(blank=True, default='files/') def __str__(self): return f'Файл: {self.file.name.split("/")[-1]}' The main problem is how to update FileField after moving the file into another directory? Here is my files moving script. bucket = S3Boto3Storage() from_path = bucket._normalize_name(bucket._clean_name(self.instance.file.name)) to_path = bucket._normalize_name(bucket._clean_name(self.cleaned_data['upload_path'])) result = bucket.connection.meta.client.copy_object( Bucket=bucket.bucket_name, CopySource=bucket.bucket_name + "/" + from_path, Key=to_path) bucket.delete(from_path) All works good, but only with path. File in FileField store old path. How can I update it to? Screen with problem -
Unable to add/identify select_related with in django codebase
This is my views.py apparently named here as admin.py class BaseMembershipInline(ReadOnlyMixin, admin.TabularInline): class MembershipInlineFormSet(BaseInlineFormSet): def get_queryset(self): print("(((((((((((GET Q SET)))))))))))))))") # Orders by property field super().get_queryset() self._queryset = sorted( super().get_queryset(), key=lambda membership: membership.order ) return self._queryset model = Membership formset = MembershipInlineFormSet print("FORMSET ", formset) extra = 0 @classmethod def get_current_membership_ids(cls): # TODO Does this SELECT all accounts? print("))))))))GET OWNER((((((((((((") return Account.objects.all().values_list("current_membership_id") def change(self, obj): print("_____CHANGE ____________") # add custom redirect url to redirect admin to membership tab of account # detail page change_membership_url = reverse( "admin:accounts_membership_change", args=[obj.id] ) redirect_url = ( reverse("admin:accounts_account_change", args=[obj.account_id]) + "#tabs-2" ) link_url = change_membership_url + f"?{REDIRECT_FIELD_NAME}={redirect_url}" return format_html('<a href="{}">{}</a>', link_url, "Change") This is my models.py class Membership(AbstractBaseModel): # Billing frequency choices BILLING_FREQUENCY_MONTHLY = "monthly" BILLING_FREQUENCY_YEARLY = "yearly" BILLING_FREQUENCY_ONCE = "once" BILLING_FREQUENCY_NEVER = "never" BILLING_FREQUENCY_CHOICES = [ (BILLING_FREQUENCY_MONTHLY, "Monthly"), (BILLING_FREQUENCY_ONCE, "Once"), (BILLING_FREQUENCY_NEVER, "Never"), (BILLING_FREQUENCY_YEARLY, "Yearly"), ] # All database fields account = models.ForeignKey( "Account", related_name="memberships", on_delete=models.CASCADE ) plan = models.ForeignKey( "MembershipPlan", related_name="memberships", on_delete=models.PROTECT ) next_membership = models.OneToOneField( "self", related_name="previous_membership", null=True, blank=True, on_delete=models.DO_NOTHING, ) This is the inherited class for every model in my models.py class AbstractBaseModel(LogEntryMixin, models.Model): id = models.BigIntegerField( primary_key=True, default=generate_unique_id, editable=False ) creation_datetime = models.DateTimeField(auto_now_add=True, editable=False) update_datetime = models.DateTimeField(auto_now=True) objects = BaseModelManager() class Meta: … -
Blog Comments System with Class Based View in Django
Here is the function-based view that I have and it works fine: def PostDetailView(request, slug): post = Post.objects.get(slug = slug) comments = post.comment_set.all() new_comment = None if request.method == 'POST': form = CommentCreateForm(request.POST) if form.is_valid(): new_comment = form.save(commit = False) new_comment.post = post new_comment.save() else: form = CommentCreateForm() context = {'post': post, 'comments': comments, 'form': form, 'new_comment': new_comment} return render(request, 'blog/post-detail.html', context) I am trying to convert this to a class-based view as per: class PostDetailView(FormMixin, DetailView): model = Post template_name = 'blog/post-detail.html' form_class = CommentCreateForm new_comment = None def get_success_url(self): return reverse('post_detail', kwargs={'slug': self.object.slug}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = self.object.comment_set.all() context['form'] = self.get_form() context['new_comment'] = self.new_comment return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.post = self.object form.save() self.new_comment = True return redirect(self.object.get_absolute_url()) The template looks like this: <h1>{{post.title}}</h1> {{post.body|linebreaks}} {% with comments.count as total_comments %} <h2>{{ total_comments}} comment{{total_comments|pluralize}}</h2> {% endwith %} {% for comment in comments %} <div class="comment"> <p class="info"> Comment {{forloop.counter}} by {{comment.name}} {{comment.created}} </p> {{comment.body|linebreaks}} </div> {% empty %} <p>There are no comments yet.</p> {% endfor %} {% if new_comment %} <h2>Your comment has been added.</h2> {% …