Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting an Error as "decoding to str: need a bytes-like object, int found" while tried to return id and field value in django models
model #1 class Add_Job(models.Model): job_name=models.CharField(max_length=254) client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client') #client=models.ManyToManyField(Client) project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project') #project=models.ManyToManyField(Project) user=models.ForeignKey(Users,on_delete=CASCADE) Hours=models.TimeField(null=True) start_Date = models.DateTimeField(max_length=10) end_Date=models.DateTimeField(max_length=10) def __str__(self): return str(self.id, self.job_name) model #2 class Add_Timelog(models.Model): project=models.ManyToManyField(Project) client=models.ManyToManyField(Client) Job=models.ManyToManyField(Add_Job) #Date = models.DateField(max_length=100 ,auto_now_add=True,editable=True) Date= models.DateField(default = datetime.date.today) Hours=models.TimeField(null=True) def __str__(self): return str(self.Date) while I tried to return the 'id' and 'job_name' from the 'Add_Job' model it is getting reflected in the database table. But the 'Add_timelog' model is getting an error as "TypeError at /api/Add_Timelog/ decoding to str: need a bytes-like object, int found". Don't know why it is getting an error. kindly help to solve this issue. -
How do I make django-form's foreign-key point to a model that is being currently created
My Models.py contains 2 models, each Project can have multiple Role (i.e. one-to-many relationship): class Project(models.Model): title = models.CharField(max_length=2000) state_of_project = models.CharField(max_length=10, default='ongoing') introduction = models.TextField(blank=True) class Role(models.Model): role_name = models.CharField(max_length=30) project = models.ForeignKey(Project, on_delete=models.SET_NULL, null = True) def __str__(self): return self.role_name And they have their respective forms in the forms.py file, which are accesed in two different html file: class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) class Meta: model = Project fields = ['title', 'state_of_project', 'introduction'] class RoleForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(RoleForm, self).__init__(*args, **kwargs) project = forms.ModelChoiceField(queryset=Status.objects.all()) class Meta: model = Role fields = ['role_name', 'project'] While filling up ProjectForm from an html page, I wanted to make it possible to go to another link that allows you to fill RoleForm for it on the other tab. But the role you add there should only be linked to current project (i.e. foreign key of that role should point to the project that is being created by the user now, but is not yet in the database). But in my current implementation through django-form, user is able to just select any past project for a new role, instead of only being allowed to select project that is … -
Error during template rendering with django-formtools
I'm following the django-formtools documentation, and curiously when I add this part: <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} <input type="submit" value="{% trans "submit" %}"/> </form> I get the Tag start is not closed error right here: <input type="submit" value="{% trans "submit" %}"/> And I do get an error in Pycharm but I can't find why, I only removed trans because I won't be using it at the moment. I also have my doubts that the "first step" and "prev step" buttons are ok -
CORS Issue - DJANGO rest_framework
I have been facing the "CORS policy" issue in my API for few days and I cannot fix it. I have used the following middleware in 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', 'corsheaders.middleware.CorsMiddleware' ] ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True Am i missing something? I am currently using Python 3.6.5 and DJANGO (3.1.7) Thanks. -
NOT NULL constraint failed: dashboard_profile.user_id
I'm trying to save the last IP of User to the Profile module in Django but I get always NOT NULL constraint failed I know that last_ip should be set tonull=True and I run this commands:py .\manage.py makemigrations, py .\manage.py migrate. Thanks in advance. #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, max_length=150) last_ip = models.GenericIPAddressField(null=True, blank=True) avatar = ContentTypeRestrictedFileField(max_upload_size=10485760, null=True, verbose_name="",default='default.jpg', blank= True, content_types=['image/png', 'image/jpeg']) def __str__(self): return self.user.username #forms.py class UpdateUserForm(forms.ModelForm): username = forms.CharField(max_length=150, required=True) first_name = forms.CharField(max_length=150, required=False) last_name = forms.CharField(max_length=150, required=False) email = forms.EmailField(required=True) class Meta: model = User fields = ['username','first_name','last_name','email'] class UpdateAvatarBio(forms.ModelForm): avatar = forms.ImageField() bio = forms.CharField() class Meta: model = Profile fields = ['avatar', 'last_ip', 'bio'] #views.py def ip_client(request): return ( x_forwarded_for.split(',')[0] if (x_forwarded_for := request.META.get('HTTP_X_FORWARDED_FOR')) else request.META.get('REMOTE_ADDR') ) def profile(request): ip = ip_client(request) model = Profile(last_ip=ip) model.save() # Traceback suppose here is the issue if request.method == 'POST': ... ... return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form}) -
i got error 500 on production when i read filefield in django
hello everyone please help me i have recently maked a website but i got 500 error when i put it in production but strangly all is working well in my computer i am trying to read the buffer of a filefield inside a model and itson local but not in production class post(models.Model): titre=models.CharField(unique=True,null=True,max_length=100) description=models.TextField(null=True,blank=True,max_length=400) T=models.CharField(default="image",blank=True,max_length=50) image=models.FileField(null=True) cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True) datepost=models.DateTimeField(auto_now_add=True,blank=True) user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True) vue=models.IntegerField(default=0,blank=True) def __str__(self): return self.titre def save(self, *args ,**kwargs): #cette partie permet de generer un identifiant unique f=self.image.readline() mime=magic.from_buffer(f,mime=True) if "video" in mime : self.T="short" super(post,self).save(*args,**kwargs) sorry for my english and thank you for your help -
Unknown string showing up in rendered HTML code
A random string "b b b b b" gets inserted between two HTML components which doesn't exist in my code to begin with. I currently have a js script to find this garbage string and just remove it manually. Was wondering if anyone knew why this was happening so I could actually fix it instead of this workaround This is how the relevant part of the code looks - HTML Code This is how the rendered HTML Code looks - Rendered Website code This is a Python-Django project being run on Chrome. I tested the same with firefox and this string shows up there too. So, I doubt it's a browser issue. Any help would be appreciated! Thanks :) -
How to setup Django with NPM?
I am very new to Django (and NPM for that matter) so please bear with me. I would like to use Django as my framework, but having NPM setup would make it a lot easier. For example, I wish to install TailWindCSS, Bootstrap, Font Awesome, and more which can be either run by CDN or manually downloaded and put into my Django project to work. However, if I just got npm installed then I can easily manage versions and install these packages at once. Therefore, right after I have my Django environment setup, how can I install and use NPM? Thanks! -
How to properly create User with allauth and custom user model in Django 4.0
I have a custom User model, subclassed from django AbstractUser: class User(AbstractUser): alias = models.CharField( "Alias", max_length=50, unique=True, null=True ) account_uuid = models.UUIDField(blank=True, null=True) I have installed allauth library, and all the signup/login mechanisms are working fine. The problem I'm facing is when I want to import Users instances from a different environment. from apps.users.models import User user, created = User.objects.update_or_create( email=account_info.get('contact').get('email_address'), defaults={ 'username': email, 'account_uuid': account_uuid, 'alias': alias } ) When a user had logged in previously with a social connector, this update/create raises an Integrity error for a constraint on User/email. Is there a proper way for creating a User instance so that it wouldn't break any underlying relations created with allauth models? -
Using query strings in django GET
I've a GET request in django rest framework that fetches data using kwargs. class FetchUser(APIView): def get(self, request, **kwargs): try: email = kwargs.get('email') user = User.objects.get(email=email) return Response(UserSerializer(user).data, status=status.HTTP_200_OK) except(KeyError, User.DoesNotExist) as e: return Response(str(e), status=status.HTTP_404_NOT_FOUND) Here's my url path(r'fetch/<str:email>', FetchUser.as_view(), name='fetch_user'), However I want to fetch the data using a query string, Something like http://base/fetch?email=something How do I modify my urls and views to do this? -
Django + React App in Azure gives a server error - 500 everytime
I have deployed a Django app to Azure through Github actions to Azure app service. But it gives a Server error 500 everytime. I have configured the static files and react template properly. In the Diagnose tab there's no error is displaying. How can I troubleshoot and find the error or Is there any other things to configure in Azure? I hosted a same copy in Heroku and it works there. -
django urls without a trailing slash show Page not found
in django urls without a trailing slash in the end i get this result "Page not found 404" the same project and the same code in one pc i get different result. this code is when i get the page without slash: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), ] and this the same code but i should to add slash from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name='about'), ] what i am waiting in the frontend its my views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def about(request): return HttpResponse('about page') i am waiting for your help guys -
Django Pass URL Parameter To Decorator
trying to redirect user to a page if they're not staff members. how do i pass a url parameter to a django decorator? # categories.urls.py from django.urls import path from categories.views import CategoryInfoView, CategoryDetailView app_name = 'categories' urlpatterns = [ path('<slug:handle>', CategoryDetailView.as_view(), name = 'category'), path('<slug:handle>/info/', CategoryInfoView.as_view(), name = 'category_info'), ] # categories.view.py class CategoryInfoView(LoginRequiredMixin, DetailView): model = Category template_name = 'categories/info.html' context_object_name = 'category' @redirect_if_not_staff(redirect_to = reverse_lazy('categories:category')) # <-- how do i pass the url parameter here?! def get(self, request, *args, **kwargs): return super().get(self, request, *args, **kwargs) def get_object(self): return get_object_or_404(Category, handle = self.kwargs.get('handle')) # decorator.py def redirect_if_not_staff(*setting_args, **setting_kwargs): """ A decorator to redirect users if they are not staff Can be used as: @decorator(with, arguments, and = kwargs) or @decorator """ no_args = False redirect_to = setting_kwargs.get('redirect_to', reverse_lazy('index')) if len(setting_args) == 1 and not setting_kwargs and callable(setting_args[0]): func = setting_args[0] no_args = True def decorator(func): @wraps(func) def redirect_function(self, request, *args, **kwargs): if not request.user.is_staff: return HttpResponseRedirect(redirect_to) return func(self, request, *args, **kwargs) return redirect_function if no_args: return decorator(func) else: return decorator how do i get localhost:8000/categories/sample/info/ to redirect to localhost:8000/categories/sample/ if the user is not a staff using decorators currently getting this error NoReverseMatch at /categories/agriculture/info/ Reverse for 'category' … -
Programmatically generate Django models for legacy databases
I'm trying to find out if there is a way to programmatically generate Django models for legacy databases. So given a list of legacy tables, create a model for each one. Here is an example of what I mean class Person_001(models.Model): id = models.IntegerField(primary_key=True) huge_dataset = models.CharField(max_length=70) class Meta: managed = False db_table = 'person_001' So for example, create this model for person_001, person_002 etc... I realize there may be a more efficient way of storing this data and I am opened to suggestions, but the data has been stored this way because huge_dataset is, well, huge. -
Django - if checkbox is selected, execute function
hey guys I'm trying to implement a feature in the user system where if you click the "is_staff" option another options pops up saying to enter your staff_id number. Is this possible? if so how can I implement it - or do I need to take a completely different approach. thanks! So something like this code from accounts>models.py from datetime import date import email import imp from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Email address is required') if not username: raise ValueError('Username is required') user = self.model( email=self.normalize_email(email), username = username, ) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password = password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self.db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) #staff_number = models.CharField(max_length=10, unique=True) is_superuser = models.BooleanField(default=False) #note for self - these fields are required USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] objects = MyAccountManager() def __str__(self): return self.email def … -
Checkbox checked, javascript in Django template
I am just trying to display hiddens items in django template when checkbox is checked, but in my console i am getting 1:194 Uncaught TypeError: Cannot read properties of null (reading 'checked') at inventoryFunction (1:194:22) at HTMLInputElement.onclick (1:107:73) the items are hidden in a table and when i check a category i am hoping to get them displayed here is the template : <div class="inventory-content"> <div class='category'> <div>Categories</div> <div class='category-checkbox'> {%for category in categories%} <input type="checkbox" id="{{category.id}}" onclick="inventoryFunction()"> <label for="{{category.id}}"> {{category.name}}</label><br> {%endfor%} </div> </div> <div class='items'> {% for category in items%} <div class='{{category.id}}' style="display:none"> <div>{{category}}</div> <table class='runninghours-table'> <tr> <th>Item name</th> <th>part number</th> <th>R.O.B</th> </tr> <tbody> {%for item in category.items.all%} <tr> <td>{{item.name}}</td> <td>{{item.part_number}}</td> <td>{{item.ROB}}</td> </tr> {%endfor%} </tobdy> </table> </div> {%endfor%} </div> </div> the JavaScript : <script> function inventoryFunction() { var checkBox = document.getElementById("{{category.id}}"); var item = document.getElementsByClassName("{{category.id}}"); if (checkBox.checked == true) { item.style.display = "block"; } else { item.style.display = "none"; } } </script> -
Real time bidirectional data sync client-server
I am trying to achieve real time data sync on my android application to django server with support to offline capabilities. What protocols or specifications to achieve that. Just like how Firebase works but with Android and Django having PostgreSQL as DB -
"unexpected keyword argument 'version'" when trying to deploy a Django app on Heroku
2022-02-06T22:55:19.786956+00:00 app[web.1]: Error: __init__() got an unexpected keyword argument 'version' 2022-02-06T22:55:19.959506+00:00 heroku[web.1]: Process exited with status 1 2022-02-06T22:55:20.021043+00:00 heroku[web.1]: State changed from starting to crashed 2022-02-06T22:55:20.033987+00:00 heroku[web.1]: State changed from crashed to starting 2022-02-06T22:55:22.000000+00:00 app[api]: Build succeeded 2022-02-06T22:55:27.937148+00:00 heroku[web.1]: Starting process with command `gunicorn bona_blog.wsgi:application --log-file -` 2022-02-06T22:55:30.108106+00:00 app[web.1]: 2022-02-06T22:55:30.108127+00:00 app[web.1]: Error: __init__() got an unexpected keyword argument 'version' 2022-02-06T22:55:30.316169+00:00 heroku[web.1]: Process exited with status 1 2022-02-06T22:55:30.440121+00:00 heroku[web.1]: State changed from starting to crashed 2022-02-06T22:56:11.005567+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fceoapp.herokuapp.com request_id=45757802-6d06-4d6e-80d3-90feafdeb023 fwd="105.112.52.76" dyno= connect= service= status=503 bytes= protocol=https 2022-02-06T22:56:10.341541+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fceoapp.herokuapp.com request_id=c030a659-ad28-4088-8b87-58d94731a394 fwd="105.112.52.76" dyno= connect= service= status=503 bytes= protocol=https -
Django: update a model with the current user when an non-model form field is changed
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page. I want to allow the user to "adopt" one or more activities by ticking a box, and have their user record linked to each activity via a ForeignKey. Here are extracts from my code... models.py from django.contrib.auth.models import User class Task(models.Model): category = models.CharField(max_length=300) description = models.CharField(max_length=300) class Activity(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) title = models.CharField(max_length=150) notes = models.TextField(blank=True) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) The activity "owner" is linked to a User from the Django standard user model. I added an extra field in the form definition for the adopt field - I don't want to add it to the model as I don't need to save it once it's done it's job. forms.py class ActivityForm(forms.ModelForm): adopt = forms.BooleanField(required=False) class Meta: model = Activity fields = '__all__' views.py def manage_task(request, pk): task = Task.objects.get(pk = pk) TaskInlineFormSet = inlineformset_factory(Task, Activity, form = ActivityForm) if request.method == "POST": form = TaskForm(request.POST, instance = task) formset = TaskInlineFormSet(request.POST, instance = task) if form.has_changed() and form.is_valid(): form.save() if formset.has_changed() and formset.is_valid(): ## ? DO SOMETHING HERE ? … -
Django rest framework Detail not found while deleting
i have a a problem deleting an object via API. So i have 2 models, Answer and Vote vote is connected to Answer via foreignKey like this class Vote(models.Model): class AnswerScore(models.IntegerChoices): add = 1 subtract = -1 score = models.IntegerField(choices=AnswerScore.choices) answer = models.ForeignKey('Answer', on_delete=models.PROTECT) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) class Meta: unique_together = ('answer', 'user',) Now i have an API endpoint for creating a Vote for user on a particular answer path('answers/<int:pk>/vote', VoteCreate.as_view()), Looks like this: class VoteSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) answer = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Vote fields = '__all__' class VoteCreate(ParentKeyAPIView, generics.CreateAPIView): model = Vote parent_model_field = 'answer_id' serializer_class = VoteSerializer def perform_create_kwargs(self, **kwargs): return super().perform_create_kwargs(user=self.request.user, answer_id=self.kwargs['pk'], **kwargs) And i also want to delete the same vote using url like this path('answers/<int:pk>/voteDelete', VoteDelete.as_view()), Because i know that only 1 user(request.user) can have 1 Vote per answer. So i tried doing it similarly to creating class VoteDelete(generics.DestroyAPIView): serializer_class = VoteDeleteSerializer def get_queryset(self): queryset = Vote.objects.get(user=self.request.user, answer_id=self.kwargs['pk']) return queryset Im using the same serializer just like above* I get an error: Not Found: /api/v1/answers/55/voteDelete There is no any traceback, i have checked in fact that in database the Vote with answer_id 55 exists and i can delete them via … -
Why shutil dont copy django image
Good day! I try to copy image from one Django model instance to another, with file cloning. I know that I can make it easier state.image = self.image, but I need physical copy of file with new name. My source: original = os.path.join(settings.MEDIA_ROOT, self.image.name) target = os.path.join(settings.MEDIA_ROOT, self.image.path.split('.')[1] + '_' + str(state.pk) + '.png') shutil.copyfile(original, target) content = urllib.urlretrieve(target) state.image.save(self.image.path.split('/')[-1], File(open(content[0])), save=True) state.save() My output: celery_1 | File "/app/state/models/bills/change_coat.py", line 79, in do_bill celery_1 | shutil.copyfile(original, target) celery_1 | File "/usr/local/lib/python3.9/shutil.py", line 264, in copyfile celery_1 | with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst: celery_1 | FileNotFoundError: [Errno 2] No such file or directory: '/app/media/img/state_avatars/file.jpg' Please tell me what am I doing wrong -
dependent select script for django
Help with js. I have two selects that earn them with nested list dictionaries. I don’t know how to write a script so that when choosing a brand it would be possible to select only the selected brand, after choosing send a request with the brand and model of the car <form action="" method="post" id="dynamic_selects"> <div class="row"> <select class="form-select" aria-label="Default select example" id="marka"> <option value="0">Select auto</option> {% for car in marka_sorted %} <option value={{ car }}>{{ car }}</option> {% endfor %} </select> </div> <div class="row"> <select class="form-select" aria-label="Default select example" id="model" disabled> <option value="0">Select model</option> {% for marka, model in marka_sorted.items %} {% for model_select in model %} <option value={{ model_select }} class={{ marka }}>{{ model_select }}</option> {% endfor %} {% endfor %} </select> -
SMTPAuthenticationError in Weblate (which uses Django)
I checked quite a few stackoverflow questions about this and none doesn't seem to be the exact case as me and didn't really work for me so posting this question. So I'm trying to setup weblate using docker which wants me to set weblate email host user, password etc. to send mails to users when using the site, my current docker-compose.override.yml looks like this: version: '3' services: weblate: ports: - 1111:8080 environment: WEBLATE_EMAIL_HOST: smtp.mymailserver.com WEBLATE_EMAIL_PORT: 465 WEBLATE_EMAIL_HOST_USER: translate@domain.com WEBLATE_EMAIL_HOST_PASSWORD: password WEBLATE_SERVER_EMAIL: translate@domain.com WEBLATE_DEFAULT_FROM_EMAIL: translate@domain.com WEBLATE_SITE_DOMAIN: translate.mydomain.com WEBLATE_ADMIN_PASSWORD: mypass WEBLATE_ADMIN_EMAIL: myemail@domain.com I checked this with gmail app in mobile with the same outgoing server configuration and it worked perfectly fine there (I was able to send mails from it) but whenever I try it with weblate, I'm seeing this error: SMTPAuthenticationError: (535, b'Authentication credentials invalid') This is the whole error I get in the logs -
How to upload profile image corresponding to the user?
models.py from django.db import models from django.forms import fields, ModelForm from .models import UploadImage from django import forms class UploadImageForm(ModelForm): class Meta: # To specify the model to be used to create form model = UploadImage # It includes all the fields of model fields = ['picture'] forms.py from django.db import models from django import forms from django.contrib.auth.models import User # Create your models here. class UploadImage(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.ImageField(default='default.jpg', upload_to='profile_pics') views.py from django.http import HttpResponse from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth.models import User from django.contrib import messages from Profile.models import UploadImage from Profile.forms import UploadImageForm def profile(request): if request.method == 'POST': form = UploadImageForm(request.POST, request.FILES, instance=request.user.profile) if form.is_valid(): form.save() return HttpResponse('uploaded') else: form = UploadImageForm(instance=request.user.profile) username = request.user.username first_name = request.user.first_name last_name = request.user.last_name email = request.user.email userinfo = { 'username': username, 'first_name': first_name, 'last_name': last_name, 'email': email, 'form': form, } return render(request, 'profile.html', userinfo) I wanted a image to be uploaded by a users of their profile. I have created a Model for uploading picture and images were getting uploaded but the other fields which recognizes that this uploaded picture of this user are empty in the database also after changing some … -
Django comment form not submitting data [ERROR: function' object has no attribute 'objects]
I have a comment form on a post page for submitting user comment. I keep getting this error: 'function' object has no attribute 'objects' And the trace-back is highlighting this in my views: comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id) Most answers on SO refer to identical model & function names but that is not my case. This is my model: class Comment(models.Model): opinion = models.CharField(max_length=2200, verbose_name='Comment', null=False) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.comment class Meta: verbose_name_plural = 'Comments' My view @login_required(login_url='Login') def AddComment(request, id): post = Post.objects.filter(id=id) user = User.objects.get(username=request.user) if request.method == "POST": usercomment = request.POST['comment'] comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id) comment_obj.save() messages.success(request, '✅ Your Comment Was Created Successfully!') return redirect('Home') else: messages.error(request, "⚠️ Your Comment Wasn't Created!") return redirect('Home') And my form: <form method="POST" action="{% url 'AddComment' post.id %}"> {% csrf_token %} <div class="d-flex flex-row add-comment-section mt-4 mb-4"> <img class="img-fluid img-responsive rounded-circle mr-2" src="{{ user.profile.profile_image.url }}" width="38"> <textarea class="form-control mr-3" rows="1" name="comment" placeholder="Your Comment" required></textarea> <button class="btn btn-primary btn-lg" type="submit">Comment</button> </div> </form> And lastly my URL: urlpatterns = [ path('post/<int:id>/comment', views.AddComment, name="AddComment"), ]