Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTML - Python Connection
So I have a website that has a form. I want to be able to connect it to Python so that all the form inputs gets transferred to an SQL Database. I have no clue how to do it tho. I've heard that Flask is easier but I have no clue if Django is easier or harder. Any help would be appreciated. -
DRF xss protection - get user details with a POST request
I'm working on an application which is going to be using DRF for the API and Angular or React on the frontend. I'll be using cookies season authentication that will be protected against XSS by csrf token for the unsafe methods. I was wondering what is happening with the safe methods as GET in cases where I request a piece of really sensitive user information, for example, user details whit phone number or even a home address. As far as I understand HTTPS alone will not protect such information as the attack is performed on an application level rather than being intercepted which makes it human-readable. I can imagen many more cases where we want to defend safe methods, especially in user-driven applications. If an attacker gains access to our authentication cookie and performs a forged GET request to /api/v1/users/:id, which by default will not be protected by csrf token even if we decorate the view with csrf_protect(), he will be able to read the response unless I'm missing something. I went through some articles here and there but didn't find a definitive answer to this problem. My question - can we use POST request in such situations despite we … -
Display a field (or not) according to another field's value
I am working on a small project with Django. But my question is more javascript related. I have a view where I need to choose the destination of a product. Now the product can go to either an external destination or an internal one. What I want to do is to display the destination once I choose the destination type. So if I choose External Destination I want to display only the external destinations... I know this can only be done in JavaScript, but I don't know the last thing about it. -
How to use conditional on Django template?
Im working on my django project. The home page of my project is to show all of my post and category-based post on the bottom after the first part. But my code isnt working and i dont know why. Please help me #first part {% for post in blog_posts %} <div class="card d-inline-flex m-1" style="width: 18rem;"> <a href="{% url 'post-detail' post.pk %}" > <img class="card-img-top postimg" src="{{ post.post_img.url }}" alt="Card image cap"> </a> <h3>{{post.category}}</h3> <div class="card-body"> <h5 class="card-text text-center">{{ post.post_title }}</h5> <p class="card-text">{{post.post_content|truncatechars:75|safe }}</p> </div> </div> {% endfor %} #second part <h1> Opini </h1> {% for post in blog_posts %} {% if post.category == "Opini" %} #the word Opini is one of my post category <div class="card d-inline-flex m-1" style="width: 18rem;"> <a href="{% url 'post-detail' post.pk %}" > <img class="card-img-top postimg" src="{{ post.post_img.url }}" alt="Card image cap"> </a> <h3>{{post.category}}</h3> <div class="card-body"> <h5 class="card-text text-center">{{ post.post_title }}</h5> <p class="card-text">{{post.post_content|truncatechars:75|safe }}</p> </div> </div> {% endif %} {% endfor %} {% endfor %} My Models class Category(models.Model): name = models.CharField(max_length=100, unique=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name def get_absolute_url(self): return reverse('post_by_category', args=[self.name]) class Post(models.Model): post_title = models.CharField(max_length=50) post_img = models.ImageField(upload_to='postImage/') post_content = RichTextField(blank= True, null = True) category = models.ForeignKey(Category … -
Running the polls app under pythonanywhere
I would like to run the simple polls app from the django official tutorial under pythonanywhere. I went to the disk, downloaded the directory mysite that contains the following: db.sqlite3 manage.py mysite __init__.py urls.py wsgi.py polls __init__.py admin.py apps.py models.py tests.py urls.py views.py then I went to the pythonanywhere dashboard, clicked on "All Web apps", then on "Add a new web app", then I chose "manual configuration", "Python 3.8" and "Django", and finally I got a configuration window in which three pieces of information can be entered: "Source code", "Working directory" and "WSGI configuration file" and it contains a button "Reload xxx.pythonanywhere.com". I guess that I have to provide the right paths and then click the button to have the polls application activated and running under the xxx.pythonanywhere.com URL. But what are these paths? I have tried many combinations and always get only the default "Hello, World! This is the default welcome page for a PythonAnywhere hosted web application." In django tutorials it says one has to use manage.py to run the server, but this doesn't work under pythonanywhere. What do I have to do to get the polls app running under pythonanywhere? -
How run instascan on django local server? no https
I have a simple web page that i use to scan qr code in web page: {% extends 'myapp/base3.html' %} {% load staticfiles %} {% block content %} <html> <script type="text/javascript" src="{% static 'adapter.min.js' %}"></script> <script type="text/javascript" src="{% static 'vue.min.js' %}"></script> <script type="text/javascript" src="{% static 'instascan.min.js' %}"></script> <body> <div id="app"> <div class="row"> <div class="col-lg-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Scanner Badge</h3></div> </div> </div> <div class="col-lg-12"> <div class="preview-container"> <video id="preview"></video> </div> </div> <div class="preview-container"> <video id="preview"> </video> </div> <div class="panel panel-primary"> <section class="scans"> <ul v-if="scans.length === 0"> <li class="empty">QRCode in Camera</li> </ul> <table> <a v-for="scan in scans" :key="scan.date" :title="scan.content" :href="'{{ url }}' + scan.content"> <h1>SEND</h1> </a> </table> </section> </div> </body> <script type="text/javascript" src="{% static 'app.js' %}"></script> </html> {% endblock %} it work very well on local server using crome://flags trust unsecure and insert server ip address; but i need to load instascan on android tablet browser. There is a way to bypass certificate check and run instascan with no https server? Or, alternatively, is there any browser that allows you to load instascan without checking the certificates? -
Why is BaseDeleteView is throwing an Attribute error saying object has no attribute render_to_response?
I am trying to implement BaseDeleteview, but getting this erroe message -> 'DeletePostView' object has no attribute 'render_to_response', I did not use DeleteView mainly beacuse it expects a confirmation template and I am using bootraps's modal (like a pop up) for confirmation. I have found much similar question here -> BaseDeleteView throws AttributeError (render_to_response missing) class DeletePostView(SuccessMessageMixin, BaseDeleteView): model = Post context_object_name = 'remove_post_confirm_object' # template_name = "posts/delete_confirm_post.html" success_url = reverse_lazy('users:profile') success_message = 'Post has been deleted SuccessFully!' Error Tranceback: Traceback (most recent call last): File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/gaurav/Programming_Practice/DjangoProjects/Blog/blog-project/venv/lib/python3.8/site-packages/django/views/generic/detail.py", line 108, in get return self.render_to_response(context) Exception Type: AttributeError at /post/2020/10/10/wertyuio/remove Exception Value: 'DeletePostView' object has no attribute 'render_to_response' -
How follow toggle work in django and how to deal with exception such as RelatedObjectDoesNotExist?
Well I am trying to add follow toggle and right now that is showing me an error the error traceback is given below. I dont understand how can i get two user from detail view. first user is the one who is going to follow someone profile and the second user whose profile is going to be follow. Im and trying that thing with the following code. views.py class UserProfileDetailView(DetailView): model = UserProfile template_name = "profiles/userprofile_detail.html" def get_context_data(self,*args, **kwargs): context = super().get_context_data(*args,**kwargs) is_following = False if self.object.user in self.request.user.userprofile.follower.all(): is_following = True context["is_following"] = is_following return context urls.py urlpatterns = [ # path('user',UserProfileCreateView.as_view(template_name = 'profiles/userprofile.html'),name='home') # path('user/',userprofile,name = 'home'), path('user-profile/',UserProfileFollowToggle.as_view(),name = 'toggle'), path('<str:username>/',UserProfileDetailView.as_view(),name = 'detail'), ] userprofile_detail.html {% extends 'base.html' %} {% block content %} <p style="text-align: center;"><img src="{{ object.user.userprofile.avatar.url }}" width = "50%"></p> {{ request.user.userprofile.follower.all }}<br> {{object.user.userprofile }} {% if object.user in request.user.userprofile.follower.all %} Following {% endif %} <p>{% include 'profiles/snippets/follow_toggle.html' with username=user.username is_following=is_following %}</p> <h2>{{ object.username }}</h2> /{{is_following}} {% endblock content %} snippets/follow_toggle.html <form class='form' method='POST' action="{% url 'profiles:toggle'%}"> {% csrf_token %} <input type='hidden' name='username' value="{% if username %}{{ username }}{% else %}hello{% endif %}"> <button class='btn {% if is_following %}btn-warning{% else %}btn-primary{% endif %}'>{% if is_following %}Unfollow … -
TypeError: Abstract base class containing model fields not permitted for proxy model 'TokenProxy'. when trying to makemigrations in Django
I have created a custom user model to replace the username with an email and want to use it with Djoser and React. But when I try to make the migrations I get this error (more details below): TypeError: Abstract base class containing model fields not permitted for proxy model 'TokenProxy'. models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user def create_superuser(self, email, password, name, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') serializers.py from djoser.serializers import UserCreateSerializer, UserSerializer from django.contrib.auth import get_user_model User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('id', 'email', 'name', 'password') urls.py urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] I´m getting this error when I try to makemigrations: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked … -
Django get pk in decorator
I would like to know how I can get the pk of an object inside my decorator. views.py @count_view def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) decorators.py def count_view(function): def wrap(request, *args, **kwargs): pk = args print(pk) If I print args at the decorator it returns the pk of the object but as some kind of list: ('e42cbde4-787c-46a3-973f-7bd0e6ef0012',) instead of of a single string, which is what I want. -
Djnago - order_by mantomany using related names
I have following models class Model_1(models.Model): .. class Model_2(models.Model): many_items= models.ManyToManyField(Model_1, through='MyThroughModel', related_name='related_name_1') class Model_3(models.Model): one_item = models.OneToOneField(Model_2, related_name='relate_name_2', null=True, on_delete=models.CASCADE) rating = models.SmallIntegerField(_("Rating"), choices=SCORE_CHOICES) I want to order_records by the rating field in Model_3 I tried this myQryset = Model_1.objects.filter(...).order_by(...) ##This returns two records which is fine myQryset.order_by('relate_name_1__relate_name_2__rating').distinct() ## This returns two records but they are same(duplicates). I think I am doing something wrong but don't know what. Please help -
Save and Rounding the range in TimeField Formset in Views Django
I have following code to save and rounding the range of TimeField in Views Django: begin1 = datetime.datetime.strptime('01:00', '%H:%M').time() end1 = datetime.datetime.strptime('02:00', '%H:%M').time() begin2 = datetime.datetime.strptime('02:00', '%H:%M').time() end2 = datetime.datetime.strptime('03:00', '%H:%M').time() import datetime if formset.is_valid(): for item in formset: if formset.mytime > begin1 and formset.mytime < end1: # formset.mytime = item.cleaned_data['mytime'] formset.mytime = '01:00' if formset.mytime > begin2 and formset.mytime < end2: # formset.mytime = item.cleaned_data['mytime'] formset.mytime = '02:00' formset.save() So for example, if user input the mytime: 01:52 then rounding to the lowest hour and would save as 01:00. But it wouldn't save to the database. What's the wrong with above code? Thank in advanced for your help. -
Django counting hits using a decorator
I would like to count my object views using a decorator like so: def count_view(function): def wrap(request, *args): pk = args user = get_user_model().objects.get(pk=request.user.pk) hit_objects = Hit.objects.filter(viewer=user, object_id=pk) if hit_objects: return function(request) else: new_hit = Hit.objects.create(viewer=user, object_id=pk) new_hit.save() return function(request) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap where my models.py look like this: hit_post_models = models.Q(app_label='App', model='model1') | \ models.Q(app_label='App', model='model2') | \ models.Q(app_label='App', model='model3') class Hit(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=hit_post_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') viewer = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) this is how my decorator gets placed: @count_view def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) ... But I always falling into the following error: django.db.utils.IntegrityError: (1048, "Column 'content_type_id' cannot be null") -
Is it correct to use multi viewsets for a model?
I have a model which its fields must be filled by both user and admin the key issue is that user need to fill some fields by API request and admin need to fill the others in Django admin panel, I dont want user can allow to POST data to fill some fields but they would be able to see all feilds in GET request. I think this is possible with different routes and viewset. but as I'm newbie in Python/Django I'm not sure what is the best practice(s) for this porpuse. -
what 's the point of adding 'path('accounts/',include('django.contrib.auth.urls'))' to the urls.py file of the django project?
Folks i've just started learning Django and can't get my head around using 'path('accounts/',include('django.contrib.auth.urls'))' in the urls.py file of the django project. Here's my root urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('',views.HomePage.as_view(),name='home'), path('accounts/',include('accounts.urls',namespace='accounts')), path('accounts/',include('django.contrib.auth.urls')), path('test/',views.TestPage.as_view(),name='test'), path('thanks',views.ThanksPage.as_view(),name='thanks'), path("posts/", include("posts.urls", namespace="posts")), path("groups/",include("groups.urls", namespace="groups")), ] and here's my urls.py of the accounts app: urlpatterns = [ path('login/',auth_views.LoginView.as_view(template_name='accounts/login.html'), name="login"), path('logout/',auth_views.LogoutView.as_view(), name="logout"), path('signup/',views.SignUp.as_view(),name='signup'), ] From above, it's obvious that the accounts app is using LoginView and LogoutView for login and logout functionalities. (SignUp view uses UserCreationForm). I also removed 'path('accounts/',include('django.contrib.auth.urls'))' and tried running the server. Apparently, everything seems to work just fine (logging in, logging out and signing up). So what exactly we get by including that in the urls.py ? -
Django: How to arrange template for Django comments and corresponding replies
I have a made a Comment model and views and it works perfectly fine. But I am not able to arrange templates so that it shows reply to its corresponding comments or reply. It will be a great help if you educate me on how do I arrange them. Models.py class Comment(models.Model): serial = models.AutoField(primary_key=True) theme = models.ForeignKey(THEME, related_name='comments', on_delete = models.CASCADE) user = models.ForeignKey(UserModel, related_name='user', on_delete = models.CASCADE) date_added = models.DateTimeField(default=now) body = models.TextField() parent = models.ForeignKey('self',null=True, related_name='replies',on_delete = models.CASCADE) def __str__(self): return f"{(self.body)}({self.user})" Views.py def viewtheme(request, theme_name): theme = THEME.objects.get(theme_name=theme_name) context={} context['theme']=theme if request.POST: form=CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) # Assign the current post to the comment new_comment.theme = theme # Save the comment to the database new_comment.user = request.user if request.POST.get('serial') == '' or request.POST.get('serial') == None: new_comment.save() return redirect(f"/theme/{theme_name}") else: new_comment.parent = Comment.objects.get(serial=request.POST.get('serial')) new_comment.save() return redirect(f"/theme/{theme_name}") context['comments_form']=form else: form=CommentForm() context['comments_form']=form return render(request, 'themes/view_theme.html',context) Template That I tried but didn't worked <div class="card"> <div class="card-body"> <div class="card-title">Comments</div> <div class="card-text"> <form method="POST"> {% csrf_token %} {{comments_form.as_p}} <input type="hidden" name="seral" value=""> <br> <button type="submit">Add Comment</button> </form> <hr> <br> {% if theme.comments.all %} {% for comment in theme.comments.all %} {{ comment.body }} <form method="POST"> {% csrf_token %} {{comments_form.as_p}} <input … -
Memory leak in Django with Gunicorn and max-requests is already set
I have a Django application that is integrated with Gunicorn and Prometheus and Kubernetes. It's an application that queries ElasticSearch. my Gunicorn config is: exec gunicorn wsgi:application \ --worker-class gthread \ --bind 0.0.0.0:15236 \ --workers 40 \ --threads 4 \ --log-level=info \ --log-file=- \ --timeout 20 \ --reload My Problem Memory is gradually increasing. And when I add --max-requests 500 config for Gunicorn, my memory still increases and my Pod becomes Evicted! I also deleted all the URLs except for url('', include('django_prometheus.urls')) to ensure that the memory leak is not caused by my code. I also checked the Prometheus directory and It was only 1mb so it is not caused by Prometheus. and DEBUG is set to False. Questions What is it possibly causing the memory leak? And why is max-requests not helping at all and only worsening? Versions Django==3.1.1 gunicorn==20.0.4 django-prometheus==2.1.0 -
How to create a js portfolio filter (Isotope.js) with Django
I am building a portfolio website with Django and I want to filter porfolios based on a category on my home page, I am using the js portfolio filter pluggin (Isotope.js). I never thought this will be so difficult to achieve in Django and I did not see any resources on this on the Internet. my_custom_processor.py def index(request): port_category = PortfoilioCategory.objects.all() service = Services.objects.all() ''' Many more querysets ''' context = { 'port_category':port_category, 'service':service } return context base.html <ul> {% for port in port_category %} <li><a href="#porfolio_menu" data-filter="{{ port.id }}">{{ port.cat_name }}</a></li> {% endfor %} </ul> How do I create a view or a context_processor for the detail of my portfolio item using the divs below? How do I pass dynamic parameter to my context_processor? How else can I achieve this? <div class="col-xs-12 col-sm-4 appsDevelopment"> <div class="portfolio_single_content"> <img src="{% static 'img/portfolio/p1.jpg' %}" alt="title" /> <div> <a data-lightbox="example-set" href="{% static 'img/portfolio/p1.jpg' %}">Photo Frame</a> <span>Subtitle</span> </div> </div> </div> -
Invalid block tag error. Unable to figure out where have I missed ending block
I am getting the following error:- Invalid block tag on line 124: 'endif', expected 'endblock'. Did you forget to register or load this tag? I am trying to create a pagination system for my listings display. I am trying to figure out where have I missed the ending block. <div class="row"> <div class="col-md-12"> {% if listings.has_other_pages %} <ul class="pagination"> {% if listings.has_previous %} <li class="page-item"> <a href="?page={{listings.previous_page_number}}" class="page-link" >&laquo;</a > </li> {% else %} <li class="page-item disabled"> <a class="page-link">&laquo;</a> </li> {% endif %} {% for i in listings.paginator.page_range %} {% if listings.number == i %} <li class="page-item active"> <a class="page-link">{{i}}</a> </li> {% else %} <li class="page-item"> <a href="?page={{i}}" class="page-link">{{i}}</a> </li> {% endif %} {% endfor %} </ul> {% endif %} </div> </div> -
Pyintsaller Execuatble RuntimeError: Script runserver not found
I used Pyinstaller to created a Django application Executable "testrun" on Linux. Then I used the command "dist/testrun/testrun runserver: localserver:8000" to test the executable. But the error message shows: "RuntimeError: Script runserver not foundspec file hiddenimport used for executable building Executable Runtime Error Message -
Access url (get_absolute_url) in Django Rest Framework inside a javascript
I have trouble in django rest framework where I filtered data using Ajax (completed) but the problem is that I can't access absolute url of a table row (td) to access the detail page (via pdf api) of that row. It is important to mention that it Work fine without Ajax, as I made a template without Ajax. Model class ApplyForm1(models.Model): STATUS = ( ('Active', 'Active'), ('Disabled', 'Disabled'), ) std_campus = models.ForeignKey(Campus, on_delete=models.CASCADE, blank=True) admission_class = models.ForeignKey(CampClass, on_delete=models.CASCADE, blank=True) std_fname = models.CharField(blank=True, max_length=20, null=True) std_lname = models.CharField(blank=True, max_length=20, null=True) std_pic = models.ImageField(upload_to='images/', blank=True) def __str__(self): return '{}'.format(self.std_campus) def std_full_name(self): return self.std_fname + " " + self.std_lname def get_absolute_url(self): return reverse('apply_form', kwargs={ 'id': self.id }) class Campus(models.Model): STATUS = ( ('Active', 'Active'), ('Disabled', 'Disabled'), ) id = models.AutoField(primary_key=True) campus_name = models.CharField(blank=True, max_length=30) user = models.ForeignKey(CampusUser, on_delete=models.CASCADE, blank=True, null=True) status = models.CharField(max_length=10, choices=STATUS, default='Disabled', null=True, blank=True) def __str__(self): return '{}'.format(self.campus_name) View def admissions(request): return render(request, 'admissions.html', {}) class AdmissionListing(ListAPIView): # set the pagination and serializer class pagination_class = StandardResultsSetPagination serializer_class = AdmissionSerializers def get_queryset(self): # filter the queryset based on the filters applied queryList = ApplyForm1.objects.all() campus = self.request.query_params.get('std_campus__campus_name', None) status = self.request.query_params.get('status', None) if campus: queryList = queryList.filter(std_campus__campus_name=campus) if status: queryList … -
Can not install django-heroku
I try pip install django-heroku and it gives me an error: ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Thank you for helping me. -
Django to block certain regex in url
I have a Django-rest-framework and i want to block/return 404 for any URL using regex like ApiRoot/?any-word question mark at the beginning of it, i haven't specified any path in urls.py but Django still returning 200 with any word that comes after "?" question mark. example request url: HTTP GET /?any-word 200 Further more how do i get the request ip when URL like this used? -
Email Sends In Development But Not In Production
I am able to send these automated emails through Dajngo while in my production environment, though in development I get the error [Errno 101] Network is unreachable Exception Location: /opt/alt/python38/lib64/python3.8/socket.py in create_connection, line 796 My settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'email.email@email' EMAIL_HOST_PASSWORD = 'password' SERVER_EMAIL = EMAIL_HOST_USER I think the connection is being refused by Outlook, however it's accepted in my development environment (I used powershell to enable SMTP AUTH). Any help would be greatly appreaciated. Thank you. -
Django get_absolute_url() doesn't seem to work in comment section
I'm trying to get my users to the article page after comments, but something is missing. class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments" ,on_delete=models.CASCADE) name = models.CharField(max_length=30) body = RichTextUploadingField(extra_plugins= ['youtube', 'codesnippet'], external_plugin_resources= [('youtube','/static/ckeditor/youtube/','plugin.js'), ('codesnippet','/static/ckeditor/codesnippet/','plugin.js')]) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) class Meta: verbose_name = "comentario" verbose_name_plural = "comentarios" ordering = ['date_added'] def get_absolute_url(self): return reverse('article-detail', kwargs={'pk': self.pk}) urls.py path('article/<int:pk>/comment/', AddCommentView.as_view(), name='add_comment'), path('article/<int:pk>', ArticleDetailView.as_view(), name="article-detail"), path('article/edit/<int:pk>', UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove', DeletePostView.as_view(), name='delete_post'), For the update_post the get_absolute_url() works. Thanks in advance.