Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Markdown is not showing up on my Django/HTML web page
I already converted the Markdown page, but it is not showing. Here is how my page looks like when I try to enter to any markdown content: VIEWS: from django.shortcuts import render from markdown2 import Markdown from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, entry): markdowner = Markdown() entrypage = util.get_entry(entry) if entrypage is None: return render(request, "encyclopedia/NonExisting.html", { "entrytitle": entry }) else: return render(request, "encyclopedia/entry.html", { "entry": markdowner.convert(entrypage), "entrytitle": entry } ) URLS: from xml.etree.ElementInclude import include from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>/", views.entry, name="entry") ] and that Edit button in the image does not work either. -
TypeError: __init__() takes 1 positional argument but 2 were given new one
I am develop a simple authentication application in django but I get this error: TypeError: init() takes 1 positional argument but 2 were given my view from .forms import RegisterForm, LoginForm from django.contrib.auth.views import LoginView from django.shortcuts import render, redirect from django.contrib import messages from django.views import View from .forms import RegisterForm def home(request): return render(request, 'users/home.html') class RegisterView(View): form_class = RegisterForm initial = {'key': 'value'} template_name = 'users/register.html' def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect(to='/') return super(RegisterView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect(to='/') return render(request, self.template_name, {'form': form}) class CustomLoginView(LoginView): form_class = LoginForm def form_valid(self, form): remember_me = form.cleaned_data.get('remember_me') if not remember_me: self.request.session.set_expiry(0) self.request.session.modified = True return super(CustomLoginView, self).form_valid(form) application urls urlpatterns = [ path('', home, name='users-home'), path('register/', RegisterView.as_view(), name='users-register'), # This is what we added path('login/', CustomLoginView.as_view(redirect_authenticated_user=True, template_name='users/login.html', authentication_form=LoginForm), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] my form from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'class': 'form-control', })) last_name = forms.CharField(max_length=100, required=True, … -
Suitescript that attempts to set an amount for sales order items causes "unexpected error"
I have this code that, in theory, changes the amount on the sublist of a sales order in Netsuite, but for one reason or another it tells me that an unexpected error happened. Nothing I've looked at has been particularly helpful Edit: To be clear, the error happens when I go to saved mass updates and execute it, not when saving it /** *@NApiVersion 2.1 *@NScriptType MassUpdateScript */ define(['N/record'], (record) => { function each(params) { let rec = record.load({ type: params.type, id: params.id }); var quant = rec.getValue('custrecordeconomcap'); rec.setCurrentSublistValue({ sublistId: 'item', filedId: 'quantity', value: quant }); rec.save(); } return { each: each }; }); -
I got error while attempting to serialize product's images
AttributeError: Got AttributeError when attempting to get a value for field picture on serializer ProductSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Product instance. Original exception text was: 'Product' object has no attribute 'picture'. class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = Picture fields = ['picture'] class ProductSerializer(serializers.ModelSerializer): category = serializers.ReadOnlyField(source='category.name') discount = serializers.ReadOnlyField(source='discount.name') picture = ProductImageSerializer(many=True) class Meta: model = Product fields = ['_id', 'category', 'discount', 'name_geo', 'picture', 'brand', 'size', 'technicalRequirements', 'instructionForUse', 'safetyStandard', 'youtubeUrl', 'price', 'createdAt', 'user'] class Picture(models.Model): picture = models.ImageField(null=True, blank=True, default='/placeholder.png') product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return str(self.picture) -
Query to calculate user balances
In my project there are coins that users can buy, use to perform certain actions and convert to real money. A user can only convert coins earned (by receiving gifts for example) into real money, not those bought from the site directly. Therefore, two balances are calculated internally: coins bought and coins earned (the total balance is the sum of these two). The following model contains coin transactions (it's simplified): class CoinTransaction(models.Model): class TransactionTypes(Enum): purchase_of_coins = ('pu', 'Purchase of Coins') # Will have a positive amount conversion_into_money = ('co', 'Conversion Into Money') # Will have a negative amount earning = ('ea', 'Earning') # Will have a positive amount expense = ('ex', 'Expense') # Will have a negative amount @classmethod def get_value(cls, member): return cls[member].value[0] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='coin_transactions') amount = models.IntegerField() transaction_type = models.CharField(max_length=2, choices=[x.value for x in TransactionTypes]) The earned coin balance is increased by all income except coin purchases, while the bought coin balance is increased only by coin purchases. Coins from conversion_into_money transactions are subtracted from the earned coin balance, while all other expenses are first subtracted from the bought coin balance if greater than 0. Note that the two balances cannot go below 0. To … -
Django filters just returns all objects
So I have model like this class Research(models.Model): CATEGORIES = (...) name = models.CharField(max_length=80) date = models.DateField() category = models.CharField(max_length=10, choices=CATEGORIES) public_use = models.CharField(max_length=17, choices=PUBLIC_USE_CHOICES) This filter: class ResarchFilter(filters.FilterSet): year = filters.DateFilter(field_name='date', lookup_expr='year') category = filters.CharFilter(field_name='category', lookup_expr='iexact') class Meta: model = Research fields = ['date', 'category'] And that view: class ResarchCategoryYear(generics.ListCreateAPIView): queryset = Research.objects.all() serializer_class = ResearchSerializer filter_backends = (filters.DjangoFilterBackend,) # filterset_fields = ['date', 'category'] filter_class = ResarchFilter So when I'm uncomment filterset_fields and comment filter_class it all works well but I can't filter by the year and not by the full date. So when I'm do it like in code above and goes to http://127.0.0.1:8000/...?year=2000 It literally do nothing, just gives me all of the Research objects. So what I'm doing wrong and how to enable this filtering? -
TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght'
from django.db import models class Coustomer (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) locality = models.CharField(max_lenght=150) zipcode= models.IntegerField() state = models.CharField(choices=STATE_CHOICES,max_lenght=100) class Product(models.Model): title = models.CharField(max_lenght=100) selling_price = models.FloatField() discount_price = models.FloatField() description = models.TextField() brand = models.CharField(max_lenght = 100) category = models.CharField(choices=CATEGORY_CHOICE, max_lenght=2) prodect_image = models.ImageField(uploded_to = 'Productimg') enter code here -
Performance: Best way to send large amounts of data
On my website, users can upload posts with or without files (images, audios, videos, etc.) to the database. I have two options now: Send a very large request containing the posts data as well as maybe multiple GB of data. Then create a post object and connect the files to it. Send one very small request with only the content of the post and creating one in the backend. Then sending back the UUID to the post. Then automatically sending a large request containing the files & the UUID to the backend and connecting post & files afterwards. The pro (at least IMO) to the second solution is that users could already see their posts while the files are still being processed by the backend celery worker. Would this be considered bad or good user experience? Not sure how well both solutions might scale in the future and if it'd be a difference in traffic load when there's two requests being sent. -
How to use JavaScript client-side encryption/decryption in django forms / crispy forms? Is there any python package available which can do this
Django Form fields needs to be encrypted at server side and needs to be decrypted in client browser while rendering and vice versa for form submission One approach is using JS cryptographic libraries or to use custom encryption code. But, Is there any python package available which implements this where we use this as django form widget along with js library at client side. An example will be a package like the django-autocomplete-light package which provides a widget for autocompletion for the particular field. How to implement this or Is there any package available which can be used. -
Django: in views how can a redirect if the paramater(linked to a url pattern) does not match a model result?
I apologize am still learning django and am just hitting my head on a wall with some of it. The current issue is that I have a view linked through a URL parameter the issue and it works for showing my model info but if you hard type the url to a different parameter it shows the page. I have tried to redirect it but that is not working I feel like it might because of how and where I return my render. Any advice on how to set up url's base off model and if that model info doesn't exist either through a 404 or redirect to a different page? View: @login_required(login_url='login_register') def project_page(request, name): project = Project.objects.all() issueticket1 = Issue.objects.filter(related_project__name__exact=name) table = IssueTable(issueticket1) project_list = {} for p in project: if p.name == name: project_list = {'id': p.project_id, 'startdate': p.start_date, 'enddate': p.end_date, 'description': p.description} return render(request, 'main_projects.html', {'name': name, 'project_list': project_list, 'project': project, 'table': table}) URL CONFIG: path('projects/<str:name>/', views.project_page, name="project_page"), -
How change filter variable in view from Django template?
I have review model that has reviews made by users. In view I do pagination for it. Then I do filter the reviews by variable type = 'art' How i can change variable filter for type = 'music' from template to display selectet reviews? How then use all() to display all of them? Do I have to make separate templates for each view variable or is simpler way? My view.py: def viewrevs(request): rev = Reviews.objects.filter(type = 'art') paginator = Paginator(rev,2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) ... My template.html {% for rev in page_obj %} {{ rev.name }} {{ rev.size }} {{ rev.data }} ... {% enfor %} -
requests are working locally but not on Heroku. Getting internal server error 500 and JSON not valid
I built a web application with django and react. It is working perfectly fine locally and the heroku deployment worked fine without issues. When I am testing the heroku app some of my requests are working fine like login/register. However the request where information is being sent back from the server to be displayed or post requests sending information are giving me the following error GET [request name] 500 (Internal Server Error) and Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON Would this issue be related to my requirements.txt or Procfile? Since the issue is not happening when the project is run locally and only on heroku. Could anyone point me in the right direction? -
Django/Python Runtime Error: RecursionError at /blog/cubs/
I have created a website, and I keep getting recursion errors on my /blog/cubs page, I have 2 identical pages for Beavers and Scouts but when I view the cubs equivalent I keep getting this recursion error. Below is the tracefile: pastebin of tracefile as it's too large to post here Here is the urlpatterns variable from cubs/urls.py: urlpatterns = [ path('', PostList.as_view(), name='cubs_blog_home'), path('about/', views.AboutView.as_view(), name='cubs_blog_about'), path('search/', views.SearchView.as_view(), name='cubs_blog_search'), path('file_upload/', views.upload, name='cubs_blog_file_upload'), path('downloads/', views.DownloadView.as_view(), name='cubs_blog_downloads'), path('badge_placement', views.BadgePlacementView.as_view(), name='cubs_blog_badge_placement'), path('user/<str:username>', UserPostList.as_view(), name='cubs_blog_user_posts'), path('post/new_post/', PostCreate.as_view(), name='cubs_blog_post_create'), path('post/<slug:slug>/like/', views.PostLikeView, name='cubs_blog_post_like'), path('post/<slug:slug>/', views.PostDetail.as_view(), name='cubs_blog_post_detail'), path('post/update/<slug:slug>/', PostUpdate.as_view(), name='cubs_blog_post_update'), path('post/delete/<slug:slug>/', PostDelete.as_view(), name='cubs_blog_post_delete'), #path('posts/<int:year>/<int:month>/', main_website_views.CubsPostMonthArchiveView.as_view(month_format='%m'), name="cubs_blog_post_archive_month"), #path('post/tag/<slug:slug>/', views.tagged, name="cubs_blog_post_tags"), ] And this is my woodhall_website/urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('blog/beavers/', include('beavers.urls')), path('blog/cubs/', include('cubs.urls')), path('blog/scouts/', include('scouts.urls')), path('executive/', include('executive.urls')), path('', include('accounts.urls')), path('', include('main_website.urls')), path('summernote/', include('django_summernote.urls')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('admin/password_reset/', auth_views.PasswordResetView.as_view(), name='admin_password_reset'), path('admin/password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset.html'), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'), name='password_reset_complete'), -
How to restrict a child table from referencing a parent table based on specific property in Django
Consider the following example: class Car(models.Model): def __str__(self): return self.name name = models.CharField(max_length=255) type_choices = [ ('Sedan','Sedan'), ('SUV','SUV'), ('Truck','Truck'), ] type = models.CharField('Type', max_length=255, choices=type_choices) class Sedan(models.Model): models.ForeignKey(Car, on_delete=models.CASCADE) class SUV(models.Model): models.ForeignKey(Car, on_delete=models.CASCADE) class Truck(models.Model): models.ForeignKey(Car, on_delete=models.CASCADE) How can I prevent a Sedan model record from referencing a Car model record with the type set as a Truck in the context of the admin dashboard? is there a better way to design this relationship? -
ReferenceError: file is not defined - Suitescript
I resolved some earlier issues and got the below script to validate and deploy. However it fails and in the logs I see this error: ReferenceError: file is not defined [at Object.execute (/SuiteScripts/purchasing.js:11:9)] but my file is definitely there in that location and is defined in the script. All help greatly appreciated. /** * @NApiVersion 2.1 * @NScriptType ScheduledScript */ define(['N/task'], function (task) { function execute(scriptContext){ var scriptTask = task.create({taskType: task.TaskType.CSV_IMPORT}); scriptTask.mappingId = 212; var f = file.load('SuiteScripts/purchasing2.csv'); scriptTask.importFile = f; var csvImportTaskId = scriptTask.submit(); }; return{ execute: execute }; }); -
How to aggregate annotate fields of related models in django
My problem is a little more complicated, but I'm posting the question in the simplest possible way. Annotated total_score in Photo. I would like to annotate max_total_score in Person. I wrote get_queryset of PersonManager, but the following error occurred. Is there a new way? models.py from django.db import models class PersonManager(models.Manager): def get_queryset(self): photos_prefetch = models.Prefetch( 'photos', Photo.objects.annotate(total_score=models.Sum('features__score')) ) return super().get_queryset() \ .prefetch_related(photos_prefetch) \ .annotate(max_total_score=models.Max('photos__total_score')) class Person(models.Model): objects = PersonManager() class Photo(models.Model): person = models.ForeignKey(Person, models.CASCADE, related_name='photos') class Feature(models.Model): photo = models.ForeignKey(Photo, models.CASCADE, related_name='features') name = models.CharField(max_length=100) score = models.IntegerField() shell >> Person.objects.all() # Unsupported lookup 'total_score' for BigAutoField or join on the field not permitted -
Nginx frontend not calling Nginx in backend
So I am using Django + react with nginx both on backend and frontend, containerized in docker. The following image will clarify how I want to serve the whole application: Having been googling but couldn't make sense of the solutions. Issue is that Nginx in frontend not connecting with nginx on backend on port 8082. Following are docker, nginx and docker-compose files. Nginx configurations for frontend: upstream react { server reactapp:3000; } server { listen 80; client_max_body_size 100M; proxy_set_header X-Forwarded-Proto $scheme; location / { root /usr/share/nginx/html; } location /add-to-waiting/ { proxy_pass http://0.0.0.0:8082; } } Dockerfile for react and nginx for frontend: # build environment FROM node as build WORKDIR /app ENV PATH /app/node_modules/.bin:$PATH COPY package.json ./ COPY package-lock.json ./ RUN npm i --silent RUN npm install react-scripts@3.4.1 -g --silent COPY . ./ RUN npm run build # production environment FROM nginx:stable-alpine COPY --from=build /app/build /usr/share/nginx/html EXPOSE 80 EXPOSE 443 CMD ["nginx", "-g", "daemon off;"] docker-compose.yml for frontend: services: frontend: build: . ports: - "8090:80" container_name: irisfrontend Nginx configurations for backend upstream django { server website:8000; } server { listen 80; client_max_body_size 100M; proxy_set_header X-Forwarded-Proto $scheme; location / { proxy_pass http://django; } location /media/ { alias /app/media/; } location /static/ { … -
How to correctly type utf-8 characters?
Azerbaijan language info = "Çox da uzaq olmayan gələcəkdə, tənha yazıçı Teodor" <p class="card-text"> {{ info|slice:"0:54" }} </p> <p class="card-text"> Çox da uzaq olmayan gələcəkdə, tənha yazı&ccedi </p> ç = &ccedi How to write utf-8 characters correctly? -
Django - How to save model objects in another model?
Let's say I have these two models (in models.py file): class FullName (models.Model): firstName = models.CharField(max_length=30,null=True,blank=False,unique=True) lastName = models.CharField(max_length=30,null=True,blank=False,unique=True) class Address (models.Model): addressLine = models.CharField(max_length=30,null=True,blank=False) city = models.CharField(max_length=30,null=True,blank=False) state = models.CharField(max_length=30,null=True,blank=False) zipcode = models.CharField(max_length=30,null=True,blank=False) How can I merge these two models in a new model? So it becomes: class FullName (models.Model): firstName = models.CharField(max_length=30,null=True,blank=False,unique=True) lastName = models.CharField(max_length=30,null=True,blank=False,unique=True) class Address (models.Model): addressLine = models.CharField(max_length=30,null=True,blank=False) city = models.CharField(max_length=30,null=True,blank=False) state = models.CharField(max_length=30,null=True,blank=False) zipcode = models.CharField(max_length=30,null=True,blank=False) class AllInformation (models.Model): firstName = models.CharField(max_length=30,null=True,blank=False,unique=True) lastName = models.CharField(max_length=30,null=True,blank=False,unique=True) addressLine = models.CharField(max_length=30,null=True,blank=False) city = models.CharField(max_length=30,null=True,blank=False) state = models.CharField(max_length=30,null=True,blank=False) zipcode = models.CharField(max_length=30,null=True,blank=False) (all fields should be inherited from FullName and Address models) PS: In my views.py file I called a save method like that: fullNameData = FullName(request.POST) fullNameData.save() and AddressData = Address(request.POST) AddressData.save() Thanks in advance and I really appreciate who answers that because I see that many people having the same problem. I also took a look at the OneToOneField from django docs but I understood nothing to be honest xD -
Django Forms ErrorList custom format HTML TAGS
In Django version 3.2 you can customize the error list format. https://docs.djangoproject.com/en/3.2/ref/forms/api/#customizing-the-error-list-format However in version 4.1 it has changed? https://docs.djangoproject.com/en/4.1/ref/forms/api/#customizing-the-error-list-format This section is very vague for me: forms.py from django import forms from captcha.fields import CaptchaField, CaptchaTextInput class ContactForm(forms.Form): first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "first name"}), required=True) last_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "last name"}), required=False) from_email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control', "placeholder": "email"}), required=True) subject = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', "placeholder": "subject"}), required=False) message = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', "placeholder": "message"}), required=True) captcha = CaptchaField(widget=CaptchaTextInput(attrs={'class': 'form-control', "placeholder": "prove u r not a bot 😎"}), required=True) In my template, I need {{ form.captcha.errors }} to be displayed with another HTML tag and not the default <ul class="errorlist"> -
How to call a function from a button in Django admin
I have manipulated the List view in my Django Admin and set a button for each entry. Now, when I click on the button, I want a URL to be called from the server. In this URL, headers and parameters are to be transferred. One parameter is the field pn of the entry. How can I do that? So far I have only the buttons without function. def button(self, obj): return format_html("<button> Action </buttton>") -
django/react app on heroku coming up blank
I built a web application with django and react and deployed it on heroku. A few days ago it was working fine, but now it is coming up as blank. When i run heroku logs --a --tail everything seems perfectly fine. When i redeploy it on heroku deployment is working completely fine and when i run the application locally it is also working perfectly. I have no idea how to begin debugging the problem since I have not been able to identify it and the same code was deployed on heroku and running fine a few days ago. Can anyone help point me in the right direction to how to start debugging such an issue? Thanks -
How can I get the object id inside a prefetch queryset?
I have struggled to get the object id inside a Prefetch queryset. models.py class ProductBatch(models.Model): name = models.CharField(max_length=100) product = models.ForeignKey( MstProduct, on_delete=models.CASCADE, related_name="product_batch" ) tutors = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name="handling_product_batches" ) class TrnEvent(models.Model): event_teacher = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, blank=False, related_name="trnevent", ) # -------> field for mapping the tutors from ProductBatch model title = models.TextField(null=True, blank=True) description = models.TextField(null=True, blank=True) start_time = models.DateTimeField() end_time = models.DateTimeField() product = models.ForeignKey( MstProduct, on_delete=models.CASCADE, related_name="product_batch" ) product_batch = models.ForeignKey( "MstProductBatch", on_delete=models.CASCADE, null=True, blank=True, related_name="product_batch_events", ) class Meta: app_label = "api" db_table = "trn_event" verbose_name = "trn_event" verbose_name_plural = "trn_events" views.py class ProductBatchesView(generics.ListCreateAPIView): def get_queryset(self): batches = ( MstProductBatch.objects.filter( product_id=self.kwargs["product_id"], ) .annotate(batch_id=F("id")) .prefetch_related( Prefetch( "tutors", MstUser.objects.filter( is_active=True, role__role_code="TCR", institute=self.request.user.institute, ).annotate( total_events_count=Count( "trnevent", filter=Q(trnevent__product_batch__id=F("batch_id")) ), ), ), ) ) return batches I wanted to annotate the total TrnEvent created for the tutors. I have tried to filter product_batch of TrnEvent model from annotate of batch_id F-Object. But, It didn't work. Unfortunately the total_events_count data includes other batch events that was mapped to the tutor. -
Django - creating a new object in the serializer but leaving some params from validated_data out
I'm using a ManyToManyField in my model: class CustomUser(AbstractUser): ... roles = models.ManyToManyField(Role, blank=True) And in the serializer I want to create a new object of the CustomUser class CustomUserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = CustomUser.objects.create_user(**validated_data) But off course Django complains about that: Direct assignment to the forward side of a many-to-many set is prohibited. Use roles.set() instead. How could I create new CustomUser object from all the params contained in validated_data, but leaving 'roles' alone? Is there an elegant way to do that? -
Getting this error when submitting a form > ValueError at /forms_testing/forms_testing/ Field 'id' expected a number but got 's'
This is new. I get this error when submitting form. I have another form with one textfield that works fine. Its this one that causes errors. What does it mean? Field 'id' expected a number but got 's'. What does "s" mean? Where is it coming from? I already tried fixing this by deleting migrations and making a new migration and tried it fresh and still not fixed. views.py def forms_testing(request): if request.method == 'POST': add_book_form = AddBookForm(request.POST) if add_book_form.is_valid(): add_book_form.save() return redirect('forms_testing:forms_testing') else: add_book_form = AddBookForm() return render(request,'forms_testing/forms_testing.html', { 'add_book_form':add_book_form }) urls.py path('book/<slug:book>/', views.book, name='book'), models.py class Book(models.Model): title = models.CharField(max_length=300,blank=True) slug = models.SlugField(max_length=300,blank=True) author = models.ManyToManyField(User, null=True,blank=True) featured_image = models.ImageField(upload_to='media/FEATURED_IMAGES/',blank=True) genre = models.ManyToManyField(Genres, null=True, blank=True) def get_absolute_url(self): return reverse('forms_testing:book', args=[self.slug]) def __str__(self): return self.title is there anything out of place? please help.