Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can't get form to load in browser 404
I've got my LAMP setup with Ubuntu and MariaDB. The Django code managed to create some tables for me in the database but I just get 404 when I try to load my form in my browser. This is my first Django app. Maybe my urls.py is wrong. Maybe it's my settings.py. I've trying all sorts of things so my code has probably got a bit mangled. From TEMPLATES in settings.py I've hardcoded the path to my .html I've experimented with this a lot. 'DIRS': [ '/opt/vcm_project/vcm/templates/vcm' ], urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('create_unit', views.create_unit, name='create_unit'), ] models.py from django.db import models # Create your models here. class Unit(models.Model): unit_code = models.CharField(max_length=15) unit_name = models.CharField(max_length=255) unit_sector = models.CharField(max_length=255) unit_application = models.TextField(max_length=65535) unit_url = models.URLField(max_length=255) superseded_equivalent = models.CharField(max_length=15) def __str__(self): return self.unit_name class Element(models.Model): element_number = models.CharField(max_length=100) element_name = models.CharField(max_length=255) def __str__(self): return self.element_name forms.py from django import forms from .models import Unit class UnitForm(forms.ModelForm): class Meta: model = Unit fields = ('unit_code', 'unit_name', 'unit_sector', 'unit_application', 'unit_url', 'superseded_equivalent') widgets = { 'unit_code': forms.CharField(label='Unit code', max_length=15) 'unit_name': forms.CharField(label='Unit name', max_length=255) 'unit_sector': forms.CharField(label='Unit sector', max_length=255) 'unit_application': forms.CharField(label='Unit application', max_length=65535) 'unit_url': forms.URLField(label='Unit URL', max_length=255) … -
Django: Override 404 template in some views
I have a custom 404 template for my whole django application but I would like to show a different one for specific views. Is there a way to overrride the 404 template at runtime for one specific view? -
Email sending through Gmail is not working in Django. Gmail less secure apps disabled
From May 30 2022 onwards Gmail removed Less Secure apps access in gmail. Is there any alternative email provider we can use or is there any solution for it? EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 if request.method == "POST": name = request.POST['form_name'] email = request.POST['form_email'] subject = request.POST['form_subject'] message = request.POST['form_message'] send_mail(subject,message,email,['mail@gmail.com'] ) return render(request, 'pages/contact.html', {'name': name}) else: return render(request, 'pages/contact.html', {}) Need help, Thanks in advance. -
Prevent User from creating instance for other users
I have 4 models each related to each other with ForeignKey. class User(models.Model): name = models.CharField() class Business(models.Model): name = models.CharField() //business name created_by = models.ForeignKey(User,related_name=businesses,on_del=models.CASCADE) class ProdCategory(models.Model): business = models.ForeignKey(Business,related_name=categories,on_del=models.CASCADE) name = models.CharField() class Product(models.Model): category = models.ForeignKey(ProdCategory,related_name=products,on_del=models.CASCADE) name = models.ForeignKey() price = models.DecimalField() Now If I try to get all the Products of the current authenticated user I get the Correct List of products (that coming from the same User>Business>ProdCategory>Product) But if I try to create a Product with authenticated user, I can create a Product with providing the id of ProdCategory(already created by different users) (User of Business>ProdCategory) != self.request.user In Short I can create product for other users. Which is not what I want. I want to prevent the current user from creating products if ProdCategory id provided is of different users. It should return error. User must provide the id of ProdCategory that was created by the same user. Serializer classes are defined with all fields using ModelSerializer. Here goes the View for creating and listing products: class ProductListCreateView(generics.ListCreateAPIView): serializer_class = ProductListCreateSerializer def get_queryset(self): return Product.objects.filter(category__business__created_by=self.request.user) -
Django How to Select One Foriegn Key Among Multiple Foriegn Keys
I have two models know i created a third one in which i want to link any one between these two forign keys but not both of them and i want to show both of them while linking then we choose one of them -
Must supply api_key with django app deployed on heroku
hello guys i've got a django app, and i'm using cloudinary to save images, on my localhost it working perfectly but once i deployed to heroku i keep getting this error message Must supply api_key and ive added the api_key to my config list -
Running a django project with documentation based in linux on windows
I want to run this project https://github.com/sajib1066/django-event-management in windows but its documentation is for linux. Please simplify the instructions for windows because I'm having trouble in setting this up. Especially since the source command is not in powershell. -
Object of type RefreshToken is not JSON serializable
I would like to trigger user_logged_in after a user is authenticated through rest_framework_simplejwt This is the code I have written: class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], "password": attrs["password"], } try: authenticate_kwargs["request"] = self.context["request"] except KeyError: pass user = authenticate(**authenticate_kwargs) user_logged_in.send(sender=user.__class__, request=self.context['request'], user=user) if not api_settings.USER_AUTHENTICATION_RULE(user): raise exceptions.AuthenticationFailed( self.error_messages["no_active_account"], "no_active_account", ) return { self.get_token(cls, user) } @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.profile.country token['city'] = user.profile.city token['bio'] = user.profile.bio token['photo'] = json.dumps(str(user.profile.profile_pic)) return token When I try to authenticate a user I get the error: Object of type RefreshToken is not JSON serializable -
Django 4.0 getting many to many field objects in List View
I'm really new to Django and have been stuck....I have a book model and a genre model that have a many to many relationship. How would I go about getting all the books for a specific genre in a list view. I'm assuming its faster to get a Genre object and get all the books from it using a query such as "genre.objects.book_set.all" rather than going through all books and seeing if they have the specified genre. However I'm not sure how I would do that in a ListView? I wanna take the genre name from the url and then use that to get the genre object. here is what I have URL: path('genre/<string:name>', GenreListView.as_view(), name='book-genre'), Models: class Genre(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=150, unique=True) description = models.TextField() user_count = models.IntegerField() pages = models.IntegerField() genres = models.ManyToManyField(Genre) image = models.ImageField(default='book_imgs/default.jpg', upload_to='book_imgs') def __str__(self): return self.name View? class GenreListView(ListView): model = Genre def get_queryset(self): Not sure what to put here.... return Any help is appreciated, thanks. -
Vue Js and Django get fields from ForeignKey Objects
I am using Django Rest Framework with Vue JS and currently unable to get the foreignkey fields from the actual model of the api. I want to be able to get the store name of a particular product. Whenever I try to call [[ product.store.name ]] in my vue template it returns nothing. Also my href does not return the slug of a store. This could be an easy fix, but I am hopeful to get a solution. Below is my code, thanks. models.py class Store(models.Model): owner = models.ForeignKey("account.Profile", null=True, on_delete=models.SET_NULL) category = models.ForeignKey("store.Category", null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=30, unique=True) slug = AutoSlugField(populate_from='name', unique=True, editable=True) description = models.CharField(max_length=255, blank=True) def __str__(self): return str(self.id) class Product(models.Model): store = models.ForeignKey("store.Store", null=True, on_delete=models.SET_NULL, related_name='product_store') category = models.ForeignKey("store.Category", related_name='product_category', on_delete=models.CASCADE) sub_category = models.ForeignKey("store.SubCategory", related_name='product_sub_category', on_delete=models.SET_NULL, blank=True, null=True) created_by = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='product_creator') title = models.CharField(max_length=255) description = models.TextField(blank=True) slug = AutoSlugField(populate_from='title', unique=True) price = models.DecimalField(max_digits=10, decimal_places=0) serializer.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' views.py class ProductListAPIView(generics.ListAPIView): pagination_class = MyCustomPagination queryset = Product.objects.all().order_by('-date_created') # queryset = Product.objects.all() serializer_class = ProductSerializer products.js <script> new Vue({ el: "#blog", delimiters: ['[[', ']]'], data() { return { products: [], currentPage: 1, hasNext: true, loading: true, … -
Django ManyToMany MultipleChoice Field Edit Values Not Getting Checked
trying to show already selected items from Django many-to-many relationship in multiple choice field, but selected values aren't checked. this is what i've tried so far // models.py class Person(models.Model): name = models.CharField(max_length = 100, help_text = _('name required! maximum 100 characters')) class Team(models.Model): name = models.CharField(max_length = 100, help_text = _('name required! maximum 100 characters')) members = models.ManyToManyField(Member, related_name = 'teams') // forms.py class TeamForm(forms.ModelForm): teams = forms.MultipleChoiceField(choices = Team.objects.all(), widget = forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super(TeamForm, self).__init__(*args, **kwargs) if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['teams'] = [t for t in kwargs['instance'].teams.all()] // views.py class PersonEditView(View): team_form = TeamForm template_name = 'persons/edit.html' def get(self, request, person_id): """ """ person = get_object_or_404(Person, pk = person_id) return render(request, self.template_name, { 'team_form': self.team_form(instance = member, initial = {'teams': person.teams.all()}), }) // edit.html template <div class=""> <p class="">Team Information</p> {% for team in team_form.teams.field.choices %} <div class=""> <input id="{{ team.id }}" type="checkbox" value="{{ team.id }}" class=""> <label for="{{ team.id }}" class="">{{ team.name|title }}</label> </div> {% endfor %} </div> how do i get to show selected teams checked in the list of teams when editing the details of a Person? -
Django - Is it possible to prefetching multiple filters for queryset?
I know you can prefetch a single filtered queryset E.g. Parent.objects.all() .prefetch_related( Prefetch("child_set", queryset=Child.objects.filter(type="A") ) That way running obj.child_set.all().count() will return the count of related A Childs without running another query. But what if I wanted to have the B count too? So the following would take 2 queries - can I somehow prefetch them both? return { "a_count": obj.log_set.filter(type="A").all().count(), "b_count": obj.log_set.filter(type="B").all().count(), } -
Set inital value on django many to many fields
I would like to start a form with a default value sent on a request, but it seems not to be working: views.py """ ADD A NEW FILE IN CLIENT DETAIL """ @login_required def new_file_detail(request, id): user = request.user client = get_object_or_404(ClientPerson, pk=id) form = FilesForm(request.POST or None, request.FILES or None, user=user, instance=client, initial={'person_client': client}) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('files_list') return render(request, 'file_form.html', {'form': form, 'client': client}) Expected: Result: -
Why does my ModelFormSet keeps updating the same record instead of creating a new one?
I have these Models, this is all part of an app that registers events which have images through an ImageAlbum: class EventAlbum(models.Model): uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='eventos') def get_main_image(self): return self.images.get(main=True) class EventImage(models.Model): uuid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) image = models.FileField('imagen', upload_to=upload_path) main = models.BooleanField('principal', default=False) album = models.ForeignKey(EventAlbum, related_name = 'images', on_delete=models.CASCADE) And this FormSet for the Images: class BaseImageFormSet(BaseModelFormSet): def clean(self): """Checks that there is only one main image""" if any(self.errors): return boolean_arr = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue main_data = form.cleaned_data.get('main') main = main_data if main_data is not None else False if sum(boolean_arr) > 1: raise ValidationError('There can only be one main image.') boolean_arr.append(main) Here is in my Views: class NewEventView(BaseView): def get(self, request, *args): ImageFormSet = modelformset_factory( EventImage, fields=('image', 'main'), extra=5, max_num=5, formset= BaseImageFormSet) image_formset = ImageFormSet(prefix='images') context = {'forms': {'image_formset': image_formset, } return render(request, "events/events_add.html", context) def post(self, request): new_album = EventAlbum(event=new_event) ImageFormSet = modelformset_factory( EventImage, fields=('image', 'main'), extra=5, max_num=5, formset= BaseImageFormSet) image_formset = ImageFormSet(request.POST, request.FILES, prefix='images') if image_formset.is_valid(): new_album.save() images = image_formset.save(commit = False) for image in images: image.album = new_album image.save() image_formset.save() return HttpResponse('Ok', content_type='text') else: return Response((image_formset.errors, image_formset.non_form_errors()), … -
SES email being consistently hacked
I'm using Amazon SES email from the django-ses module. I have two SES-verified addresses; SES is restricted to sending only to those addresses. There's a DKIM string on my domain's DNS configuration. SES is accessed using django-ses from a contact form on my website that's protected by Recaptcha. Recently I've begun getting spam sent to those verified addresses coming from SES. Messages in Russian, messages containing website links, messages starting with "Hey guys...". I get about one per day. There are many questions on the net about SES emails going to the spam directory. That is NOT the issue here. The emails are received by my InBox; they are just bogus, hacked emails. I changed the SES API key and Secret key, to no avail. Where do I look next? (I don't have AWS Support, and find nothing in their Knowledge Base.) -
How to provide initial data to ForeignKey in ModelFormSet?
So I have this thing. These are the relationships of my models To define an event you have a Place, a QR Link and an ImageAlbum which have up to five Images. An event may or may not have a Place An event MUST have the main image which is marked by the main attr in the Image Form. All the forms are in the same page, they all are processed with a single Submit Now my troubles begin and end in the Forms Department, i have several Model Forms: #FORMS FILE class EventForm(ModelForm): date_time_start = forms.DateTimeField(input_formats=["%Y-%m-%d"], required=True, widget=forms.DateTimeInput(format="%Y-%m-%d", attrs={"id": "cal_start", "placeholder": "yyyy-mm-dd"})) has_place = forms.BooleanField() class Meta: model = Event fields = ['title', 'subtitle', 'phrase', 'date_time_start', 'prices', 'has_place'] class BaseImageFormSet(BaseModelFormSet): def clean_main(self): """Checks that there is only one main image""" if any(self.errors): return boolean_arr = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue main_data = form.cleaned_data.get('main') main = main_data if main_data is not None else False if sum(boolean_arr) > 1: raise ValidationError('There can only be one main image.') boolean_arr.append(main) class PlaceForm(ModelForm): class Meta: model = EventPlace exclude = ['uuid', 'event'] class QRForm(ModelForm): class Meta: model = EventQR exclude = ['uuid', 'event'] My headache is with the Images, … -
importing models into commands file causing Error module not found django
I'm trying to import my app's models into my update.py located inside website/management/commands knowing that website is my application, the problem that i get is that there is no module named 'website' even that I've mentioned it in my Installed_APPS in my settings.py: this is my update.py file : from django.core.management.base import BaseCommand import pandas as pd #from website.models import Product from website.models import Main_data class Command(BaseCommand): help='import booms' def add_arguments(self, parser): pass def handle(self,*args,**options): df=pd.read_excel('main.xlsx',engine='openpyxl') for P_N,P_P,P_L,P_I,P_Logo in zip(df.Product_Name,df.price,df.Link,df.Image,df.Logo): models=Data_Main(Product_Name=P_N,Product_Price=P_P,Product_Link=P_L,Product_Image=P_I,Product_Logo=P_Logo) models.save() this is the error that i get : Traceback (most recent call last): File "C:\Users\dell\Desktop\tam\website\management\commands\update.py", line 4, in <module> from website.models import Main_data ModuleNotFoundError: No module named 'website' this is my INSTALLED_APPS section located in my settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ] -
The file is downloading in local but not in production server in Django Rest framework?
I have a simple API that downloads a file in the system. It works perfectly in the local server, but when I deploy the same code to production, it gives me a 500 server error. If I try with another id that doesn't exist, it will say the object is not found. My code is as follows. def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.request.query_params.get("download") == "file": return [] return [permission() for permission in self.permission_classes] def get(self, request, *args, **kwargs): if request.query_params.get("download") == "file": return self.download_file(request) /....other codes........./ def download_file(self, request, *args, **kwargs): instance = self.get_object() file_handle = instance.file.path document = open(file_handle, "rb") response = HttpResponse(FileWrapper(document), content_type="") response["Content-Disposition"] = ( 'attachment; filename="%s"' % instance.file_name ) return response My endpoint URL is this: {{prod}}api/v1/example/notes/12/?download=file When I call this api, putting local in place of prod, it works and I get a file downloaded, but not in production. Is it something to do with file being closed before getting a response?? -
Django complex query with a many to many field
Let's explain the problem. I am trying to filter out all Person that have certain attributes. These are my models: class Person(models.Model): community = models.ForeignKey( Community, on_delete=models.CASCADE, related_name="people" ) class Attribute(models.Model): community = models.ForeignKey( Community, on_delete=models.CASCADE, related_name="attributes" ) name = models.CharField(max_length=50) value = models.CharField(max_length=100) class Trait(models.Model): person = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="person_attributes" ) attribute = models.ForeignKey( Attribute, on_delete=models.CASCADE, related_name="traits" ) A person could have the following attributes: Attribute(name='head', value='big') Attribute(name='head', value='small') Attribute(name='head', value='medium') Attribute(name='hands', value='white') Attribute(name='hands', value='red') #... These attributes are linked to Person through the Trait entity. Now, I have the following dict, witch I use to dynamically build the query: { "head": ["small", "medium"], "hands": ["white", "red"], } I want to filter out all the Person that have the attribute "head" with the value "small" or "medium" and the "hands" "white" or "red" This is what I have done so far, but it doesn't works: # value is the dict like the one explained above from which # I will obtain the elements for filtering def routine(self, value): query = Q() for attr, traits in value.items(): if len(traits) > 0: query &= Q( Q(person_attributes__attribute__name=attr) & Q(person_attributes__attribute__value__in=traits) ) return Person.objects.filter(query) -
how to make use of the file field in django
what else do I need to add to that "file = models.FileField()" this is what I have done but am still not getting any results, why that? class Course(models.Model): TOPIC_CHOICES = ( ("History", "History"), ("Chemistry", "Chemistry"), ("Computer", "Computer") ) lecturer = models.ForeignKey(Lecturer, on_delete=models.CASCADE) category = models.CharField(choices=TOPIC_CHOICES, max_length=100) topic = models.CharField(max_length=250) file = models.FileField() date_created = models.DateTimeField(default=datetime.now) def __str__(self): return f"{self.lecturer}: {self.topic}" -
Django category dosent show up
Am making a django blog and i got problems with it displaying the posts when they are in categories. I got them to work on category_list.html to show the categories listed. But when you click in on a category you should be able to see the blog posts in that category from the categories.html I got no idea why the category posts dosent show up when you enter a category. anyone got any idea what the problem can be? I used {% for cats in cat_menu_list %} in the categories template to display it and ithink the code: def CategoryView(request, cats): cat_menu_list = Post.objects.filter( category=cats.replace( '-', ' ')).order_by('-id') paginator = Paginator(cat_menu_list, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'categories.html', {'cats': cats.replace('-', ' ').title(), 'cat_menu_list': cat_menu_list, 'page_obj': page_obj}) newsapp views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView) from .models import Post, Category, Comment from .forms import PostForm, EditForm, CommentForm from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect from django.core.paginator import Paginator def LikeView(request, pk): post = get_object_or_404(Post, id=pk) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('article-detail', args=[str(pk)])) class HomeView(ListView): model = Post template_name … -
How to send multiple email invitations with django-allauth and django-invitations
I installed django-invitations to use it together with django-allauth, but it doesn't let me send several mails at the same time, which is inefficient for the correct functioning of the app. Maybe I installed something wrong. I only wrote in setting.py this: ACCEPT_INVITE_AFTER_SIGNUP = os.getenv('ACCEPT_INVITE_AFTER_SIGNUP', True) #I think allow json invites is for multiple emails, but doesn't work INVITATIONS_ALLOW_JSON_INVITES = True INVITATIONS_LOGIN_REDIRECT = os.getenv('INVITATIONS_LOGIN_REDIRECT', '/') ACCOUNT_ADAPTER = 'invitations.models.InvitationsAdapter' Or maybe exists another app who send invitations with allauth, if anyone have any advices please comment, thanks. -
creating django proejcts gets error ValueError: No closing quotation?
I want to create django project.The first thing which I did is install virtualenv for this; after run the following codes I get this error every time.And Pipfile.lock file doesn't create pipenv install virtualenv $ pipenv install virtualenv Creating a virtualenv for this project... Pipfile: C:\Users\Muhammed's\Desktop\django\kkk\Pipfile Using C:/Users/Muhammed's/AppData/Local/Programs/Python/Python39/python.exe (3.9.6) to create virtualenv... [ ] Creating virtual environment...created virtual environment CPython3.9.6.final.0-64 in 1130ms creator CPython3Windows(dest=C:\Users\Muhammed's\.virtualenvs\kkk-fuKJ3HTM, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\Muhammed's\AppData\Local\pypa\virtualenv) added seed packages: pip==22.0.4, setuptools==62.1.0, wheel==0.37.1 activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator [= ] Successfully created virtual environment! Virtualenv location: C:\Users\Muhammed's\.virtualenvs\kkk-fuKJ3HTM Creating a Pipfile for this project... Installing virtualenv... Adding virtualenv to Pipfile's [packages]... Installation Succeeded Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Locking...Building requirements... Resolving dependencies... Locking Failed! Traceback (most recent call last): File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 764, in <module> main() File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 758, in main _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write, File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 741, in _main resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev) File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 702, in resolve_packages results, resolver = resolve( File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 684, in resolve return resolve_deps( File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1397, in resolve_deps results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1110, in actually_resolve_deps resolver.resolve() File "c:\users\muhammed's\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line … -
cant load wsgi_mod on apache server centOS
im using httpd (apache) for rocky linux to develop a django application. I am currently stuck in this problem so I dont get why dont work. Does anybody knows? -
Django Class based view comment section
Blessings, I have a page where DetailView is is being displayed and I would like to add an option to comment on the same page without redirecting to /add-comment url I've tried everything from this Tutorial and the comments still do not work. (comments wont show or post upon submitting) models.py class Comment(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE, default=None) email = models.EmailField(max_length=100) content = models.TextField() post = models.ForeignKey(Movie, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__(self): return 'Comment by {}'.format(self.name) views.py class MovieDetail(DetailView): model = Movie def render_to_response(self, *args, **kwargs): self.object.refresh_from_db() self.object.views_count += 1 self.object.save() return super().render_to_response(*args, **kwargs) def get_context_data(self, **kwargs): context = super(MovieDetail, self).get_context_data(**kwargs) context['links'] = MovieLink.objects.filter(movie=self.get_object()) context['related_movies'] = Movie.objects.filter(category=self.get_object().category) return context def post(self, request, *args, **kwargs): form = CommentForm(request.POST) self.object = self.get_object() context = super().get_context_data(**kwargs) post = Movie.objects.filter(slug=self.kwargs['slug'])[0] comments = post.comment_set.all() context['post'] = post context['comments'] = comments context['form'] = form if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] content = form.cleaned_data['content'] comment = Comment.objects.create( name=name, email=email, content=content, post=post ) form = CommentForm() context['form'] = form return self.render_to_response(context=context) return self.render_to_response(context=context)