Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filer - PolymorphicTypeInvalid ContentType 37 does not point to a subclass
I am using django-filer to handle uploading images in my Django app. I am currently trying to load data from MySQL to PostgreSQL database. I have used the following commands to get data from MySQL and move it t PostgreSQL: python manage.py dumpdata myapp> myapp.json set DJANGO_SETTINGS_MODULE=myproject.settings.production python manage.py loaddata "myapp.json" All content works fine and I can see in pgAdmin4 that it's been successfully exported however when I am trying to open a website that contains images I get Internal Server Error like this: PolymorphicTypeInvalid at /myapp/homepage ContentType 37 for <class 'django_comments_xtd.models.BlackListedDomain'> #205 does not point to a subclass! Or error like this: PolymorphicTypeInvalid at /admin/myapp/articles/30/change/ ContentType 37 for <class 'django_comments_xtd.models.BlackListedDomain'> #232 does not point to a subclass! How can I get rid of this error and how can I move all image paths from MySQL to PostgreSQL? -
Creating a model instance
I have two Models, (Doctor & Patient), the Doctor Model is the parent Model, How can I make (Service_doctor) field be an instance of the Doctor's Model so that I can get the Doctor's name into the Patient's Model using for loop in the HTML Template. This is what am trying to mean; Models.py class Doctor(models.Model): Doctor_Name = models.CharField(max_length=200) def __str__(self): return self.Doctor_Name class Patient(models.Model): Name = models.CharField(max_length=200) Telephone = models.CharField(max_length=100, unique=True) Service_doctor = models.ForeignKey(Doctor, on_delete=CASCADE) def __str__(self): return self.Doctor_Name Views.py def Newpatient(request): if request.method == 'POST': Name = request.POST.get('Name') Telephone = request.POST.get('Telephone') Service_doctor = request.POST.get('Service_doctor') formdata = Patient(Name=Name, Telephone=Telephone, Service_doctor=Service_doctor) formdata.save() return render(request, 'Adm.html') ``` Any help please? -
Django signal user_login_failed not working for Custom User model , Custom Backend
I am a beginner in Django and due to my project requirements, I came to conclusion that I have to implement Custom User model, and also due to this I also implemented Custom Backend. But, now I am unable to use user_login_failed Django Signal, as I am thinking to use it for restrict the user login attempt to 3. and also, I have both encrypted and non-encrypted password and I want to authenticate both for now, but in future only encrypted password will remain in my DB ex: - "pbkdf2_sha256$390----------------------------" Any help will be a great deal to me Thanks settings.py AUTH_USER_MODEL = 'accounts.Usermanagement' AUTHENTICATION_BACKENDS = [ 'accounts.backends.EmailAuthBackend', 'django.contrib.auth.backends.ModelBackend', ] modely.py class Usermanagement(AbstractBaseUser): emailid = models.CharField(db_column='EmailID', unique=True, max_length=45,default=1) ------------ --------- ----------- objects = UsermanagementCustomUserManager() USERNAME_FIELD = "emailid" EMAIL_FIELD = "emailid" managers.py class UsermanagementCustomUserManager(BaseUserManager): def create_user(self,emailid,firstname, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not emailid: raise ValueError('Users must have an email address') user = self.model( emailid=self.normalize_email(emailid), password=password, ) user.set_password(password) user.save(using=self._db) return user backends.py from django.contrib.auth.backends import BaseBackend from django.contrib.auth.hashers import make_password,check_password from django.contrib.auth import get_user_model Usermanagement = get_user_model() class EmailAuthBackend(BaseBackend): def authenticate(self,request,username=None,password=None): # print("Custom authenticate rqst: ",request) try: print("Trying the … -
Image upload leads to Server Error (500) Django app deployed on railway.app
I have deployed a django app on railway.app. In development I can upload images but when I go to deployed app and click on upload it leads me to Server Error (500). following is my settings.py code STATIC_URL = 'static/' # STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if 'XXX' in os.environ: # Bucket config AWS_STORAGE_BUCKET_NAME = 'xxx' AWS_S3_REGION_NAME = 'xxx' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' # Static and media files STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATICFILES_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' MEDIAFILES_LOCATION = 'media' # Override static and media URLs in production STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATICFILES_LOCATION}/' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}/' html code <div> <img src="{{user_profile.profile_img.url}}" alt="Profile Image"> </div> <a href="{% url 'profile-image' user_profile.user user_profile.profile_uuid %}"</a> -
TypeError: the 'package' argument is required to perform a relative import for './myapp/manage.py.test_settings'
Trying to run script inside AWS Linux: ./runtests.sh ./myapp/manage.py and get the below error. Does anyone know what this means and what I should do? manage.py and test_settings.py are both in the main directory ./deploy-scripts/runtests.sh ./myapp/manage.py Traceback (most recent call last): File "manage.py", line 18, in <module> execute_from_command_line(sys.argv) File "/usr/local/python37/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/python37/lib/python3.7/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/usr/local/python37/lib/python3.7/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/python37/lib/python3.7/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/local/python37/lib/python3.7/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/python37/lib/python3.7/importlib/__init__.py", line 122, in import_module raise TypeError(msg.format(name)) TypeError: the 'package' argument is required to perform a relative import for './myapp/manage.py.test_settings' ./deploy-scripts/runtests.sh: line 57: flake8: command not found ------------------------ There were failed tests! Scroll up for details -
Transform python requests's exceptions to django-rest-framework's API exceptions
I'm developing a REST API using django-rest-framework that needs to interact with a 3rd party API. I use requests for comunication with this 3rd party API. Some recurrent pattern I get in my code is making a request from an APIView handler def calculate_order(order): url = f"https://api.anotherservice.com/orders/calculate/" try: response = requests.post(url, json=order.data) response.raise_for_status() # TODO: handle errors, just printing and re-raising for now except requests.exceptions.HTTPError as errh: raise errh except requests.exceptions.ConnectionError as errc: print(errc) raise errc except requests.exceptions.Timeout as errt: print(errt) raise errt except requests.exceptions.RequestException as err: print(err) raise err return response.json() # ... In my view def post(self, request, *args, **kwargs): # ... Some preprocessing code here order_calculated = calculate_order(order) return Response(order_calculated, status=HTTP_200_OK) DRF implements a mechanism that hanldes Subclasses of APIException raised inside REST framework. Django's Http404 exception. Django's PermissionDenied exception. I was wondering if there's a package for transforming requests's exceptions to exceptions objects that DRF can handle. Also I'll be glad to know any recomendation on how this should be implemented (best practices). I was googling it but terms with "Django" and "requests" drop results mostly of Django itself. -
Using an API to generate virtual numbers
I will build a website of virtual numbers, where the user can buy a number for a certain period of time and, after registering on a platform that requires a number to send a code, my website will receive the code through a webhook and return to the user. The central question is: which service fits my need? I thank. -
How to refresh token after expiry in django knox authentication?
I am running django application with django knox token authentication. I was able to do login with the package. But after the token expired, url response are throwing " Invalid Token". I don't understand how to refresh the token after expiry? whether i need to login again? if it is, the user will get irritated. How to do it in proper way? Which is the best token authentication for django rest framework? -
Django: Match two models by same field they have
I have 2 models. User model class User(TimeStampedModel): phone_number = models.CharField( _('Phone number'), null=True, blank=True, max_length=30, ) reservations = models.ManyToManyField( 'Reservation', related_name='Users', verbose_name=_('Reservations'), ) and Reservation model: class Reservation(TimeStampedModel): phone_number = models.CharField( _('Phone number'), null=True, blank=True, max_length=30, ) As you see there is ManyToManyField relationship between them. Here I need to get one user that phone_number is same with Reservation model's phone_number How can I get that one user -
Network: My web app goes down and I get "Connection Refused"
I have a serious network problem that is making me go crazy. My web application uses a Nginx web server, all deployed with Docker. We have two network cards with two different IP addresses. because 1 is for 100% uptime and providing external services like a static public IP address. And the other is for internal uses, like an SSH connection. And, therefore, I have a DNS service with two public IPs of type A to serve the website if one is unavailable. I have my nginx webserver configured to serve the two adresses, maybe I should change that. ` upstream app { server 192.168.1.84:5001; server 172.16.31.10:5001; } server { listen 443 ssl; ssl_certificate /etc/ssl/ssl.pem; ssl_certificate_key /etc/ssl/ssl-key.key; server_name example.com; root /var/www/example.com; resolver 127.0.0.11 ipv6=off; index index.html index.htm index.nginx-debian.html; charset utf-8; #max upload size client_max_body_size 75M; location /media { alias /app/media; } location /staticfiles { alias /app/assets; } location / { proxy_set_header Host $host; proxy_redirect off; proxy_pass http://app; # Add your own server port here instead of 5000. proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; include /etc/nginx/uwsgi_params; } } ` It worked at 100% uptime before; maybe this is related to having two networks now. I have a monitoring service that pings … -
Django testing UpdateView - object has no attribute 'object'
I am trying to write a test for an UpdateView I created. My view looks like this: class MutantUpdateView(UpdateView): context_object_name = "mutant" fields = ["mutation_level"] model = Mutant pk_url_kwarg = "mutant_id" template_name_suffix = "_update_form" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["admin"] = get_object_or_404( Person, id=self.kwargs["admin_id"] ) context["backstory"] = get_object_or_404( Backstory, id=self.kwargs["backstory_id"] ) context["evidences"] = self.object.evidences.all() return context def get_form(self, form_class=None): form = super().get_form(form_class) mutant = self.object mutation_levels = ( mutant.expectation.mutation_levels.all() ) form.fields["mutation_level"].queryset = mutation_levels return form def form_valid(self, form): form.instance.updated_by = = get_object_or_404( Person, id=self.request.user.person_id ) return super().form_valid(form) def get_success_url(self, **kwargs): return reverse_lazy( "mutants:mutant-update", kwargs={ "admin_id": self.kwargs["admin_id"], "backstory_id": self.kwargs["backstory_id"], "mutant_id": self.kwargs["mutant_id"], }, ) My test looks like this (per the documentation) def test_form_valid_posts_appropriately(self): new_level = MutantLevelFactory(short_description="Next Mutant Level") self.mutant.expectation.mutation_levels.add(new_level) data = { "created_by": self.admin_person.id, "updated_by": self.admin_person.id, "backstory": self.mutant.backstory.id, "expectation_level": new_level, "expectation": self.mutant.expectation.id, } kwargs = { "admin_id": self.admin_person.id, "backstory_id": self.mutant.backstory.id, "mutant_id": self.mutant.id, } request = self.factory.get( reverse("mutants:mutant-update", kwargs=kwargs) ) request.user = self.admin_user # simulate admin user logged in self.view.setup(request) context = self.view.get_context_data() self.assertIn('backstory', context) self.assertFalse(context["form"].errors) self.assertEqual(response.status_code, 302) It's giving me this error: def get_form(self, form_class=None): form = super().get_form(form_class) > mutant = self.object E AttributeError: 'MutantUpdateView' object has no attribute 'object' The model looks like this: class Mutant(models.Model): id = models.BigAutoField(primary_key=True) … -
Pass HTML as agrumnet within inclusion tag
I have created an inclusion tag for creating a certain number of columns within a row: <tr> {% for col in cols %}<td>{{ col }}</td>{% endfor %} </tr> My inclusion_tag function is: @register.inclusion_tag("row_with_cols.html") def row_with_cols(*cols): return {"cols": cols} So I can now pass as many values I want to my rows as I want with something like: {% row_with_cols "Full name" session.userinfo.name %} This is all well and good however to take this to the next level I would like to pass in arguments that are HTML arguments. For example, I want to turn something like this: <tr> <td>Image</td> <td> <img src="{{ session.userinfo.picture }}"> </td> </tr> into {% row_with_cols "Image" <img src="{{ session.userinfo.picture }}"> %} However, this gives me Could not parse the remainder: '<img' from '<img' I know I could modify the inclusion_tag function with some additional arguments that could provide the info but was hoping to keep that nice and generic. It would be helpful if someone can either tell me whether what I'm doing is not possible or if there is a clean/non-hacky way to do it. Thanks -
Display inline values in other app's admin model
I have been trying to figure it out but since I am not much experienced in this, I wanted to ask if there is a way to display the values from an inline at an other app's model.admin; In my case: accounts\admin.py: @admin.register(models.Customer) class CustomerAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ('first_name', 'last_name', 'customer_subscription', 'company') This is where I want to show inline values. core\admin.py: class ManageAddressInline(GenericStackedInline): model = AssignAddress class CustomCustomerAdmin(CustomerAdmin): inlines = [ManageAddressInline] admin.site.unregister(Customer) admin.site.register(Customer, CustomCustomerAdmin) address_reports\model.py: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django_countries.fields import Country, CountryField from accounts.models import Customer class AssignAddressManager(models.Manager): def get_tags_for(self, obj_type, obj_id): content_type = ContentType.objects.get_for_model(obj_type) return AssignAddress.objects \ .select_related('manage-address') \ .filter( content_type=content_type, object_id=obj_id ) class ManageAddress(models.Model): defined = models.ForeignKey(Customer, on_delete=models.CASCADE) apartment_or_suite = models.CharField(max_length=255) street = models.CharField(max_length=255) city = models.CharField(max_length=255, null=True) postal_code = models.CharField(max_length=20, blank=True) country = CountryField() class AssignAddress(models.Model): objects = AssignAddressManager() apartment_or_suite = models.CharField(max_length=255, null=True) street = models.CharField(max_length=255, null=True) city = models.CharField(max_length=255, null=True) postal_code = models.CharField(max_length=255, null=True) country = CountryField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() address_reports\admin.py: from django.contrib import admin from address_reports.models import ManageAddress @admin.register(ManageAddress) class ManageAddressAdmin(admin.ModelAdmin): search_fields = ['defined', 'apartment_or_suite', 'street', 'city', 'postal_code', 'country'] list_display = ['defined', 'apartment_or_suite', 'street', 'city', 'postal_code', 'country'] … -
Django, spawn worker process on start generates django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
Background: I have an app that scrapes through our IT infrastructure resources (vCenter, storage, and backup entities) to pull things into a central inventory for quick reference. Each collection spins up in its own thread, and I've taken measures to implement a producer/consumer setup to better scale for our resources. What I've noticed is that when I have collections running from multiple types (Ex: vCenter and storage), the web interface chugs. My thought is because I've got a ton of threads running from multiple sources and the GIL is causing everything to get queued up under one main thread. So, I thought that I could have the main producer/consumer model run as processes instead of threads since they are fairly independent of each other. What's wrong: When I made the code switch from spinning up threads to processes, the worker process tries to load up the models that it should, but it fails because the sub process is separate, and the applications aren't loaded up. It throws django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. What I have found is since this spawned process doesn't inherit anything from the Django main process, it's trying to access the models without having anything started. What … -
How to fetch the Finance Charge Preferences values using SuiteScript in NetSuite?
We need to perform calculations in SuiteScript using the values in Setup/Accounting/Finance Charge Preferences. Which record is this stored on? Specifically, we're looking for these finance charge fields: Annual Rate Minimum Finance Charge Grace Period We've tried to create saved searches in all of the obvious records but have not been able to find these fields. -
I launched a django server and now I can't stop the process
Can anyone please tell me how to stop my server? I did like the first few things you need to do in order to commence a django webpage, url pattern, request, HttpResponce etc. and I ran my server but that rocket is still showing on my screen despite trying to kill, pkill, ctrl+pause, ctrl+C. I'm so done with this... I looked up on The Internet how to stop my django server. Nothing worked. On top of that when I ran it I got a "ModuleNotFoundError" but the rocket is still showing when I type in the numbers... -
Correct way to use DRF and viewsets
I have a model: class Definition(Model): definition_id = BigAutoField(primary_key=True) definition_name = CharField(max_length=50) is_active, created_by, created_datetime, last_modified_by, last_modified_datetime = default_model_attrs() class Meta: db_table = 'definitions' def __str__(self: Self) -> str: return self.definition_name With this serializer: class DefinitionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Definition fields = [ 'url', 'definition_id', 'definition_name', 'attributes', 'created_by', 'created_datetime', 'last_modified_by', 'last_modified_datetime', 'is_active', ] read_only_fields = [ 'url', 'definition_id', 'attributes', 'created_by', 'created_datetime', 'last_modified_by', 'last_modified_datetime', 'is_active', ] I tried making a view set for a couple of custom actions on create: class DefinitionViewSet(viewsets.ModelViewSet): """ API endpoint that allows definitions to be viewed or edited. """ queryset = Definition.objects.all().order_by('definition_id') serializer_class = DefinitionSerializer permission_classes = [permissions.IsAuthenticated] def create(self: Self, request: Request, **kwargs: dict[str, Any]) -> Response: if not is_valid_db_object_name(request.data['definition_name']): return Response( { 'message': f"Invalid definition name -> {request.data['definition_name']}", }, status=status.HTTP_400_BAD_REQUEST) definition = Definition( definition_name=request.data['definition_name'], created_by=request.user, last_modified_by=request.user ) serializer = self.serializer_class(definition, context={'request': request}, partial=True) definition.save() return Response( data=serializer.data, status=status.HTTP_201_CREATED ) But this seems overly complicated for validating a field (is_valid_db_object_name is basically a regex) and to add created_by and last_modified_by. Also, trying to figure out how to make definition_name the only possible field that should be passed for creating and editing. Am I on the right path? Also, how would the edit method look … -
How can i reduce the spacing between checkboxes rendering in a django template?
I have retrived some data by retreival from database and saved in into variable DATA ` def sendApproval(request): form = SendApp data = Profile.objects.filter(Admin="Lavanya") context = { "form": form,"data":data} return render(request, 'homePageHtml/SendApproval.html', context) ` And then in the html templete I used that data to represent it as checkboxes ` {%for a in data%}<br> <input type="checkbox" id="recommender" name="choosen" value="{{a.UserName}}" > <label for="recommender" style="font-size:15px"> {{a.UserName}}</label><br><br> {%endfor%} ` and after viewing it on web page it is visible like this: Any one with the solution will be appreciated! Thanks in advance I tried: ` .adjust-line-height { line-height: 1em; } ` adding this into my code, but this didn't work.... -
Can't install extension in VS Code: XHR failed
I can't install the extensions in VS Code and I'm a Mac user. When I tried to install the extension, it gave me an error and suggested me to install it manually. And I'm currently building my Django app, I wonder if there are any recommendations for the extensions that are quite useful for HTML or in general. I tried to search for the solution online but I found out I didn't have the problem with "fetching the extension", I just failed to install it. Here is the log with the errors. -
python/django create a text file and make user download it
does anyone know if there is a way to create a text file who can be downloaded by an user of my django site ? Can someone help me or send me tutorials to show me how to do it ? Thanks -
Have to save ModelChoiceField into database using Django forms and Template
Here I am using Django 3.0 and Python 3.7 I am not able to save ModelChoiceField into database Here is my models.py class ProductionProcess(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) name = models.CharField(max_length=500) order = models.IntegerField(default=None, null=True, blank=True) milestone_1 = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.name Here is my views.py class ProductionProcessAddCreateView(CreateView): template_name = 'core/production_process_form_1.django.html' form_class = ProductionProcessForm context_object_name = "production" model = ProductionProcess def form_valid(self, form): self.object = form.save(commit=False) self.object.client = self.request.user.client try: self.object.save() messages.success(self.request, 'Production Process created successfully.') except BaseException as e: logger.exception(e) messages.error(self.request, 'Failed to create a Production Process.') return HttpResponseRedirect(reverse("production_process")) Here is my forms.py class ProductionProcessForm(forms.ModelForm): milestone_1 = forms.ModelChoiceField(queryset=ProductionProcess.objects.values_list("name", flat=True).distinct(),empty_label=None) class Meta: model = ProductionProcess fields = ['name','order','milestone_1'] exclude = ['client'] Here is my production_process_form_1.django.html <form class="form-horizontal" method="post"> {% csrf_token %} <div class="row"> <div class="span10 offset1"> <div class="control-group"> <label class="control-label pull-left" for="{{ form.name.auto_id }}">{{ form.name.label }}</label> <div class="controls"> {{ form.name}} </div> </div> <div class="control-group"> <label class="control-label pull-left" for="{{ form.order.auto_id }}">{{ form.order.label }}</label> <div class="controls"> {{ form.order}} </div> </div> <div class="control-group"> <label class="control-label pull-left" for="{{ form.milestone_1.auto_id }}">{{ form.milestone_1.label }}</label> <div class="controls"> <select id="id_milestone" name="milestone_1"> <option value="" selected="selected">---------</option> {% for cat in form.milestone_1 %} <option>{{cat}}</option> {% endfor %} </select> </div> </div> </div> </div> <div id="form-buttons-container" class="form-actions"> <input type="submit" class="btn btn-inverse" … -
Django-tables2 - How do I disable pagination for a SingleTableMixin,FilterView?
How can I disable pagination in FilterView? All the commented out code is what I've already tried. None of which is working. As soon as I filter the table, the pagination appears at the bottom and part of the filtered result is not visible (unless you go to the next page) class AlpineTableView(SingleTableMixin, FilterView): table_class = AlpineTable queryset = Artikel.objects.all() filterset_class = AlpineFilter # def get_table_pagination(self, request): # return False # def get_table_pagination(self, table): # return False # table_pagination = False # pagination_class = None # paginator = None # table_pagination = { # "per_page": 100000 # } template_name = "artikelen/alpine-voorraad-filter.html" -
How to migrate to the models from a previous commit?
I have a python Django project with several applications and multiple git branches for each features. It's a true hell to do the migration by hand because there are too many apps, and have to diff showmigrations to see what have changed... Is there a way to automate this, or at least a way to generate the migration I should restore the db to ? -
Django translate salutation
Assume we have person definitions, e.g.: { "first_name": "Peter", "last_name": "Peterson", "academic_title": "Dr", "salutation": "mr" } In english, the salutation should be: def person.display_name(): prefix = person.academic_title if person.academic_title else person.salutation return _(Hello "%(prefix)s {first_name} {last_name}") % {"prefix": prefix} # Dr. Peter Peterson #if the person has a title # Mr. Peter Peterson #if the user has no title In german this definition does not work, as it is always prefix = f"{person.salutation} {person.academic_title} Is there any way to mark it for translations except for def person.display_name(lang): if lang == 'en': prefix = person.academic_title if person.academic_title else person.salutation elif lang == 'de': prefix = f"{person.salutation} {person.academic_title} return _("Hello %(prefix)s {first_name} {last_name}") % {"prefix": prefix} Which has the disadvantage of having two translation strings -
Redirecting user to another page after submitting the form using get_absolute_url() method
I'm new to django and I'm following a tutorial trying to create a blog. I'm currently working on a page to add posts to the blog and I want the user to be automatically directed to the post page after submitting the form. I tried using get_absolute_url method but got this error: NoReverseMatch at /my_blog/add_post/ Reverse for 'post-detail' not found. 'post-detail' is not a valid view function or pattern name. I checked my code to see if I have done anything wrong but I couldn't notice. I appreciate any help in advance. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): STATUS = [ (0, 'Drafted'), (1, 'Published'), ] title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) published_on = models.DateTimeField(auto_now=True) content = models.TextField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', args=(str(self.id))) urls.py from django.urls import path from .views import PostListView, PostDetailView, AddPostView, UpdatePostView app_name = 'my_blog' urlpatterns = [ path('', PostListView.as_view(), name='posts'), path('post/<int:pk>', PostDetailView.as_view(), name='post-detail'), path('add_post/', AddPostView.as_view(), name='add-post'), path('post/edit/<int:pk>', UpdatePostView.as_view(), name='update-post'), ] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView from .models import …