Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create a Django model in views.py?
In a DetailView page for object "Patient", I have a form. When the form is filled and submitted, I want to create a "Location" object. Then, I want to create a ForeignKey pointing to the "Patient" object that we are looking at in the DetailView. As you can see, if the form is valid, I call the model constructor, save the information and connect it to the patient object. However when I check Django Admin, I can't see a new object created. I totally improvised as I couldn't find examples online. Is this the way to do it? class PatientDetailView(DetailView, FormMixin): model=Patient form_class = PastLocationForm #template_name = 'patient_detail.html' def get_success_url(self): return reverse('patient_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): pastLocationDetail = Location() setattr(pastLocationDetail,'location',str(form.cleaned_data['location']).split(',')[0]) setattr(pastLocationDetail,'address',str(form.cleaned_data['location']).split(',')[1].split(', ')[0]) setattr(pastLocationDetail,'district',str(form.cleaned_data['location']).split('District: ')[1].split(',')[0]) setattr(pastLocationDetail,'grid_x',str(form.cleaned_data['location']).split('Coordinates: (')[1].split(', ')[0]) setattr(pastLocationDetail,'grid_y',str(form.cleaned_data['location']).split('Coordinates: (')[1].split(', ')[1][:-1]) setattr(pastLocationDetail,'date_from',form.cleaned_data['date_from']) setattr(pastLocationDetail,'date_to',form.cleaned_data['date_to']) setattr(pastLocationDetail,'details',form.cleaned_data['details']) setattr(pastLocationDetail,'patient', self.object) return self.form_valid(form) else: return self.form_invalid(form) Location model class Location(models.Model): patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True) . . Note: I printed out both the objects print(type(self.object)) print(pastLocationDetail) And everything seems fine. I really don't understand why it is not written to the database -
ajax response return with function for
Can you tell me how can I replace code html with function 'for from django'? $.ajax({ url: url, data: $('#FormSite').serialize(), type: "POST", async:false, success: function(response) { $($("#Pic").first()).replaceWith($(response['Pic'])); $("#HeaderWpis").text(response['h1']); $("#WpisChild").html("<div id='WpisChild'> {% for News in Messags %} <p>{{ News.title }}</p> </div>"); }, error: function(data) { alert('Bad connection'); console.log(data); } }); When I do this I got {%for%} from third div 'WpisChild' as text. The function does not perform on the page. Could you tell me why? -
no redirect from auth_view.LoginView.as_view(authentication_form=LoginForm)
i am using auth_view.LoginView.as_view() urls.py as default login in django. To add more fields i used custom form with AuthenticationForm in form.py, but after using custom form i cannot redirect from login page as i click submit button here is my form.py ''' from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): user_type_choice = (('visitor', 'Visitor'),('guest', 'Guest'),('contractor', 'Contractor')) username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) user_type = forms.MultipleChoiceField(choices=user_type_choice, widget=forms.NullBooleanSelect, required=True) here is my urls.py from django.urls import path from django.contrib.auth import views as auth_view from account.form import LoginForm from . import views urlpatterns =[ path('login/', auth_view.LoginView.as_view(authentication_form=LoginForm), name='login'), path('logout/', auth_view.LogoutView.as_view(), name='logout'), path('', views.dashboard, name='dashboard') ] here is my views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required # Create your views here. @login_required def dashboard(request): render(request, 'account/dashboard', {'section': dashboard}) sorry for bad english. i am a newbie, please pardon me for my mistakes -
Django + Heroku + MongoDB Atlas (Djongo) = DatabaseError with No Exception
One line description of the issue Whenever my django app deployed on heroku tries to access my MongoDB Atlas cluster to submit a form or check an admin login it throws something like the attached error. Extra Details Error reproducible on heroku build here I think that this is error has to do with how heroku interacts with my MongoDB Atlas cluster, as I am able to get the app to successfully read and make modifications do different records in my database when I run the build locally. I have enabled traffic from all IP addresses to my Atlas cluster, removed the default Heroku PostrgreSQL database from my Heroku app and the config variables, and stored my own database IP as a config var. Any help would be greatly appreciated. Python script # Model Script from django.db import models class RawRequest(models.Model): content = models.CharField(max_length=130) identifier = models.CharField(max_length=30) # Views Script from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.http import HttpResponse from django.views.generic import CreateView from .models import RawRequest # Create your views here. def index(request): return HttpResponse("euler-calc terminal GUI") def potato(request): return HttpResponse("potato") class RequestView(CreateView): model = RawRequest fields = ('content', 'identifier') def get_success_url(self): … -
How to add an image to Django's Syndication RSS-feed
Having this model: class MyModel(models.Model): … image = StdImageField( upload_to="img/images", blank=True, variations={ "large": (1024, 1024), "thumbnail": (150, 150, False), "medium": (600, 600), }, delete_orphans=True, ) and this view … from django.contrib.syndication.views import Feed … class LatestItems(Feed): title = "LatestItems" description = "Latest Items" link = "/sitenews/" def items(self): return MyModel.objects.all() def item_title(self, item): return item.description_short def item_description(self, item): return item.description def item_link(self, item): return reverse('item_detail', args=[item.pk]) How to add an image to the body of an RSS-article? -
how do I convert Django queryset values data to pandas dataframe?
I have a Django Queryset which I obtain using `answers = CatResponse.objects.values('administration_id','administered_words','administered_responses').filter(administration__in=administrations)` The result looks like: <QuerySet [ { 'administration_id': 102201, 'administered_words': ['hat', 'cheese', 'milk', 'bath', 'hi', 'meow', 'moo', 'cookie', 'duck', 'apple', 'banana', 'ear', 'car', 'uh oh', 'baby', 'nose', 'no', 'book', 'bye', 'shoe', 'daddy*', 'mommy*', 'ball', 'eye', 'juice', 'bubbles', 'woof woof', 'grandma*', 'hot', 'hair', 'fish (animal)', 'please', 'cat', 'thank you', 'night night', 'yes', 'truck', 'water (beverage)', 'cup', 'diaper', 'water (not beverage)', 'quack quack', 'ouch', 'kitty', 'cracker', 'bear', 'eat', 'spoon'], 'administered_responses': [True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True] },{ 'administration_id': 102200, 'administered_words': ['bird', 'balloon', 'apple', 'banana', 'ear', 'car', 'uh oh', 'baby', 'nose', 'eye', 'no', 'book', 'bye', 'duck', 'cookie', 'moo', 'meow', 'hi', 'bath', 'milk', 'cheese', 'bubbles', 'woof woof', 'grandma*', 'hot', 'hair', 'fish (animal)', 'please', 'cat', 'thank you', 'night night', 'yes', 'truck', 'water (beverage)', 'cup', 'diaper', 'water (not beverage)', 'quack quack', 'ouch', 'kitty', 'cracker', 'bear', 'eat', 'spoon', 'door', 'baa baa', 'mouth', 'grandpa*'], 'administered_responses': [True, True, True, False, True, False, True, False, True, … -
(AttributeError: module 'PIL.Image' has no attribute '_meta') When resizing images with pillow
I was trying to change the size of an image but then when I was to run the code it showed up this error:`AttributeError: module 'PIL.Image' has no attribute '_meta' This si my models.py file: from django.db import models from PIL import Image class LmtbProject(models.Model): title = models.CharField(max_length=200) description = models.TextField() public = models.BooleanField(default=True) LmtbImage = models.ImageField(blank=True) def __str__(self): return f'{self.title}' def save(self): super().save() img = Image.open(self.LmtbImage.path) output_size = (1000, 800) img.thumbnail(output_size) img.save(self.LmtbImage.path) class SecondaryImage(models.Model): MyProject = models.ForeignKey(LmtbProject, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') def __str__(self): return f'{self.MyProject.title}' def save(self): super().save() img = Image.open(self.image.path) output_size = (1000, 800) img.thumbnail(output_size) img.save(self.image.path) `This is my view that I use with it: def project(request): projects = LmtbProject.objects.all() context = { 'projects': projects } return render(request, 'projects.html', context) def project_detail(request, id): project = get_object_or_404(LmtbProject, id=id) photos = SecondaryImage.objects.filter(MyProject=project) return render(request, 'project-detail.html', {'project': project, 'photos': photos}) -
Chrome becoming unresponsive when parsing json from ajax response (Mozilla works)
Initial page load works without any issues: json = JSON.parse('{{ json|escapejs }}'); but if I refresh my data with an ajax call to my django back-end calling the same exact function returning the same exact data chrome becomes unresponsive (mozilla has no issue parsing the json on both page load and ajax refresh): json = JSON.parse(response.json); It's a fairly large amount of data, but can someone please explain what's going on and why it's only chrome that isn't able to parse the json and only in the ajax response? -
How to pass an object from one view to another in Django?
I want to pass an object from one view to another in my Django project. But I got an error such as Object of type ModelCreate is not JSON serializable Here is my sender view: @login_required(login_url = "user:login") def modelCreate(request): customer_name = str(request.user) home_path = Methods.get_home_path(customer_name) outputs = request.user.profile.selected_outputs process = ModelCreate(str(home_path), customer_name, outputs) request.session['process'] = process return redirect("data:status") Here is my receiver view; @login_required(login_url = "user:login") def process_status_view(request): process = request.session['process'] return render(request, "pending_page.html") How can I pass this object? -
Why Am I getting "None" when using ForeignKey on integer value from another model that I know that have integer number?
I wanted to ask you for your help. I have two models. In the first one I wanted to reference foriegn key from the second one to be able to print votescore that I store there. My models.py : class Question(models.Model): question = models.CharField(max_length=300) answered = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) votesscore = models.ForeignKey('VoteQuestion', on_delete=models.CASCADE, null=True, blank=True, related_name='question_votesscore') def __str__(self): return self.question class VoteQuestion(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE, blank=False, null=True) votesubmitted = models.DateTimeField(null=True, blank=True) votesscore = models.IntegerField(default='0') amountofvotes = models.IntegerField(default='0') def __str__(self): return self.votesscore class Meta: unique_together = ['user', 'question', 'votesscore'] Next in my views.py: def home(request): allquestionswithanswers = Question.objects.filter(datecompleted__isnull=False) allquestionswithoutanswers = Question.objects.filter(datecompleted__isnull=True) return render(request, 'main/home.html', {'allquestionswithanswers': allquestionswithanswers, 'allquestionswithoutanswers': allquestionswithoutanswers}) And in my home.html I am calling it like this: {% for question in allquestionswithanswers %} <li> {{ question }} Score: {{ question.votesscore }} {{ question.user }} <br><br> <form class='my-ajax-form' method='POST' action='' data-url="{% url 'questionvoteup' question.id %}" > {% csrf_token %} <button type='submit'>UP</button> </form> {% for answer in question.answer_set.all %} {{ answer }}<br> {% endfor %} </li> {% endfor %} And when I try to print {{ question.votesscore }} I get value "None". Yet I am sure that in … -
Django - taking values from POST request, JavaScript fetch API
Sorry if this is a noob question, I am creating an Django app and for that i am trying to access data received from POST request, using JavaScript fetch API but it is showing empty I am not getting what is my mistake. I have tried to remove to all unnecessary part to debug and even on executing only this part I am getting same error. Code of my views.py def checkdb(request): if request.method == "POST": a = request.POST.get('tag', 'default') print("printing", a) print(request.POST) return HttpResponse("Hello") def check(request): return render(request, 'shop/new.html') Code of URLS.py urlpatterns = [ path('', views.index, name="shop"), path('checkdb/', views.checkdb, name="checkdb"), path('check/', views.check, name="check"), ] Code of new.html, it has only script tag to fetch request just for testing purpose. <script> data = JSON.stringify({ headline: "Testing", tag: "Testing", background_image: "Testing", content: "Testing", user: 1 }) let csrftoken = getCookie('csrftoken'); let response = fetch("/shop/checkdb/", { method: 'POST', body: data, headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, }) function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name … -
'django-admin' is not recognized as an internal or external command, operable program or batch file. Windows10
I tried starting my own project in Django but I keep getting "'django-admin' is not recognized as an internal or external command, operable program or batch file." C:\>cd C:\Users\Gamer Grill\Desktop C:\Users\Gamer Grill\Desktop>mkdir django-practise C:\Users\Gamer Grill\Desktop>cd django-practise C:\Users\Gamer Grill\Desktop\django-practise>mkdir my_first_project C:\Users\Gamer Grill\Desktop\django-practise>django-admin startproject first_project 'django-admin' is not recognized -
Syntax Error in manage.py while executing process_tasks
I'm trying to execute some background apps in Django 2.2 but every time I call python3 manage.py process_tasks it raise syntax error other commands like run server, migrate, ... works fine only for process_tasks it raises this error even when I comment on all background task codes File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax -
Display pdf file with proper indentation
I want to Display Pdf file on webpage. The Pdf File contains Python Program which has indentation. But while displaying the file i am not able to get the proper spacing as in the pdf. import PyPDF2 def read_file(request): pdfFileObj = open('media/documents/from_django.pdf', 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pageObj = pdfReader.getPage(0) text=pageObj.extractText() pdfFileObj.close() context = {'file_content': text} return render(request, "file.html", context) HTML <!DOCTYPE html> <html lang="en"> <head> <title>File</title> </head> <body> {{ file_content}} </body> </html> -
my marketing_message is displayed only in index.html and rest of the pages middleware dont display marketing messages
I think since i am adding marketing_message in templates of views.py thats why my context is displaying message only at index.py... i want to display my message in every page of my app. middleware.py--- from .models import MarketingMessage from django.utils.deprecation import MiddlewareMixin class DisplayMarketing(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def process_request(self, request): print("something") try: request.session['marketing_message'] = MarketingMessage.objects.all()[0].message except: request.session['marketing_message'] = False settings.py--- MIDDLEWARE = [ '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', 'marketing.middleware.DisplayMarketing', ] added it in views.py-- def index(request): products = Product.objects.all() marketing_message = MarketingMessage.objects.all()[0] context = {'products':products,'marketing_message':marketing_message} return render(request,'pro/index.html',context) my views.py def index(request): products = Product.objects.all() marketing_message = MarketingMessage.objects.get() context = {'products':products,'marketing_message':marketing_message} return render(request,'pro/index.html',context) base.html-- {% if marketing_message %} <div class="alert alert-success alert-dismissible alert-top-message" role="alert"> <h3> {{ marketing_message.message|safe }} </h3> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} -
How to create <img> element including a Django static src using jQuery
I would like to create an img element using jQuery. Since I work with Django I will have to reference the imagefile by the static variable. I tried different solutions to come about this but the server can't load the image since the browser gets the wrong url. What I tried: // Create Image element var arrowImage = $('<img />', { id: 'arrowImage', src: '{% static \"images/arrow.svg\" %}', }); // src: '{% static "images/arrow.svg" %}', // src: "{% static 'images/arrow.svg' %}", Error: GET http://127.0.0.1:8000/%7B%%20static%20%22images/arrow.svg%22%20%%7D 404 (Not Found) Any solution for this? -
Mapping Django urls and views
Guys i am new to Django but i am bit clued up on a few things. I need help with urls. So in my models.py i defined category, subcategory and product models and all these models fields have got a slugfield. I have also managed to define the index page url and its working but after the index page i want when the user clicks the category link he will be able to see subcategories that are under categories, and when the user click on subcategories he will able to see products in the subcategory. So for example i would love to create an url like www.127.0000/electronics , electronics is the category and under electronics the user will be able to see subcategories like TV's , Microwaves...when the user click on TV's link the url will be www.127.0000/electronics/tvs and at this page the user will see the products. This is my models.py class Category(models.Model): name= models.CharField(max_length=100) slug= models.SlugField(max_length= 100, unique= True) class Meta: ordering = ('name',) verbose_name= 'category' verbose_name_plural= 'categories' def __str__(self): return self.name class SubCategory (models.Model): name = models.CharField(max_length= 200) slug = models.SlugField (max_length= 200, unique= True) category= models.ForeignKey(Category, on_delete= models.CASCADE) class Meta: ordering = ('name',) verbose_name= "SubCategory" verbose_name_plural= … -
Zappa deployment successful without url
I am trying to deploy a django application through zappa. When I deploy the application everything works correctly and I also get the message "Your updated Zappa deployment is live". But I can't seem to find the url to access the live application. -
Django - Form not saved when submitted
I'm working on a question creation page on my website. I have two different types of questions : classical questions and MCQ. I have a dropdown list with the 2 types of questions and when I choose one and hit "confirm", the corresponding form appears. The problem is, when I submit the form, it doesn't save and a new, blank, form shows up. I created three models in models.py : from django.db import models from django.contrib.auth.models import User class Mod_Choix(models.Model): CHOIX = [ ('qcm', 'QCM'), ('question', 'Question') ] Type_de_question = models.CharField(choices=CHOIX, max_length=200, default='qcm') class Question_Num(models.Model): num_question = models.IntegerField(default=0) question = models.CharField(max_length=1000, unique=True) reponse = models.IntegerField(default=0) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' class QCM(models.Model): num_question = models.IntegerField(default=0) question = models.CharField(max_length=1000, unique=True) choix_1 = models.CharField(max_length=200, unique=True, default='') choix_2 = models.CharField(max_length=200, unique=True, default='') choix_3 = models.CharField(max_length=200, unique=True, default='') choix_4 = models.CharField(max_length=200, unique=True, default='') class Meta: verbose_name = 'QCM' verbose_name_plural = 'QCM' def __str__(self): return f'QCM n°{self.num_question}' Then I use them in forms.py : from django import forms from django.contrib.auth.models import User from .models import Question_Num, QCM, Mod_Choix class Form_Choix(forms.ModelForm): Type_de_question = forms.Select() class Meta: model = Mod_Choix fields = ['Type_de_question'] class Form_Creation_Question(forms.ModelForm): num_question = forms.IntegerField(label='Numéro de … -
How to create search in product listing page Django
I am doing an eCommerce site in django. And in dashboard there is a product listing page so i need to create search with in the same page so that admin can easily access particular product by searching it. I haven't created search within the listing page rather I have created search page with search result separately.So if anybody could help me. -
Django Crispy Forms with MaterializeCSS
I am trying to write a helper to render MaterializeCSS forms with Django-crispy-forms. So far I couldn't find how to implement the tags properly or the form in general, to make them slide up in animation when active (A material thing, can be observed here: MaterializeCSS FormFields). My code looks like this: class SignUpForm(CustomUserCreationForm): class Meta: model = CustomUser fields = ('email', 'password1', 'password2',) def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Div( Div( Field('email', css_class='validate'), css_class='input-field col s12' ), css_class='row' ), Div( Div( Field('password1', css_class='validate'), css_class='input-field col s12' ), css_class='row' ), Div( Div( Field('password2', css_class='validate'), css_class='input-field col s12' ), css_class='row' ), ) I am afraid I am making this overly complicated. Is there any better way to accomplish such html structure for my form with django-crispy-forms? Or would you suggest a different approach all-together, like not using crispy forms? Here is the HTML I am trying to replicate form my form: <div class="row"> <div class="input-field col s12"> <input id="password" type="password" class="validate"> <label for="password">Password</label> </div> </div> -
Getting this error psycopg2.errors.DuplicateTable: relation "posts_post" already exists
I am getting this error after deleting all migrations and again I did makemigrations and during make migrations getting this error. Applying posts.0001_initial...Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "posts_post" already exists The above exception was the direct cause of the following exception: return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "posts_post" already exists This is the production server I can't reset the psql database. -
Correct way for nested python classes (or django foreign keys.) *Conceptual/engineering question*
This is more of a conceptual/engineering question than an actual programming question, but I keep going back and forth between what is the "right" thing to do here. For quick background, I am still a bit of a noob at python/django and don't have a ton of experience working with classes. The program I'm trying to develop is an inventory management app. There are multiple products but lets simplify and say one is shoes and one is clothing. Both products share some attributes (UPC, size, color, etc), but also have some unique attributes (shoe_width, clothing_type) as well. Additionally, it seems like I should have a separate Product class (unique product attributes UPC, size shoe_width, clothing_type) and InventoryItem class (attributes unique to each piece of inventory such as price paid or condition) that inherits its corresponding Product class attributes. Conceptually, I am trying to build this multi-purpose. Users should be able to view product information (not inventory related) and add products and inventory items via django admin or via spreeadsheet upload (spreadsheet hooks already built.) So to the actual question, what is the correct way to implement the individual classes and what are some of the problems I may run into … -
update django inline formset class based view
i've created web blog with django 2.2 each post has multiple images , but when i try to update the post the images wont updated i use class based view class Post(models.Model): user= models.ForeignKey(Account,on_delete=models.CASCADE) title= models.CharField(max_length=100) slug = models.SlugField(unique=True,blank=True,null=True) #others class PostImage(models.Model): post= models.ForeignKey(Post,on_delete=models.CASCADE,related_name='images') media_files = models.FileField(upload_to=random_url) def __str__(self): return self.post.title and this my forms.py class PostImageForm(forms.ModelForm): class Meta: model = PostImage fields = [ 'media_files' ] class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = [ 'title','description',#and others ] my views.py PostImageFormSet = inlineformset_factory( Post,PostImage,form=PostImageForm,extra=1,can_delete=True,can_order=False ) class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView): model = Post form_class = PostUpdateForm template_name = 'posts/update_post.html' def get_context_data(self,**kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['images'] = PostImageFormSet(self.request.POST or None,self.request.FILES,instance=self.object) else: data['images'] = PostImageFormSet(instance=self.object) return data def form_valid(self,form): context = self.get_context_data() images = context['images'] with transaction.atomic(): if form.is_valid() and images.is_valid(): self.object = form.save() images.instance = self.object images.save() return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.username == post.user.username: return True return False def get_success_url(self): return reverse_lazy('post:post-detail',kwargs={'slug':self.object.slug}) it only save the post form not images , it doesnt affect images form thanks -
How to customize url pattern in django
First of all i am new & enjoying django application with no programming background. I was wondering can i generate urls like this www.example.com/user,1 instead of default www.example.com/user/1 where 1 is pk.