Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to Select data from django tables and insert them to an another external database in use?
i have some data in Django database and i want to select them and copy them to an other external database in use the structure of tables in Django database and in external database is same i hope find any help please for make this logic ,thank you -
How to get specific value from parent-class in django serializer
Context I am trying to recreate the hospital management system wherein once the user logins[either as a patient or as a doctor] on the website; the patient/user can track their health record and so can the concerned doctor. To do so, I have used the AbstractBaseUser class to create a custom-user-model wherein user can choose their user-role which is either doctor or patient during signup class UserProfile(AbstractBaseUser, PermissionsMixin): """ Database Model for users in the system """ email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USER_TYPE_CHOICES = ( ('DOCTOR', 'DOCTOR'), ('PATIENT', 'PATIENT'), ) user_type = models.CharField(max_length=255, choices=USER_TYPE_CHOICES, null=True) The doctor model is an extension of UserProfile model with doc as ForeignKey attribute class Doctor(models.Model): doc = models.ForeignKey( UserProfile, null=True, blank=True, on_delete=models.CASCADE) #.....Other doctor attributes..... def __str__(self): return f'{self.doc.name}' The patient model is an extension of both UserProfile and Doctor class Patient(models.Model): pat = models.ForeignKey( UserProfile, null=True, blank=True, on_delete=models.CASCADE) doctor = models.ForeignKey( Doctor, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return f'{self.pat.name}' The disease of the patient is another model which is has a foreign-key attribute patient class DiseaseOfPatient(models.Model): pat = models.ForeignKey(Patient,null=True,blank=True,on_delete=models.CASCADE) #other attributes are ailment attributes of that particular patient Problem When I run "python manage.py shell" … -
When I try to delete a superuser I get this error : Manager isn't available; 'auth.User' has been swapped for 'auctions.User'
I started a Django project with one starting app called auctions, I have two super user, so I tried to delete one, with this shell commands: from django.contrib.auth.models import User User.objects.get(username="XXX", is_superuser=True).delete() but I receive this error: Manager isn't available; 'auth.User' has been swapped for 'auctions.User' This are my files: models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass views.py from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .models import User def index(request): return render(request, "auctions/index.html") def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "auctions/login.html") def logout_view(request): logout(request) return HttpResponseRedirect(reverse("index")) def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "auctions/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: user = User.objects.create_user(username, email, password) … -
PermissionRequiredMixin issue
views.py model =Lab template_name ='repo/lab_detail.html' login_url ='account_login' permission_required='labs.add_lab' even after adding the can add lab permission to user the site showing 403 Forbidden code -
Github webhook returns 404 to my django app
I'm trying to build an auto-deploy system with github webhooks where I commit every time I push to master, but I'm new to this and I'm struggling to make it work. Goal: So far my goal is to just fire a github webhook and have a status 200 What I've done: I tried 2 approaches, I created a deploy.sh with this content: echo "Hey it is deploying" the webhook was set the following: Payload URL: https://recyppo.com/deploy.sh Content type: application/x-www-form-urlencoded Secret: ''(empty) Enable ssh verification Which events would you like to trigger this webhook?:Just the push event. I create the webhook and in Recent deliveries there is something that looks like a test { "zen": "It's not fully shipped until it's fast.", "hook_id": 236644851, "hook": { "type": "Repository", "id": 236644851, "name": "web", ... but it fails with 404 status and the response is the custom 404 page of my django webapp -
Django self.renderer_classes object of type 'type' has no len()
I create a basic django rest project and follow the official tutorial. When I called my API the following error message appears. Am I missing some settings? object of type 'type' has no len() Request Method: GET Request URL: http://localhost:8000/test Django Version: 3.0.6 Exception Type: TypeError Exception Value: object of type 'type' has no len() Exception Location: D:\Projects\PythonProjects\poeRadar\venv\lib\site-packages\rest_framework\views.py in default_response_headers, line 158 Python Executable: D:\Projects\PythonProjects\poeRadar\venv\Scripts\python.exe Python Version: 3.6.5 Here is my code setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ) } url.py from django.conf.urls import url from backend.api import views urlpatterns = [ url(r'^test$', views.test) ] views.py from rest_framework.response import Response from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer import requests @api_view(('GET',)) @renderer_classes((JSONRenderer)) def test(request): return Response({'a': 1}) -
Django - How to cast "None" from url kwargs to None without repeating yourself
I have a model like this: #models.py class Location(BaseArticle): name = models.CharField(max_length=200) parent_location = models.ForeignKey("self", blank=True, null=True, help_text="Fill in if this location is a smaller part of another location.", on_delete=models.SET_NULL) description = HTMLField(blank=True, null=True, help_text="A description of the location and important features about it") class Meta: unique_together = ('name', 'parent_location') I decided in my urls to uniquely identify each Location through its own name, and the name of its parent-element. # urls.py urlpatterns = [ path('locations/<str:parent_location_name>/<str:location_name>', wiki_views.LocationView.as_view(), name='location'), ] # example url to location "Seedy Bar" located in "City" # https://<DOMAIN>/locations/city/seedy bar # example url to location "City" that does not have a parent_location # https://<DOMAIN>/locations/none/city As you can see from the examples, Locations where parent_location is null/None are possible. I decided to convert None to "None" for these urls, though I'm not set on what None gets transformed to. Now as you may realize this means that whenever I do anything with Location, I need to pay attention to convert "None" to None in the views as necessary, which gets annoying really fast. To follow DRY I was wondering what the best way would be to deal with this, or have I designed myself into a corner here? What … -
is it safe to pass csrf_token directly to ajax post data?
I have a concern about the safety of using Django's {{ csrf_token }} in an ajax call stated in a template. Consider the case below: function set_sensitive_data() { $.ajax({ url: "{% url 'some_sensitive_view' %}", method: "POST", data:{ 'csrfmiddlewaretoken': "{{ csrf_token }}", 'sensitive_data': "{{ some_data }}" }, }); } It works perfectly fine but is there any particular reason why I shouldn't do it this way? I've read Django docs and know that preffered way is to use cookies but that's not my case and I'm not asking about other solutions - I just want to know if this way is unsafe and if so then why? -
how to make foreignkey from different fields django using to_field
hi i'm trying to make a new foreignkey from different fields using to_field but it return product values instead no_invoice class Model1(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Products,on_delete=models.CASCADE) no_invoice = models.IntegerField(unique=True) def __str__(self): return product.name class Model2(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) invoice = models.ForeignKey(Model1,to_field='no_invoice',on_delete=models.CASCADE) is there something else i have to add ? thanks -
how to login with registered phone number and password in Django
here is the code for registration with email and password but how to do with phone number i have models.py 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("Users must have an email address") if not username: raise ValueError("Users must have an username") 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) is_superuser = models.BooleanField(default=False) # first_name = models.CharField(max_length=30) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True whenever i was trying to createsuper the it gives me the following error Traceback (most recent call last): File "C:\Users\TIKAMS~1\DJANGO~1\env\lib\site-packages\django\db\backends\utils.p y", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\TIKAMS~1\DJANGO~1\env\lib\site-packages\django\db\backends\sqlite3 \base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: account_account The above exception was the … -
On extending django user model but i am getting this error: from customauth.models...... No module named 'customauth'
Here is my models.py from django.db import models from datetime import datetime from django.utils import timezone from django.contrib.auth.models import User,auth from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, mobile, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') if not mobile: raise ValueError('Users must have a mobile number') user = self.model( email=self.normalize_email(email), mobile=moble, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, mobile, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, mobile=mobile, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) mobile = models.CharField(max_length=12) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['mobile'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" … -
How to setup a live streaming platform for paid users [closed]
I want to setup a live steaming platform for users to stream videos to their followers form mobile apps or webcams. What would be the tech stack for that type of platform if I want to use scalable open source technologies. -
Django filter Foreign query Key
In this quiz game, I'm trying to filter the questions of a particular course. models.py class Course(models.Model): course_name = models.CharField(max_length=50) date_created = models.DateTimeField(auto_now_add=True) class Quiz(models.Model): course_name = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='quiz_course') question = models.TextField(max_length=100) class Choice(models.Model): question = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="choice_question") choice = models.CharField(max_length=100) is_true = models.BooleanField("This is Correct Answer", default=False) class Quizgame(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) total_score = models.DecimalField("Total score", default=0, decimal_places=2, max_digits=6) start_time = models.DateTimeField(auto_now_add=True) finish_time = models.DateTimeField(null=True) def get_new_question(self,course_id): used_question = AttemptedQuestion.objects.filter(quiz_profile=self).values_list('question__id',flat=True) remaining_questions = Quiz.objects.exclude(id__in=used_question) if not remaining_questions.exists(): return return random.choice(remaining_questions) def create_attempt(self, question): attempted_question = AttemptedQuestion(question=question, quiz_profile=self) attempted_question.save() class AttemptedQuestion(models.Model): quiz_profile = models.ForeignKey(Quizgame, on_delete=models.CASCADE, related_name='attempt') question = models.ForeignKey(Quiz, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE, null=True) is_true = models.BooleanField(default=False) In above where in class Quizgame I filter the questions in get_new_question method here I passed an course_id as an argument by I don't know how to filter out with the course_id for the particular course questions.. -
TemplateDoesNotExist at /test/ error popped up while running application
iam using django 3.08 my view function is as follows ============================================= from django.shortcuts import render import datetime # Create your views here. def date_time_view(request): date=datetime.datetime.now() h=int(date.strftime('%H')) if h<12: msg='Hello Guest!!! Very good Morning!!!' elif h<16: msg='Hello Guest!!! Very good Afternoon !!!' elif h<21: msg='Hello Guest!!! Very good Evening!!!' else: msg='HELLO GUEST!! very good Night!!!' my_dict = {'date':date,'msg':msg} return render(request, 'testapp/results.html', my_dict) my template is as follows:- <!DOCTYPE html> {%load staticfiles%} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>hello</title> </head> <body> <h1>{{msg}}</h1> <h2>{{date}}</h2> <img src="{%static "images/images.jpg" %}"> </body> </html> -
How to use Ajax to update pandas dataframe and change plotly graph accordingly
I am very much new to Django and Ajax. I have had decent knowledge on Plotly and Dash, but unfortunately for my project we need login sessions, db etc so had to learn django for it. My problem statement is I have a plotly bar chart, which displays top performing items based on sales. Also I have a dropdown that has categories , on changing the dropdown values aka categories, I would like the bar graph also to update. I have no prior knowledge on Ajax, but with some googling i was able to come up with the below code. My Ajax Code : $('#category').change(function(){ var category = $(this).val(); $.ajax({ headers: { "X-CSRFToken": token }, type:'POST', url : 'test/', data : { 'category':category } }) }); My plotly JS code : var categoryGraph = document.getElementById('categoryTrend'); var bstPerfbar = document.getElementById('bstPerfBarPlt'); var data_categoryGraph = {{data_categoryTrend_pl|safe}}; var layout_categoryGraph = { title:'Category Trend', //width: 1200, //height: 400, xaxis : { automargin : true }, yaxis : { tickprefix : '₹', tickformat:',.2f', type:'log', autorange : true } }; var data_bstPerfBar = {{data_bstPerf_plt|safe}}; var layout_bstPerfBar = { title:'Top performing Items', //width: 1200, //height: 400, xaxis : { automargin : true }, yaxis : { tickprefix : … -
Get the list element that was clicked from a Javascript object event handler that calls another object method
The javascript object looks like this: chat = { .... cacheDOM: function(){ this.$channel = $('.conversation'); }, bindEvents: function() { this.$channel.on('click', this.switchChannel.bind(this)); }, switchChannel: function(){ this.$nameOfRoom = this.$channel.find('.name').attr('data-room-slug'); } }; And the template looks like this: <ul class="list"> {% for student in student_list %} <li class="clearfix conversation"> <div class="name" data-room-slug="xyz">{{student.fullname}}</div> </li> {% endfor %} </ul> Any help is appreciated, if you know how to access the li element that was clicked in the switch Channel function. The way it is, the click is sending ALL of the li elements, and I only end up finding the first element's attributes no matter which li element I click. -
All Possible Causes of 403 Forbidden From CSRF
I want to know all the possible triggers of a 403 Forbidden from CSRF. What causes this error to show up and how can I prevent it, in all of its cases. Thanks! -
Django Allauth Prevent Email Verification & Password Reset Email Abuse/Spam
I need to stop users from abusing allauth's ability to send users verification & password reset emails so that my email provider does not temporarily suspend my email address for sending too many emails. On the /accounts/email/ page, a user could click the re-send verification all they want and an email gets sent every click. I noticed an ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN setting but am not entirely sure how it works. I tried testing it and am still able to spam click and have the emails get sent every click. On the /accounts/password/reset/ page, this issue occurs: https://github.com/pennersr/django-allauth/issues/2167 The creator mentions doing something like this to alleviate it: https://github.com/pennersr/django-allauth/issues/1008 Maybe this can be used to solve both problems? How would you implement it with the allauth code? https://stackoverflow.com/a/2157688/13955916 Would rate limiting or throttling solve this? If so, what would a code example be for this? I came up with a client side javascript cookie solution but am afraid it will not be effective to stop these problems since it is not a server side solution: button.disabled, button[disabled] { box-shadow: none; cursor: not-allowed; opacity: 0.5; pointer-events: none; } <button id="re-send" class="secondaryAction" type="submit" name="action_send" >{% trans 'Re-send Verification' %}</button> <script> const resendBtn … -
Django PDF Print with Apache (WAMP) error
Im trying to Print a PDF using PyWin32. It works perfectly well on the Django test server. When i migrate to WAMP apache I get a System error and I havent been able to find a solution. Any help with this would be really helpful. def print_label(printer_id, filename): all_printers = [] # A List containing the system printers if not os.name == 'posix': for printer in win32print.EnumPrinters(2): all_printers.append(printer[2]) if path.exists(filename): print("Setting default printer to: {} File name: {}".format(all_printers[printer_id], filename)) win32print.SetDefaultPrinter(all_printers[printer_id]) win32api.ShellExecute(0, "print", filename, None, ".", 0) return True else: print("File not found {}".format(filename)) return False else: return True I get the following error when I run on Apache: SystemError at /dashboard/printer_test/ returned a result with an error set Request Method: GET Request URL: http://127.0.0.1/dashboard/printer_test/ Django Version: 3.0.7 Exception Type: SystemError Exception Value: returned a result with an error set Python Executable: C:\wamp\bin\apache\apache2.4.41\bin\httpd.exe Python Version: 3.7.0 Python Path: ['C:\Users\User\Agnus_POS', 'C:\Program Files (x86)\Python37-32\python37.zip', 'C:\Program Files (x86)\Python37-32\DLLs', 'C:\Program Files (x86)\Python37-32\lib', 'C:\wamp\bin\apache\apache2.4.41\bin', 'C:\Program Files (x86)\Python37-32', 'C:\Program Files (x86)\Python37-32\lib\site-packages', 'C:\Program Files (x86)\Python37-32\lib\site-packages\win32', 'C:\Program Files (x86)\Python37-32\lib\site-packages\win32\lib', 'C:\Program Files (x86)\Python37-32\lib\site-packages\Pythonwin'] Server time: Sat, 25 Jul 2020 11:34:54 +0000 Im not sure how to fix it. -
Django: FieldError: Cannot resolve keyword 'username' into field
I am putting up a website. I have two apps in my website- 'accounts' and 'articles'. I am trying to create a User view which when searched by username returns all articles authored by that particular user. The models are: articles.models.py class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField() uploads = models.FileField(blank=True, null=True, upload_to='uploads/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='articles') clappers = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="claps", blank=True) slug = models.SlugField(max_length=120, unique=True) is_anonymous = models.BooleanField(default=False) def save(self, *args, **kwargs): self.slug = get_unique_slug(self.id, self.title, Article.objects) return super(Article, self).save(*args, **kwargs) def get_unique_slug(id, title, obj): slug = slugify(title.replace('ı', 'i')) unique_slug = slug counter = 1 while obj.filter(slug=unique_slug).exists(): if(obj.filter(slug=unique_slug).values('id')[0]['id'] == id): break unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug The accounts.models.py file: class User(AbstractUser): username = models.CharField(max_length=120, unique=True) email = models.EmailField(unique=True) phone = models.CharField(max_length=10) avatar = models.ImageField(blank=True, null=True) bio = models.CharField(max_length=250, blank=True, null=True) slug = models.SlugField(max_length=120, unique=True) def get_username(self): return self.username def save(self, *args, **kwargs): self.slug = get_unique_slug(self.id, self.username, User.objects) return super(User, self).save(*args, **kwargs) def __str__(self): return self.username def get_unique_slug(id, title, obj): slug = slugify(title.replace('ı', 'i')) unique_slug = slug counter = 1 while obj.filter(slug=unique_slug).exists(): if(obj.filter(slug=unique_slug).values('id')[0]['id'] == id): break unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug Here … -
Django better way to send model data to the headers and footers
In Django, we create the templates for the headers and footers so as to mitigate the code repetition. But when, the content of the headers and footer are dynamic then for every view we need to query the content and pass the context like this: from django.shortcuts import render from models import HeaderModel, FooterModel def home(request): #views code here: #get latest news header_content = HeaderModel.objects.all() footer_content = FooterModel.objects.all() #info to pass into the html template context = { 'header_content': header_content, 'footer_content': footer_content, } return render(request,'home.html',context) def login(request): #views code here: #get latest news header_content = HeaderModel.objects.all() footer_content = FooterModel.objects.all() #info to pass into the html template context = { 'header_content': header_content, 'footer_content': footer_content, } return render(request,'login.html',context) In my approach, I see that for every pages I need to repeatedly write the code for the header and footer content and pass into the context. Is there any better way to do this so that there is no repetation ?? -
Django 2 - URL routing issue
I am trying to get my index page to open on my Django 2 project, but I cant seem to get it to open a simple page from the templates in my music app(index.html). Using class based views at the moment. My releases URL works but that is using he re_path. I cant seem to get the normal path to work at all. I haven't looked at the project for a year and am not normally working with Django, but want to get back into it. urls.py from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), # include urls from the music app path('music/', include('music.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) music/urls.py from django.contrib import admin from django.urls import path, include, re_path from . import views # defined the app name in case the same fields are used in other apps app_name = 'music' urlpatterns = [ # no info past music return index EG /music/ path('', views.IndexView.as_view(), name='index'), re_path(r'^release/$', views.ReleaseView.as_view(), name='release'), re_path(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name="detail"), re_path(r'^(?P<pk>[0-9]+)/$', views.ArtistView.as_view(), name="artist"), re_path(r'^register/$', views.UserFormView.as_view(), name="register"), ] views.py from django.shortcuts import render, redirect from django.contrib.auth import … -
Django-allauth error "Social Network Login Failure"
I am trying to integrate facebook login in django using django-allauth library. Here is my website link, https://thelittlechamp.com/ on the nav bar you can see facebook login button. The problem is when i try to login it says "Social Network Login Failure" even though i have configured all settings properly. Please provide me suggestions where i might have done wrong. I can provide anyother configuration screenshot if necessary. -
How to send email through contact.html template in django
Here is my contact.html code <div class="col-lg-8"> form class="form-area " id="myForm" action="{% url 'contact' %}" method="post" class="contact-form text-right"> <div class="row"> {% csrf_token %} <div class="col-lg-6 form-group"> <input name="name" placeholder="Enter your name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your name'" class="common-input mb-20 form-control" required="" type="text"> <input name="email" placeholder="Enter email address" pattern="[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter email address'" class="common-input mb-20 form-control" required="" type="email"> <input name="subject" placeholder="Enter subject" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter subject'" class="common-input mb-20 form-control" required="" type="text"> </div> <div class="col-lg-6 form-group"> <textarea class="common-textarea form-control" name="message" placeholder="Enter Messege" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Messege'" required=""></textarea> </div> and here is my views.py file def contact(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] send an email send_mail( subject, name, message, email, ['nishantkkr68@gmail.com'], fail_silently= False ) return render(request,'contact.html',{'name': name}) else: return render(request,'contact.html',{}) Here is my settings.py file EMAIL_HOST = 'localhost' EMAIL_HOST = '1025' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False It seems my action button in contact.html is not doing any job (NOTE: My localhost 1025 is working) How can I solve this please help Thank You. -
django registration accounts cannot find url to register
I've been trying for hours to find the solution to this problem: admin/ accounts/ ^activate/complete/$ [name='registration_activation_complete'] accounts/ ^activate/resend/$ [name='registration_resend_activation'] accounts/ ^activate/(?P<activation_key>\w+)/$ [name='registration_activate'] accounts/ ^register/complete/$ [name='registration_complete'] accounts/ ^register/closed/$ [name='registration_disallowed'] accounts/ ^register/$ [name='registration_register'] accounts/ ^login/$ [name='auth_login'] accounts/ ^logout/$ [name='auth_logout'] accounts/ ^password/change/$ [name='auth_password_change'] accounts/ ^password/change/done/$ [name='auth_password_change_done'] accounts/ ^password/reset/$ [name='auth_password_reset'] accounts/ ^password/reset/complete/$ [name='auth_password_reset_complete'] accounts/ ^password/reset/done/$ [name='auth_password_reset_done'] accounts/ ^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$ [name='auth_password_reset_confirm'] Django3 has registration-redux installed and the registration model is trying really hard to find the logout url ..herokuapp.com/accounts/logout But its seemed to go through the urls in order above and not matching on accounts/logout, and including a space in the account views configured by registration-redux. Annoying because I've installed registration in my urls.py file: from django.conf import settings from contacts.views import profile from django.contrib import admin from django.urls import include, reverse, path urlpatterns = [ path('admin/', admin.site.urls), path('', include(site_urls)), url(r'^accounts/', include('registration.backends.default.urls')), path('accounts/', include('registration.backends.default.urls')), path('accounts/profile', profile, name='profile'), path('', include('contacts.urls')), ] As well as migrating to use the path style urls as opposed to urls. Any help here appreciated as I don't understand why it cant match the account/logout url.