Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can't display the image saved in the database
I wrote two templates in Django "index.html" and "detail.html". In both templates, I display png, in the template "index" the graphics are displayed correctly, and in the template "detail" has the status "src (unknown)". detail.html (details.html should display only one graphic) <section class="jumbotron text-center"> <div class="container"> <h1 class="jumbotron-heading">Course Detail</h1> <p class="lead text-muted"> {{ films.summary}}.</p> <img class = "card-img" src="{{film.image.url}}" > </img> <p> <a href="{% url 'index' %}" class="btn btn-primary my-2">Back</a> </p> </div> </section> index.html <div class="row"> {% for film in films.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <a href="{% url 'detail' film.id %}"> <img class = "card-img" src="{{film.image.url}}" > </img> </a> <div class="card-body"> <p class="card-text"> {{film.summary}} </p> </div> </div> </div> {% endfor %} </div> </div> views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Films # Create your views here. def index(request): films = Films.objects.all() return render(request, 'films/index.html',{'films':films}) def detail(request, films_id): films_detail = get_object_or_404(Films,pk=films_id) return render(request, 'films/detail.html',{'films':films_detail}) urls.py from django.urls import path from .import views urlpatterns = [ path('', views.index, name="index"), path('<int:films_id>', views.detail, name="detail"), ] -
Django- admin: compare unique values before save
I have two models user and telephone, where telephone is displayed under user-admin. User can have only one main telephone number (so only one number can be set as main). I tried to use unique_together but that didnt work as i wanted. My models: class User(models.Model): name = models.CharField(...) class Telephone(models.Model): number = models.CharField(...) main = models.NullBooleanField(choices=((None, "Normal"),(True, "Main")) user = models.ForeignKey(User, on_delete=models.SET_NULL) my problem is: i want to change first telephone number from main to normal and set second number from normal to main at same time in django-admin. After i press save.. i get ValueError that said unique error. i tried to rewrite save and clean method in model, but there i get only one telephone number at time.. so i cant compare with other numbers that belongs under user So my question is: Is there a way how to get a list of changes made in admin to compare fields before saving to database? -
How to put the default datefield in a form with the previous date that was given before django
Well, i am using a datefield. My question is how can i set the default dateField form (in the template) to put it with the previous date that the field has. class enterprisedata(models.Model): .... date = models.DateField(default=timezone.now) .... And this is the template where i am using it: <!--Date of foundation--> <strong>Fecha de fundación:</strong> <div class="form-group"> <input class= "form-control" type="date" name="date" value="{{enterprise.date}}" > </div> See that the form control has the value "enterprise.date", cause i am trying to put the date that it had before the new one... If you can help me i will appreciate... Thank you!. -
Entry gets into the DB even if an exception is thrown
So I have a form which takes some input and a file field. I'm using a validator on the file filed to check for the size of the file. It is working well because I get the error on the page saying that the file is too large, but the entry still gets into the DB. I don't know why this happens. I supposed that raising an exception would do the trick in my case, but it does not. models.py from django.db import models from django.contrib.auth.models import User from .validators import validate_file_size # Create your models here. class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) dataSolicitare = models.DateField(auto_now_add=True) cor = models.CharField(max_length=25) denumireMeserie = models.CharField(max_length=12) locuri = models.IntegerField() agentEconomic = models.CharField(max_length=50) adresa = models.CharField(max_length=150) dataExpirare = models.DateField() experientaSolicitata = models.CharField(max_length=200) studiiSolicitate = models.CharField(max_length=200) judet = models.CharField(max_length=20) localitate = models.CharField(max_length=25) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) rezolvata = models.BooleanField(default=False) def __str__(self): return self.cor class CV(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) dataUploadCV = models.DateField(auto_now_add=True) nume = models.CharField(max_length=12) prenume = models.CharField(max_length=12) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) CV = models.FileField(upload_to='documents/%d/%m/%Y', validators=[validate_file_size]) rezolvata = models.BooleanField(default=False) def __str__(self): return self.nume + " " + self.prenume + ": " + str(self.CV) validators.py from django.core.exceptions import ValidationError def validate_file_size(value): filesize=value.size if … -
Django NotFoundError after plugin elastic search
After i plugin elastic search and i run previously worked good testcase, now it fires me this error message.. raise ConnectionError("N/A", str(e), e) elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7fea39197588>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7fea39197588>: Failed to establish a new connection: [Errno 111] Connection refused) b When i try to post something from django defult admin templates, it firs me this error... status_code, error_message, additional_info elasticsearch.exceptions.NotFoundError: NotFoundError(404, '<!DOCT..bla bla bla bla bla all these shit happening after i add elastic search... this is my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'blog2', 'search', 'rest_framework', 'django_elasticsearch_dsl', ] ELASTICSEARCH_DSL={ 'default': { 'hosts': '127.0.0.1:8000' }, } I am seeing those error only when i add elastic search and documents.py.... If you dont understand whats going on, you can see these below: Optional these may be blog2/models.py below from django.db import models import uuid class Organization(models.Model): organization_name = models.CharField(max_length=50) contact = models.CharField(max_length=12, unique=True) def __str__(self): return self.organization_name class Author(models.Model): name = models.CharField(max_length=40) detail = models.TextField() organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Article(models.Model): alias = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = … -
How to use Razorpay intergration for python with django
I want to use Razorpay payment gateway for my site. I built my site using Django package for web development in Python. How can I use Razorpay in it? The Razorpay docs only show how to integrate it with Flask not with Django. Can anyone help it with a little example or so? Or if you can suggest any other payment gateway to use with Django that works in India. -
parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object
I have the error with this models.py ? This replace built-in User model. Errors are detected in line user_obj.save(using=self._db) in def UserManager and in line def create_superuser user = self.create_user( email, last_name=last_name, first_name=first_name, password=password, ) It seems like it does not like my timestamp attribute with date value ? thanks from django.db import models from django.utils import timezone from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserManager(BaseUserManager): def create_user(self, email, last_name, first_name, password=None, is_active=True, is_staff=False, is_admin=False): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') if not password: raise ValueError('Users must have a password') user_obj = self.model( email=self.normalize_email(email), ) user_obj.set_password(password) # change user password user_obj.first_name = first_name user_obj.last_name = last_name user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email,last_name, first_name, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, last_name=last_name, first_name=first_name, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return … -
How to format text written to a variable?
I am get the text from the database. He comes in the following form. city = City.objects.first() country = Contry.objects.first() metatag = MetaTag.objects.first() #text {city.name} else text {country.name} How can I format it? -
'BooleanField' object has no attribute 'use_required_attribute' in django
as the title says i am getting the error while i am using a booleanfield: 'BooleanField' object has no attribute 'use_required_attribute' in django Models.py class contactData(models.Model): ... mapActivated = models.BooleanField(default=True) forms.py: class ContactForm(forms.ModelForm): class Meta: model = contactData fields = [ 'vision', 'horario', 'image_path', 'mapActivated', ] labels = { 'image_path': '', } widgets = { 'mapActivated': forms.BooleanField(required=True) } Anyone can help me with this? Thank you! -
How do I stop ajax call from refreshing my page?
<form id="review" method="post"> {% csrf_token %} <button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" > <span class="icon text-white-50"> <i class="fas fa-poll-h"></i> </span> <span class="text">Fetch Reviews</span> </button> </form> This is my html form on a Django rendered page <script type="text/javascript"> $(document).on('submit','#review'.function(e){ e.preventDefault(); e.stopPropagation(); $.ajax({ type:'POST', URL:'/reviews/', data:{ asin:$('#sbtn').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, beforeSend:function() { $('#loader').removeClass('hidden'); }, complete : function() { $('#loader').addClass(''); }}); return false; }); This is the ajax function on the page. The problem is...the current page is the result of a form on a previous page so as soon as the form-submit event is invoked the page refreshes and data on the page is lost. I tried both e.preventDefault() and e.stopPropagation() but that doesn't help. I'd like to know if you have some approach or a workaround..Thank you! -
How can I embed an API to a Django Project?
So I'm working on a Django project where I want to embed an API made by a friend of mine with python and some libraries like matplotlib and others,it should process some images and return a result(also an Image).however i can't really get my mind around it,I made a data model with ImageField but i don't know how I can call the API with get(from HTML button) method ( making a view for it ) or how i should handle this. I thought that I could make a model with two fields one is the uploaded by the user and the other is the processed but what's next ? -
Django sometimes receives ManyToManyField lookup result from some sort of cache
When I try to access a ManyToManyField with through= specified using the field name, the results are taken from some kind of cache - not from the database. Suppose we have these (simplified) models: class Device(models.Model): name = models.CharField(max_length=50) class Person(models.Model): name = models.CharField(max_length=50) devices = models.ManyToManyField( Device, through="Person_device", related_query_name="device", related_name="person" ) class Person_device(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) device = models.ForeignKey(Device, on_delete=models.CASCADE) row_time = models.DateField(auto_now=True) # just some extra data ipad = Device.objects.create(name="iPad") iphone = Device.objects.create(name="iPhone") samsung = Device.objects.create(name="Samsung") sam = Person.objects.create(name="Sam") mary = Person.objects.create(name="Mary") Person_device.objects.create(person=sam,device=iphone) Person_device.objects.create(person=susie,device=samsung) # Note we didn't apply ownership of any iPads Now, let's try to access some of these. [device.name for device in Person.objects.get(name="Sam").devices] [device.name for device in Person.objects.get(name="Mary").devices] We were supposed to get ["iPhone"] ["Samsung"] But what I actually am getting is: ["iPad"] ["iPad"] Now, this problem is hard to reproduce. I have simplified this, but this is essentially the same code I used in my project. One of the possible reasons that crossed my mind, is that it messes up when you play around with editing the model, running application, then editing it back (no migrations in the middle). Of course, this problem is solved if we access the necessary QuerySet directly by … -
Django django.utils.timezone.make_aware not adding default timezone
Naive datetime not properly converted in timezoned datetime by django timezone.make_aware My application is handling some strings representing datetime, for example: 2019-05-20 15:47:19 I'm receiving these data from an external API so I don't have control over the received values. I'm trying to set this datetime in my python model using the following code: datetime_to_parse = '2019-05-20 15:47:19' my_model.start = timezone.make_aware(datetime.strptime(datetime_to_parse, "%Y-%m-%d %H:%M:%S")) my_model.save() What I'm obtaining is the following error: DateTimeField Event.start received a naive datetime (2019-05-20 15:47:19) while time zone support is active Since I'm calling make_aware I expect the datetime to be automatically converted in a timezoned datetime using the timezone specified in my django settings. My django settings contain the following definition: TIME_ZONE = "Europe/Zurich" Am I doing something wrong ? -
Why one Django database query is working when similar one is not
I reused similar code twice but on one occasion it doesn't add anything to database, can anyone tell me why? Lack of form validation is the problem? I'm trying to increase some user model fields by certain integer every time form is send to server. One of them working, one doesn't. Code below increase amount_comments by one every time: def add_comment(request, pk): ticket = get_object_or_404(Ticket, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): user = CustomUser.objects.get(username=request.user) user.amount_comments += 1 user.save() return redirect('show_single', pk=pk) else: form = CommentForm() ...and this one doesn't increase contributions for some reason: def show(request, pk): if request.method == "POST": user = CustomUser.objects.get(username=request.user) user.contributions += 5 user.save() return redirect('checkout', pk=pk) I don't get any errors just checking admin panel and user doesn't get his contributions field changed by 5 when amount_comments goes up every time. -
Unable to display QuerySet in Django view
I was trying to display a QuerySet using method below, Passing Django Queryset in Views to Template I was able to display single object by using get() method, however it returns as a blank page when I try to return all data in the Restaurant Table. Class Restaurant class Restaurant(models.Model): restId = models.AutoField(db_column='restId', primary_key=True) restName = models.TextField(db_column='restName') phone = models.IntegerField() address = models.TextField() ratings = models.DecimalField(max_digits=2, decimal_places=1) cuisine = models.TextField() region = models.TextField() #image = models.ImageField() last_modify_date = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = "restaurant" views.py def index_view(request): rest_list = Restaurant.objects.all() context = { 'rest_list': rest_list } return render(request, 'index.html', context) index.html <h1>Index</h1> {% for rest in rest_List %} {{ rest.restId }} {{ rest.restName }} {% endfor %} -
How do I implement a location drop down menu
I would like to implement a location drop down menu like the ones shown on Airbnb.com and Postmates.com. Basically I would like a user to be able to type in a location anywhere around the world and show only results from that location. I assume the location drop down menu has something to do with Google maps but I can't seem to figure it out. -
Django NotFoundError at /admin/blog2/article/add/
I am trying to create a post from Django default admin template but fires me an error that i am not getting... this is my models: from django.db import models import uuid class Organization(models.Model): organization_name = models.CharField(max_length=50) contact = models.CharField(max_length=12, unique=True) def __str__(self): return self.organization_name class Author(models.Model): name = models.CharField(max_length=40) detail = models.TextField() organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Article(models.Model): alias = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) and fires me below this error: -
How to fix "pip installation error on pillow"
I just ran pip install pillow on pycharm windows but it gives an error as mentioned below help me to solve this problem i tired manually installing pillow form downloading pillow form github by python setup.py install but didn't work on installing on pycharm i don't know what the error is the entire process in mentioned below:- Collecting Pillow Using cached https://files.pythonhosted.org/packages/81/1a/6b2971adc1bca55b9a53ed1efa372acff7e8b9913982a396f3fa046efaf8/Pillow-6.0.0.tar.gz Installing collected packages: Pillow Running setup.py install for Pillow ... error Complete output from command C:\Users\rijal\Desktop\webdevlops\django_project\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\rijal\\AppData\\Local\\Temp\\pip-install-di5is9gd\\ Pillow\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\rijal\AppData\Local\Temp\pip-record-zdea w2p6\install-record.txt --single-version-externally-managed --compile --install-headers C:\Users\rijal\Desktop\webdevlops\django_project\venv\include\site\python3.8\Pillow: C:\Users\rijal\AppData\Local\Temp\pip-install-di5is9gd\Pillow\setup.py:29: RuntimeWarning: Pillow does not yet support Python 3.8 and does not yet provide prebuilt Windows binaries. We do not recommend buildin g from source on Windows. warnings.warn( running install running build running build_py creating build creating build\lib.win-amd64-3.8 creating build\lib.win-amd64-3.8\PIL copying src\PIL\BdfFontFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ContainerIO.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\CurImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\ExifTags.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\features.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FitsStubImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FliImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FontFile.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.win-amd64-3.8\PIL copying src\PIL\FtexImagePlugin.py -> … -
Is Django admin functionality used in production on large sites or do you use it for testing only?
I have been working through the Django tutorial and I note on page 7... https://docs.djangoproject.com/en/2.2/intro/tutorial07/ ...that the much touted "admin for free" feature of Django is rather weak. The tutorial shows how to add Choice objects to Question objects in the Polls admin. Three Choices are added by the ChoiceInline class, but the problem is that none of those three may be removed. Only Choices added by clicking the Add button may be removed. This is poor UI/UX because it mixes static and dynamic behaviour in an arbitrary way. It doesn't look so bad in the tutorial example, but if the feature is deployed thoroughly, it can result in new Question objects having three Choices (or however many are specified) that cannot be deleted. One solution is to use no Choices by default and only use the Add button, but that is not good either, as there should be at least one Choice object by default, or rather two of them, since we're working on a Poll. But the fields should all have the same functionality, they should all be removable. Having seen this, my question for those experienced in working with Django on large projects: Is the "admin for … -
How can I display the values from a ManyToMany Field in Django instead of their Id?
I have two models Influencer class Influencer(models.Model): full_name = models.CharField('Full Name',max_length=255) username = models.CharField('Username',max_length=255,unique=True) photo = models.URLField(blank=True,max_length = 500) email_id = models.EmailField('Email Id',blank=True,max_length=500) categories = models.ManyToManyField(Category,blank=True,max_length=400) and 2. Categories class Category(models.Model): name = models.CharField(max_length=400) def __str__(self): return self.name Influencer has a many to many field categories. My views functions to display all the influencers is: def index(request): influencers = Influencer.objects.all().order_by('followers') paginator = Paginator(influencers,16) page = request.GET.get('page') paged_listings = paginator.get_page(page) user_list = UserList.objects.all().filter(user_id = request.user.id) queryset = list(chain(paged_listings,user_list)) ser_query = serializers.serialize('json', queryset) return HttpResponse(ser_query,content_type='application/json') The HttpResponse contains category id's instead of category names, something like this: where categories is an array which contains category id's. I want to display the name of categories instead of their id's. I think this can be achived using Django Rest Framework nested serializer, but at this moment I am not using DRF. -
How the users can access my Elasticsearch database in my Django SaaS?
Let's say that I have a SaaS based on Django backend that processes the data of the users and write everything to the Elasticsearch. Now I would like to give users access to search and request their data stored in ES using all possible search requests available in ES. Obviously the user should have only access to his data, not to other user's data. I am aware that it can be done in a lot of different ways but I wonder what is safe and the best solution? At this point I store everything in one index and type in the way shown below but I can do this in any way. "_index": "example_index", "_type": "example_type", "_id": "H2s-lGsdshEzmewdKtL", "_score": 1, "_source": { "user_id": 1, "field1": "example1", "field2": "example2", "field3": "example3" } -
Using numpy, javascript, and django
I am trying to create a web app using django, and integrating some javascript and i'm not sure where to put the numpy analysis to allow javascript to access the data easily. I am just looking for some advice on where to put my data analysis code within the django framework. At the moment I have got a model/form for people to enter data, and within views.py I have access the inputs and done the calculation (creating a dataframe) there. Still within the views, I have created a graph (using matplotlib) that saves as an image that my html reads in. I am not happy with the graph that is being created, so I want to use chart.js for this instead. However I am not sure on the best way to go about structuring this. Should I keep the calculations within the views class, or is it best to move it out? I have looked at using the django rest framework, but I am having difficulty getting the dataframe that I created in my view for the javascript to read. Has anyone done a similar thing or has any advice on how to go about setting this up? -
Sqlite ordering/sorting for turkish alphabet
How can I sort letters for Turkish alphabet? Can I do it with a function? > def a(request): > keyword = request.GET.get("keyword") > if keyword: > makaleler = Makale.objects.filter(title__contains = keyword) > return render(request,"a.html",{"makaleler":makaleler}) > > makaleler = Makale.objects.filter(title__startswith="A").order_by("title") > context = { > "makaleler":makaleler > } > return render(request, "a.html",context) -
ModelForm save() got an unexpected keyword argument 'commit'
i try to make custom user in django but have a problem with, please help the probem is when me add or change the user from the admin and save it, i am not understand where the problem is but i feel in form.py, please help me to fix this. models.py class ObUser(AbstractUser): SEX = ( ('M', 'MALE'), ('F', 'FEMALE'), ) username = models.CharField(max_length=30, unique=True) email = models.EmailField(max_length=30, unique=True, blank=False, null=False) first_name = models.CharField(max_length=20, blank= False, null=False) last_name = models.CharField(max_length=50, blank= False, null=False) password = models.CharField(max_length=50) born_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) address = models.TextField(blank=True, null=True) phone = models.IntegerField(blank=True, null=True) sim_id = models.IntegerField(blank=True, null=True) quotes = models.CharField(max_length=100, blank=True, null=True) sex = models.CharField(max_length=1, choices=SEX) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True, null=True) last_update = models.DateTimeField(auto_now=True, auto_now_add=False, blank=True, null=True) date_joined = models.DateField(auto_now=False, auto_now_add=True) is_verified = models.BooleanField(default=False) objects = ObUserManager and then i make the ModelForm form.py class ObUserCreate(forms.ModelForm): password1 = forms.CharField(label='password', widget=forms.PasswordInput) password2 = forms.CharField(label='konfirmasi password', widget=forms.PasswordInput) class Meta: model = ObUser fields = ('username', 'email', 'first_name', 'last_name', 'password') def clean_password2(self): password1=self.cleaned_data.get('password1') password2=self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError('password tidak sama') return password2 def save(self, commit=True): self.clean_password2() user = super().save(commit=False) user.set_password(self.cleaned_data['password2']) if commit: user.save() return user class … -
Connect Form attributes with User model inside views before saving form data
I am trying to connect a form to the username value. What I am trying to do is to save the person who commented on a post (author) as the username of the User. I have tried a few methods but none is working. When I ask users to manually provide an author value, it saves it and shows in my html page as posted by followed by the value provided by users. Below are the codes. def add_comment_to_post(request,pk): post=get_object_or_404(Post,pk=pk) if request.method=='POST': form=CommentForm(request.POST) if form.is_valid(): def update_form(self,form): self.comment=form.save(commit=False) self.comment.post=post self.comment.author= User.username self.comment.save() return redirect('post_detail',pk=post.pk) else: form=CommentForm() return render(request,'blog/comment_form.html',{'form':form}) When I used the above code, the submit button did not return any value. and I have also used comment=form.save(commit=False) comment.author = User.username The above code says value too big(50) My Commentform is class CommentForm(forms.ModelForm): class Meta: model= Comment fields=('text',) widgets={ 'text': forms.Textarea(attrs={'class': 'editable medium-editor-textarea'}), and models.py is class Comment(models.Model): post=models.ForeignKey('blog.Post', related_name='comments',on_delete=models.CASCADE) author=models.CharField(max_length=50) created_date=models.DateField(default=timezone.now) approved_comment=models.BooleanField(default=False) def approve(self): self.approved_comment=True self.save() def get_absolute_url(self): return reverse('post_list') def __str__(self): return self.text What can I do to save the value so that the only that users, who commented on the post is able to delete the comment (except admin).