Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can an array of object be posted using Django DRF if this objects contain a file and other data?
I want to post an array of objects via the Django DRF. The array comes from my React JS frontend and contains a file and other data: [{"image":"file object", "title_picture":"false"}, {"image":"file object", "title_picture":"true"},{"image":"file object", "title_picture":"false"}} I get the image via a FileFild and the title_picture via a CharField, with the code below (following this approach) I can post a image list, but I lose the title_picture i.e., i get something like that [{"image":"file object",}, {"image":"file object",}, {"image":"file object"}] ###Model### class Photo(models.Model): image = models.FileField(upload_to='audio_stories/') title_picture = models.CharField(max_length=100, null=True, default='some_value') ###Serializer### class FileListSerializer (serializers.Serializer): image = serializers.ListField( child=serializers.FileField( max_length=1000, allow_empty_file=False, ) ) def create(self, validated_data): image=validated_data.pop('image') for img in image: photo=Photo.objects.create(image=img) return photo ###View### class PhotoViewSet(viewsets.ModelViewSet): serializer_class = FileListSerializer parser_classes = (MultiPartParser, FormParser,) http_method_names = ['post', 'head'] queryset=Photo.objects.all() Basically my question is how to post an array (list) of objects if these objects contain a file and some other data. -
get value from POST request in Django
I want to get the value of the key 'result' but every time I'm trying to get it it becomes empty if request.method == 'POST': result = request.POST after printing the result as you can see there is something there but when I'm trying to print: request.POST.get('result') or request.POST['result'] I'm getting an empty string -
Append "Teacher" to "Student" Profile
I have the following model setup: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class StudentProfile(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) teacher = models.ForeignKey('TeacherProfile', on_delete=models.SET_NULL, blank=True, null=True) class TeacherProfile(models.Model): teacher = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) In my view, I want the teacher to append herself as the student's teacher in the studentprofile. This is what I have thus far: def teach_student(request, student_id): student = get_object_or_404(Student, student_id=student_id) StudentProfile.objects.create(teacher=request.user.teacher, student=student) return redirect('account:path_to_students_without_teacher') PROBLEM: I'm getting an error: Cannot assign "<Student: Student One (@student)>": "Student.student" must be a "User" instance. QUESTION: Any suggestions on how to allow a teacher to append herself as the student's teacher? -
Posting 'dictionary-style' items in a Django form
I want to submit information for multiple items through a form, where I need to be able to associate keys and value. The information needs to be posted in this particular way but I'm not sure how to best label my fields and retrieve the data. Here is an example of data I want to submit through fields: Product 1: 100 Product 12: 492 Product 1049: 235 The content on the page is generated dynamically and I have no easy way to know which products will appear on this page. So ideally I can simply retrieve the information from the POST and figure out BOTH which product ID is being sent and what the price is. Coming from PHP, this could be easily done by labeling inputs as such: Product 1: <input name="price[1]" value="100"> Product 12: <input name="price[12]" value="492"> Product 1049: <input name="price[1049]" value="235"> However, when I try this in Django I have great difficulty retrieving the values. I found this thread, and there doesn't seem to be a good alternative. However, I don't need to use the bracket system. I can call the inputs whatever I like, but I'm simply trying to find out what a recommended approach is … -
Django OneToOne relationship - how to serialize it?
Simple example student and employee class, I want to serialize it like below and it should be OneToOne relationship: { "college": "string", "year": "string", "is_with_college": true, "employee": { "full_name": "string", "email_id": "user@example.com", "mobile_no": "string", "is_job_ready": true, "type": "string", "location_preference": "string" } } models: class Employee(models.Model): full_name=models.CharField(max_length=100) email_id=models.EmailField(max_length=100) mobile_no=models.CharField(max_length=11) is_job_ready=models.BooleanField(False) type=models.CharField(max_length=20) location_preference=models.CharField(max_length=20) class Student(models.Model): college=models.CharField(max_length=100) year=models.CharField(max_length=20) is_with_college=models.BooleanField() employee=models.OneToOneField(Employee, on_delete=models.CASCADE) serializers: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('full_name', 'email_id', 'mobile_no', 'is_job_ready', 'type', 'location_preference') class StudentSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(many=False) class Meta: model = Student fields = ('college', 'year', 'is_with_college', 'employee') def create(self, validated_data): employee_data = validated_data.pop('employee') if employee_data: student = Student.objects.create(**validated_data) Employee.objects.create(student=student, **employee_data) return student views: class EmployeeViewSet(viewsets.ModelViewSet): serializer_class = EmployeeSerializer queryset = Employee.objects.all() class StudentViewSet(viewsets.ModelViewSet): serializer_class = StudentSerializer queryset = Student.objects.all() I'm not sure what I'm doing wrong. I'm trying to change a few things, still have different errors. I'm sure that it's simple and I'm missing something.. At this moment I have: NOT NULL constraint failed: rest_student.employee_id -
How do I get an item id via a modal where the link that triggers it is within a for loop in Django
This is an online shop where the page that lists products has a small button that triggers a modal that display detailed info about the specific product. For me to be able to display this info I need to get this specific id back in the views so that I can fetch this specific product. Below is the html code {% if products %} {% for item in products %} <!-- product--> <div class="col-xl-3 col-lg-4 col-sm-6"> <div class="product"> <div class="product-image"> <div class="ribbon ribbon-info">Fresh</div><img class="img-fluid" src="{{item.image.url}}" alt="product"/> <div class="product-hover-overlay"><a class="product-hover-overlay-link" href="{{item.get_absolute_url}}"></a> <div class="product-hover-overlay-buttons"><a class="btn btn-outline-dark btn-product-left" href="#"><i class="fa fa-shopping-cart"></i></a> <a class="btn btn-dark btn-buy" href="{{item.get_absolute_url}}"><i class="fa-search fa"></i></a><a class="btn btn-outline-dark btn-product-right" href="{% url 'shop:modal_product_list' item.id %}" data-toggle="modal" data-target="#exampleModal"><i class="fa fa-expand-arrows-alt"></i></a> </div> </div> </div> <div class="py-2"> <p class="text-muted text-sm mb-1">{{item.products.sub_category}}</p> <h3 class="h6 text-uppercase mb-1"><a class="text-dark" href="{{item.get_absolute_url}}">{{item.name}}</a></h3><span class="text-muted">KSH {{item.discount_price}}</span> </div> </div> </div> <!-- /product--> {% endfor %} {% else %} <p> No products at the moment. Please check back later</p> {% endif %} I was hoping this href="{% url 'shop:modal_product_list' item.id %}" will come through...my view looks like this def product_list(request, product_id=None,category_name=None,category_slug=None): def get_category(name): return Category.objects.filter(name=name) products = PRODUCTS category = None if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) category_name = None if … -
How can I update the email address using the confirmation code in Django?
I use all the functionalities of dj-rest-auth to register, log in, confirm the email address, change the password, reset the password and many more. Unfortunately, the library does not support changing the email address. I would like the authenticated user to first enter the account password and the new email address. After the successful process of authentication, I would like to send the user a specially generated confirmation code. Only when he enters it, the old email address will be changed to the new one. As far as I know, there is no such functionality in dj-rest-auth. Unfortunately, I also have not found any current solutions or libraries for this purpose anywhere. Did anyone have such a problem and could share his solution here? Thank you in advance. -
Django on Apache2 - Restart Server when making changes?
right now I'm trying - for the first time - to deploy a Django-Application on a Apache2 with mod_wsgi and it's still not working the way I wish it would. Anyway, I'm arguing with my Admin who says I don't have to restart the server after making changes to my python code, only if there are changes to the .conf-files. The tutorials online are also not that useful for this specific problem! Some say "A", some say "B" and some don't mention this topic at all. Can someone who already deployed this way answer to my problem? Thanks and a great weekend! -
Problem with Celery task in Django, stopped for unknown reason
I made simple script using Django and Celery, which makes queries in Django database compares to dates with current date and send email. I use Heroku, and Redislab server for Resis server. I used Celery beam and Celry worker to check every 1 second. I made simple task which send emails from Gmail and the settings.py in Django. All fine. When I deployed to Heroku it was working for few minutes, then stoped. What could be the possible reasons? Is this the right approach? What I think is: probably Gmail or the receiver mail told that that's flood. Or... Please help and thank you in advance. -
The submit button is not functioning in html, even though i gave onclick element
$("#btn1").click(function(){ $(".btn1").show(); $(".btn1").attr("disabled",true); }); }); function getanswer() { document.getElementById(useranswer).innerHTML = ""; var e = document.getElementsByTagName('input'); for(i = 0; i<= e.length ; i++) { if(e[i].type == 'radio') { if(e[i].checked) { document.getElementById(useranswer).innerHTML += "Q" + e[i].name + "Answer you selected is :" + e[i].value+ "<br/>"; } } } } This is script code for the below html line <tr> <td><label id="correctanswer" class="ans" value="{{Result.correctanswer}}" style="display: none; color:green;"><br>{{Result.correctanswer}}<br></label></td> </tr> And the submit button is not working if i click on that. <input type="submit" value="submitanswer" id="btn1" onclick = " getanswer();" > Can anyone help me out with this, what is problem going on. Whenever the submitanswer is clicked it is not functioning. What i expected is : it should jump to getanswer function and display the following propertys. Please help me with this. And i am working with Django framework. I am using this function to validate the user answers. Thank you. -
Django makemigrations ignoring blank=False or null=False
from django.db import models # define a custom field class CustomCharField(models.CharField): def __init__(self, *args, **kwargs): print(kwargs) # test code defaults = {'null': True, 'blank': True} defaults.update(kwargs) super().__init__(*args, **defaults) # use custom field in a model class class FooModel(models.Model): bar_char = CustomCharField('bar char', null=False, blank=True) and run makemigrations # python3 manage.py makemigrations {'verbose_name': 'bar char', 'blank': True} # this is printed because of the 'test code'. I expected bar_char is non-nullable and blankable, but it is nullable and blankable in this case, null=False parameter is ignored. (if blank=False, it would be ignored.) In short, False set null or blank parameter is ignored. why is that happended? am I missing something? or is it Django's bug? -
How to proper test signals.py in Django?
I want to know that is my signal test was correct ? the test coverage with "django-nose" of signals.py still 0% This is my signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() This is my test.py class TestSignals(TestCase): def test_create_profile_signal_triggered(self): handler = MagicMock() signals.create_profile.send(handler, sender='test') form = UserCreationForm() form.cleaned_data={'username':'oatty111','email':'oatty@mail.com','password1':'test123', 'password2':'test123','first_name':'Michael','last_name':'Jordan'} form.save() signals.create_profile.send(sender='test',form_date=form) handler.assert_called_once_with(signal=signals.create_profile, form_data=form, sender='test') This is my forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2','first_name','last_name'] -
how can I render the column of excel file to template?
I have a model that has two objects. The first object contains Excel files and the second contains the name of the Excel file. I created a template that shows the names of Excel files. When the user clicks on the file name, I want to show him objects name and below it a special column of contents inside the Excel file. my model is: class charts(models.Model): excel= models.FileField(null=True, blank=True) name = models.CharField(max_length=40) model manager: def get_by_id(self, ch_id): qs = self.get_queryset().filter(id=ch_id) if qs.count() == 1: return qs.first() else: return None views.py for show detail: def chart_detail(request, *args, **kwargs): ch_id= kwargs['ch_id'] chare = charts.objects.get_chart(ch_id) if MineralSpectrum is None: raise Http404 context = { 'a': chare, } return render(request, 'chart_detail.html', context) chart_detail.html: {% block content%} <p>{{ i.name }}</p> <p> 'here I want to show the x columns of excel inside database related to i.name' </p> {% endblock%} this is an example for explain my problem. -
How to use a variable as name in a Django Form?
In a table, each row contains an ID number and a dropdown. I want the user to choose a value in each row's dropdown, and then submit all that and display it on the next page. On the next page I call request.POST.get() so each dropdown needs to have a unique HTML name. Currently I have the following which works for displaying the info: class Dropdown(forms.Form): def __init__(self, mylistTuples): super(Dropdown,self).__init__() self.fields['dropdown'] = forms.CharField(label="", widget=forms.Select(choices=mylistTuples)) dropdown = forms.CharField() I think I want something like the following, but I don't quite understand how the self.fields['name'] relates to the variable name. class Dropdown(forms.Form): def __init__(self, mylistTuples, my_id): super(Dropdown,self).__init__() self.fields['dropdown_'+my_id] = forms.CharField(label="", widget=forms.Select(choices=mylistTuples)) dropdown?? = forms.CharField() I also tried the following without success: class Dropdown(forms.Form): def __init__(self, mylistTuples, my_id): super(Dropdown,self).__init__() self.fields['dropdown_'+my_id] = forms.CharField(label="", widget=forms.Select(choices=mylistTuples)) self.my_id = my_id globals()['dropdown_'+self.my_id] = forms.CharField() In the next page's view, request.POST.items() will allow me to loop through my results. -
Issue while rendering view with Django 3.1.3 using render function that works fine with Django 2.2
#Code of Django View: check Output here!! def studiolist_page(request,*args,**kwargs): studiomaster={'studio_master_key':StudioMaster.objects.all()} studiolist_all=StudioDetails.objects.filter(studio_status=10) city_query=request.GET.get("cty") studio_type_query=request.GET.get("s_type") genre_query=request.GET.get("gnre") baseprice_query=request.GET.get("price") studiolist={'studio_list_key':studiolist_all} print(6) x=len(studiolist.get('studio_list_key')) if x==0: y='Sorry!! No Studios Available Here !!' else: y=str(x)+' Fresh Studios Served !!' messages.success(request,y) return render(request,'studiomaster/studiocard_list.html',studiolist,studiomaster) I also have tried changing the template to find if its an issue with html, but the result is same, So I assume that it might be something to do with the View handling itself. To my surprise this works fine in Django 2.2 but loads html code on the browser when being rendered so the template is being called but the loading has some abnormal behaviour . Any help here is greatly appreciated. -
Exception occurred processing WSGI script [Django + Apache2]
I'm getting some errors deploying a Django app with Apache2. One error I see in my logs says Exception occurred processing WSGI script I'm not sure if my permissions are right or if maybe I am confused about the difference between sites-available and sites-enabled Here's the full error log: [Sat Nov 14 04:51:24.181106 2020] [wsgi:error] [pid 407301:tid 140682895165184] [remote XXX.XX.XX.XXX:52895] mod_wsgi (pid=407301): Failed to exec Python script file '/srv/example/example/wsgi.py'. [Sat Nov 14 04:51:24.181150 2020] [wsgi:error] [pid 407301:tid 140682895165184] [remote XXX.XX.XX.XXX:52895] mod_wsgi (pid=407301): Exception occurred processing WSGI script '/srv/example/example/wsgi.py'. [Sat Nov 14 04:51:24.181178 2020] [wsgi:error] [pid 407301:tid 140682895165184] [remote XXX.XX.XX.XXX:52895] Traceback (most recent call last): [Sat Nov 14 04:51:24.181205 2020] [wsgi:error] [pid 407301:tid 140682895165184] [remote XXX.XX.XX.XXX:52895] File "/srv/example/example/wsgi.py", line 12, in <module> [Sat Nov 14 04:51:24.181246 2020] [wsgi:error] [pid 407301:tid 140682895165184] [remote XXX.XX.XX.XXX:52895] from django.core.wsgi import get_wsgi_application [Sat Nov 14 04:51:24.181270 2020] [wsgi:error] [pid 407301:tid 140682895165184] [remote XXX.XX.XX.XXX:52895] ImportError: No module named django.core.wsgi /etc/apache2/sites-enabled/example.conf <VirtualHost *:80> ErrorLog ${APACHE_LOG_DIR}/example-error.log CustomLog ${APACHE_LOG_DIR}/example-access.log combined WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess example processes=2 threads=25 python-path=/srv/example WSGIProcessGroup example WSGIScriptAlias / /srv/example/example/wsgi.py Alias /robots.txt /srv/example/static/robots.txt Alias /favicon.ico /srv/example/static/favicon.ico Alias /static/ /srv/example/static/ Alias /media/ /srv/example/media/ <Directory /srv/example/example> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /srv/example/static> Require all granted </Directory> <Directory … -
getting error while using model form in django
path('', include('farmingwave.urls')), File "F:\farm\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\Mohit\AppData\Local\Programs\Python\Python39\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 790, in exec_module File "", line 228, in call_with_frames_removed File "F:\farm\fwave\farmingwave\urls.py", line 3, in from . import views File "F:\farm\fwave\farmingwave\views.py", line 3, in from .forms import ContactForm File "F:\farm\fwave\farmingwave\forms.py", line 3, in from django.forms import contactForm ImportError: cannot import name 'contactForm' from 'django.forms' (F:\farm\lib\site-packages\django\forms_init.py) -
Tracking Recent Actions in Django Admin Panel to send notification
When there is a change in admin panel, the logs are automatically registered to django_admin_log table. I want to trigger an action to send a notification or trigger an action on such changes. so far I have tried (in <app_name>/admin.py) using the LogEntry provided by django @admin.register(LogEntry) class LogEntryAdmin(admin.ModelAdmin): date_hierarchy = 'action_time' list_filter = [ 'user', 'content_type', 'action_flag' ] search_fields = [ 'object_repr', 'change_message' ] list_display = [ 'action_time', 'user', 'content_type', 'action_flag', 'change_message' ] but this doesn't get executed on each action change. The logs that we see in Recent Actions tab on django admin panel, exact same thing is needed here. But I am not able to figure out how to trigger an action on such changes. One way to keep track of django_admin_log table but this will never be efficient since I have to go through the table every time. Any idea on how to achieve this. -
Django 3, request.POST didnt save when i filter the user with request.user
im trying to filter the user that only display the current user login. after im found the solution how to filter the user but didnt save to db forms.py class EnrollmentForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(EnrollmentForm, self).__init__(*args, **kwargs) self.fields['user'].queryset = User.objects.filter(username=user) class Meta: model = Enrolled fields = ['schedule', 'user'] views.py def StudentEnroll(request): if request.method == 'POST': form = EnrollmentForm(request.POST) if form.is_valid(): form.save() return redirect('student-schedule') else: form = EnrollmentForm(request.user) return render(request, 'main/student_enroll.html', {'form': form}) -
Validating Entered Data with custom constraints in Django Forms in __init__
In my project, the user is entering data in a settings page of the application and it should update the database with the user's settings preference. I read this answer by Alasdair and how using the __init__() will allow to access the user's details. I was wondering if it's possible to return data from __init__() so I can validate the entered data before calling the save() function in the view? This is what I tried (and did not work). I am open to going about this in a better approach so I appreciate all your suggestions! Forms.py class t_max_form(forms.ModelForm): side = None def __init__(self, *args, **kwargs): side = kwargs.pop('side', None) super(t_max_form, self).__init__(*args,**kwargs) if side == "ms": self.fields['hs_max_sessions'].widget.attrs.update({'class':'form-control', 'readonly':True}) self.fields['ms_max_sessions'].widget.attrs.update({'class':'form-control mb-3'}) elif side == "hs": self.fields['hs_max_sessions'].widget.attrs.update({'class':'form-control'}) self.fields['ms_max_sessions'].widget.attrs.update({'class':'form-control', 'readonly':True}) else: self.fields['hs_max_sessions'].widget.attrs.update({'class':'form-control'}) self.fields['ms_max_sessions'].widget.attrs.update({'class':'form-control'}) #Trying to validate the data here valid_session_count = settings.objects.first() if(side == "ms"): input_sessions = self.fields['ms_max_sessions'].widget.attrs['readonly'] if(input_sessions > valid_session_count.max_sessions): self.add_error("ms_max_sessions", "You have entered more than the limit set by the TC. Try again") elif(side == "hs"): input_sessions = self.cleaned_data['hs_max_sessions'] if(input_sessions > valid_session_count.max_sessions): self.add_error("hs_max_sessions", "You have entered more than the limit set by the TC. Try again") else: input_sessions = self.cleaned_data['ms_max_sessions'] + self.cleaned_data['hs_max_sessions'] if(input_sessions > valid_session_count.max_sessions): self.add_error("hs_max_sessions", "You have entered more than … -
Given an encrypted string in the database, can somebody help me crack this password?
I have uploaded an application on heroku following a course in udemy. The lesson asked me to download an example database uploaded by them and link it with my own application. The application has a sign in page which authenticates itself with auth_user in the database. However, the password is encrypted. as such, i am stuck at the sign in page. I cannot create a new account for the application or write columns into the database, and the author of the udemy course has been uncontactable thus far. Querying the database yielded the account information. However, the password has been encryted, and i have no way of decrypting it. Can anyone help me with this? the password is: pbkdf2_sha256$30000$GBQUIvjRTK1b$JACrwzhRoiSXovL1Sf2A7LiWjZgmUlvTz3thWBRxMfs= this is the account information -
django ORM: get all the fields of model with positive value in one field
I am trying to query all the objects in a model that have a positive value in one particular field. I have not been able to find anywhere whether there is a way to use greater than signs in django. I have tried doing by sorting the column that interests me and removing the 0 values in that column in order to the overcome the greater than. First it seems over complicated, and second it does not work. here is the query: count_orders = replenishment.objects.order_by(F('StockOnOrder')).desc().exclude('StockOnOrder' = 0) I also need to count the positive rows in this field and it does not work either as following: count_orders = replenishment.objects.order_by(F('StockOnOrder')).desc().exclude('StockOnOrder' = 0).count() I am wondering if by chance this is the proper way to do it, or if there is something more intuitive and simple. -
Getting data from related tables using Django ORM
Using the Django ORM, how does one access data from related tables without effectively making a separate call for each record (or redundantly denormalizing data to make it more easily accessible)? Say I have 3 Models: class Tournament(models.Model): name = models.CharField(max_length=250) active = models.BooleanField(null=True,default=1) class Team(models.Model): name = models.CharField(max_length=250) coach_name = models.CharField(max_length=250) active = models.BooleanField(null=True,default=1) class Player(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING ) number = models.PositiveIntegerField() age = models.PositiveIntegerField() active = models.BooleanField(null=True,default=1) Note that this Player model is important in the application as it's a major connection to most of the models - from registration to teams to stats to results to prizes. But this Player model doesn't actually contain the person's name as the model contains a user field which is the foreign key to a custom AUTH_USER_MODEL ('user') model which contains first/last name information. This allows the player to log in to the application and perform certain actions. In addition to these base models, say that since a player can play on different teams in different tournaments, I also have a connecting ManyToMany model: class PlayerToTeam(models.Model): player = models.ForeignKey( Player, on_delete=models.DO_NOTHING ) team = models.ForeignKey( Team, on_delete=models.DO_NOTHING ) tournament = models.ForeignKey( Tournament, on_delete=models.DO_NOTHING ) As an example of … -
Using Validators in Django not working properly
I have recently learning about Validators and how they work but I am trying to add a function to my blog project to raise an error when a bad word is used. I have a list of bad words in a txt and added the code to be in the models.py the problem is that nothing is blocked for some reason I am not sure of. Here is the models.py def validate_comment_text(text): with open("badwords.txt") as f: CENSORED_WORDS = f.readlines() words = set(re.sub("[^\w]", " ", text).split()) if any(censored_word in words for censored_word in CENSORED_WORDS): raise ValidationError(f"{censored_word} is censored!") class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) -
Updating and Deleting Comments for Posts in Django
I have added a Comment system to posts in a Blog Project and I am trying to add an option to update and delete the comments by the users. I am trying to use the same concept as creating a Post and building a Class Based Views for these comments, creating a commment is working fine and it is appearing correctly, the only obstacle I am facing is the slug, when a user clicks on update or delete it is showing an error Cannot resolve keyword 'slug' into the field. Choices are content, created, id, post, post_id, updated, user, user_id which makes sense since there is no Slug in the comment Model. My question is how do refer back to the same page post.slug in the template without getting this error Here is the models.py class Post(models.Model): slug = models.SlugField(blank=True, null=True, max_length=120) ------------------------------------------------------------ class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text]) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) Here is the views.py class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', …