Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Facing error while using .dat file in Django
I am trying to integrate a deep learning model into my django project and it throws an error saying " can't open shape_predictor_68.dat" . I wrapped my ML code into a function and called it from django rest framework API. What am I missing ? -
How can I send a CSRF token in a form?
I included a Vue form component in one of my Django templates. Now, I would like to send a CSRF token along with the data, since Django views require a CSRF token. Is there any way I can include it in my Vue form? Here is my component: <template> <form @submit.prevent="formSubmit()"> <input type="text" class="form-control" v-model="amount"> <br> <input type="text" class="form-control" v-model="price"> <br> <button class="btn btn-primary" style="width: 100%">BUY</button> </form> </template> <script> import axios from 'axios' export default { mounted() { console.log('Component mounted.') }, data() { return { name: '', description: '', output: '' }; }, methods: { formSubmit() { let currentObj = this; axios.post('MY_URL', { price: this.price, amount: this.amount, }) .then(function (response) { currentObj.output = response.data; }.bind(this)) .catch(function (error) { currentObj.output = error; }); }, } } </script> -
Follow button created with ajax and jQuery not responsive
I'm trying to add a follow feature to my project with ajax views and jquery but the follow button is not responsive. It keeps returning: *127.0.0.1 - - [29/Dec/2020 00:11:47] "POST /account/users/follow/ HTTP/1.1" 404 - Not Found: /account/users/follow/ * whenever I click on the button. Here's my views.py code @ajax_required @require_POST @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create( user_from=request.user, user_to=user, ) else: Contact.objects.filter(user_from=request.user, user_to=user).delete() return JsonResponse({'status': 'ok'}) except User.DoesNotExist: return JsonResponse({'status': 'error'}) return JsonResponse({'status': 'error'}) the model's file from django.db import models from django.conf import settings from django.contrib.auth import get_user_model class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) def __str__(self): return f'Profile for user {self.user.username}' class Contact(models.Model): user_from = models.ForeignKey('auth.User', related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey('auth.User', related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user_from} follows {self.user_to}' # Add following field to User dynamically user_model = get_user_model() user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) then the detail template {% extends "base.html" %} {% load thumbnail %} {% block title %}{{ user.get_full_name }}{% endblock %} {% block content %} <h1>{{ user.get_full_name }}</h1> <div class="profile-info"> <img src="{% thumbnail … -
Django base.models.Post.DoesNotExist
I am very new to django. I have followed the steps from a video on youtube on how to create a simple blog. Basically, I have a portfolio main page that displays several things including the latest blogs. It all works well. I can see the latest posts on the main page. I can also click in each of them and they open up fine. However, now, I want to create a new page (blog.html) that will hold all the posts. I created a blog.html and did the necessary settings in views.py and urls.py. However, for some reason I get an error when trying to access localhost/blog/ This is my urls.py: urlpatterns = [ path('', views.home, name='home'), path('work/', views.work, name='work'), path('<slug:slug>/', views.post_detail, name='post_detail'), path('blog/', views.blog, name='blog'), ] Here views.py: def home(request): posts = Post.objects.all() return render(request, 'home.html', {'posts': posts}) def post_detail(request, slug): post = Post.objects.get(slug=slug) return render(request, 'post_detail.html', {'post': post}) def blog(request): posts = Post.objects.all() return render(request, 'blog.html', {'posts': posts}) And lastly the error: Internal Server Error: /blog/ Traceback (most recent call last): File "C:\Users\frank\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\frank\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\frank\Anaconda3\envs\djangoenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = … -
Translate many-to-many relationship in database ER diagram to Django model
I want to represent users and teams in Django application. Each user can be member of zero or more teams. This is ER diagram of database that I came up with: Following this design, I'd like to implement Django models: class Team(models.Model): name = models.CharField() created_at = models.DateTimeField(auto_now_add=True) class UserIsMemmberOfTeam(models.model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) But this aproach feels not fitted for Django ORM. I've also thought about: from django.db import models from django.conf import settings class Team(models.Model): name = models.CharField() created_at = models.DateTimeField(auto_now_add=True) members = models.ManyToManyField(settings.AUTH_USER_MODEL) There is new field members, but I think, under the hood, database looks similar to the diagram above. Which aproach is better? Maybe each of them has its own perks? But what if: I'd like to assign each team member some role(s) in given team. In ER diagram, I would design it like that: How should I represent it in Django? This time it looks like I can't use the second approach from above, because there is no model representing member. Should I make MemberHasRole model, or should I make Member model that has roles (many-to-many) field? -
Receiving an Error when a Form is submitted related to cleaned_data
I am trying to submit a Message form for my Django Project but I keep receiving an error: AttributeError at / 'MessageForm' object has no attribute 'cleaned_data' I am not sure what is the reason for getting this error although I revised the https://docs.djangoproject.com/en/3.1/topics/forms/ Here is my views.py def home(request): if request.method == 'POST': #Check Post form = MessageForm(request.POST) if form.is_valid(): data = MessageForm() #Create Relationship with Model data.name= form.cleaned_data['name'] data.email= form.cleaned_data['email'] data.message= form.cleaned_data['message'] data.ip = request.META.get('REMOTE_ADDR') data.save() messages.success(request,'Your Message has been sent, Thank you!') return HttpResponseRedirect('base:home') template_name = 'base/home.html' form = MessageForm() ----------------------other unrelated contexts-------------------- context = { 'form': form, } return render(request, template_name, context) Here is the urls.py urlpatterns = [ path('', views.home,name='home') ] Here is the template.html <form class="form" id="form" method="post"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <input name="name" id="form-name" type="text" placeholder="Your Name" class="form-control input" autocomplete="off"/> <div id="name-error"></div> </div> </div> <div class="col-md-6"> <div class="form-group"> <input name="email" id="form-email" type="email" class="form-control input" placeholder="Your E-Mail" autocomplete="off"> <div id="email-error"></div> </div> </div> </div> <div class="form-group"> <textarea name="message" id="form-message" class="form-control input" rows="7" placeholder="Your Message here ..." autocomplete="off"></textarea> <div id="message-error"></div> </div> <!-- Messages --> {% if messages %} {% for message in messages %} <div class="container"> <div class=" alert alert-{{ message.tags … -
Django 400 when sending request through postman, 200 through curl
Problem: When sending request through postman I get 400 error code, logs: Bad Request: /api/auth/login/ [28/Dec/2020 22:07:10] "POST /api/auth/login/ HTTP/1.1" 400 40 [28/Dec/2020 22:07:10] code 400, message Bad request syntax ('{') [28/Dec/2020 22:07:10] "{" 400 - The weird thing I that when I copy the request from postman and past it in the terminal, as the image below, it works fine: ~$ curl --location --request POST 'http://127.0.0.1:8000/api/auth/login/' \ > --header 'Content-Type: application/json' \ > --data-raw '{ > "username": "admin", > "password": "123456" > }' {"access_token":"...","refresh_token":"..."} Other details: When debugging request.data is empty when sending through postman. I am running django in debug mode. -
Getting this error TemplateDoesNotExist at
this is my Views.py from django.shortcuts import render from django.http import HttpResponse Create your views here. def home(request): return render(request, 'home.html') This is my settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z!pmq9mgbaavz!$1i6afqo&-g4egbsql$81s#eii(qt&16z77f' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'seun.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'seun.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True … -
Blank page due to "for template tag" in Django
My web page was working fine until I added {% for %} in my template file. This is my home.html file <body> <div> <div> {% if not status %} <a href="/gmailAuthenticate" onclick="gmailAuthenticate()" title="Google">Google</a> {% else %} {% for item in contexto %} <p>Your are verified</p> <form id="myform" method="post" action="{% url 'logout' id=item.id %}/?next={{request.path }}"> {% csrf_token %} <input type="hidden" name="name" value="value" /> <a onclick="document.getElementById('myform').submit();">disconnect</a> </form> {% endfor %} {% endif %} </div> </div> </body> And this is my home function def home(request): status = True contexto = CredentialsModel.objects.all() if not request.user.is_authenticated: return HttpResponseRedirect('admin') storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() try: access_token = credential.access_token resp, cont = Http().request("https://www.googleapis.com/auth/gmail.readonly", headers={'Host': 'www.googleapis.com', 'Authorization': access_token}) except: status = False print('Not Found') return render(request, 'index.html', {'status': status}) I´ve checked my errors.log file, but nothing is displayed -
Render JSON data to Flask UI vs Django UI?
My requirement is to find out what is the easiest way to render data to web UI via Flask or Django (easiest one) by thinking I already have sample JSON objects with me. Any suggestions how to do that & what's the best/easy among the Flask vs Django ? Thank you! -
Spyne+Django ValueError have conflicting name using
I trying to use spyne to generate a SOAP server, but have an error. Spyne: ValueError: classes <class CHILD'> and <class 'CHILD'> have conflicting name; the types.py file is: class PARENT(ComplexModel): class Section1(ComplexModel): NAME = String class CHILD(ComplexModel): NAME = String class Section2(ComplexModel): NAME = String class CHILD(ComplexModel): NAME = String type = String Have not way to use same class name? spyne need to decalre on views as json and also declare a complexmodel as python classes, but cant use same name of class, but the application need to be return an xml that have this structure, thanks a lot. -
Send emails with Django and SMTP Google
I need to use google's SMTP mail server for my server to send e-mails to x recipients. But the mail never reaches the intended recipient. I have activated the non-secure applications in my gmail account and configured the following: In Gmail I go to "Manage your GMAIL account" -> "Security" and activate 2-step verification. Then in "Manage your GMAIL account" -> "Security" -> "Application password" in selecting application I choose "Other (custom name)" and I add a name for the application and it generates a password of 16-digit characters. Now the Django code is as follows: from django.conf import settings from django.core.mail import EmailMultiAlternatives EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'xxxxxxxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxx xxxx xxxx xxxx' #contrasena de 16 digitos EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'default from email' def send_user_mail(randomNumber): subject = 'Titulo del correo' message = EmailMultiAlternatives(subject, #Titulo "Su número es: "+str(randomNumber), 'xxxxx@gmail.com', #Remitente to=['xxxx@gmail.com']) #Destinatario message.send() in settings.py I added: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' Am I forgetting something or doing something wrong? Thanks in advance. -
How can you print the scrapped values in a paragraph format? Django
One quick question. I'm building a scrapper that outputs emails. For now the emails get printed in a CSV file. But I want the emails to be outputted in a paragraph format on another URL. I've tried doing some things but it doesn't work out. Here is the code: views.py from django.shortcuts import render from django.shortcuts import render from . scrapper import EmailCrawler def index(request): return render(request, 'leadfinderapp/scrap.html') def scrap(request): url = request.GET.get('Email') crawl = EmailCrawler(url) crawl.crawl() return render(request, 'leadfinderapp/results.html') Here is the html fie where I'm trying to output the emails (ignore the code) (results.html): {% load static %} <html> {% for email in scrap %} <p>{{ result }}</p> {% endfor %} </html> -
django-allauth not redirecting me to the next page after
I'm working with Django 3.0.9 and the django-allauth 0.42.0 package. I've implemented the login, signup, reset password and logout pages. And in all of them, when I click the corresponding form button, I'm not being redirected to the next page. However, the action is being done -- if I refresh the page manually I can see I'm logged in/out, etc. I'm not getting any error or warning message anywhere, anytime, either from the browser of from the Django logs. This is how my code looks for the login page, for example. I'm stripping away lots of CSS, HTML, etc. for clarity: login.html: {% load static i18n %} {% load i18n %} {% load account socialaccount %} {% load crispy_forms_tags %} {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} <p>{% blocktrans with site.name as site_name %}Please sign in with one of your existing third party accounts. Or, <a href="{{ signup_url }}">sign up</a> for a {{ site_name }} account and sign in below:{% endblocktrans %}</p> <div class="socialaccount_ballot"> <ul class="socialaccount_providers"> {% include "socialaccount/snippets/provider_list.html" with process="login" %} </ul> <div class="login-or">{% trans 'or' %}</div> </div> {% include "socialaccount/snippets/login_extra.html" %} {% else %} <p>{% blocktrans %}If you have not created an account yet, then please … -
Django elasticsearch - how to implement functional (non-native to Elasticsearch, but common in Django) filters/lookups?
I am integrating elasticsearch into my Django project. Currently, it works to find the exact match only: s = MovieDocument.search().query("match", title=search_query) But I want to be able to use Django's contains. How should I modify my document to do this? @registry.register_document class MovieDocument(Document): class Index: # Name of the Elasticsearch index name = 'movie' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Movie # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'id', 'title', ] -
Send Email From Logged in User Django
Let’s suppose I have an app where all users have an email address and password in the User model. And let’s also also assume that all the users use the same email host and port. Is it possible to set the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD shown below to be variables that pull from the user model? This way when a logged in user uses an email sending functionality, it comes from their email instead of some single email account defined in settings.py as shown below? ‘’’ EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_HOST_USER = 'parsifal_app' EMAIL_HOST_PASSWORD = 'mys3cr3tp4ssw0rd' EMAIL_USE_TLS = True ‘’’ -
IntegrityError at /new_entry/3/ NOT NULL constraint failed: learning_logs_entry.user_id
[enter image description here][1] [1]: https://i.stack.imgur.com/84zxH.png(Please see the picture) My new_entry() function was working fine lately but now it is not saving the form and shows error at new_entry.save(). I don't understand why the error is happening. My function def new_entry(request, topic_id): """Add a new entry for a particular topic""" topic= Topic.objects.get(id=topic_id) if request.method != 'POST': #No data submitted: create a blank form. form = EntryForm() else: # POST data submitted ; create a blank form. form = EntryForm(data=request.POST) if form.is_valid(): new_entry= form.save(commit=False) new_entry.topic = topic new_entry.owner=request.user new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html',context) My models. from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): """A topic user is learning about""" text=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about the topic""" topic=models.ForeignKey('Topic',on_delete=models.CASCADE) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) user= models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural='entries' def __str__(self): """Return a string representation of model""" return self.text[:50] +"..." my template {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic }}</p> <p>Entries:</p> <p> <a href="{% url 'learning_logs:new_entry' topic.id %}">add new entry</a> </p> <ul> {% for entry in entries %} … -
Django DateTime Issue - Server ahead of timezone
I was working on an app and I can't solve the issue of date and time. In setting.py file I have set the timezone to UTC. TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True I live in UTC+05 so when I publish a blog the date and time is 5 hours into the future so the blog can only publish after 5 hours. Is there a way to automatically detect the time zone of users to either add or subtract hours relative to UTC or anything that can automatically solve this issue. models.py class blog(models.Model): blog_text = models.CharField(max_length=1000) pub_date = models.DateTimeField("date published") def __str__(self): return self.blog_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = "pub_date" was_published_recently.boolean = True was_published_recently.short_description = "Published recently?" -
Using a model manager isn't working but querying using a filter in in the view does, where am I going wrong?
I am trying to create a view to show all friend requests for a user. I am able to render the requests in a view if I use a plain filter method but moving to the model and using a model manager doesn't find the objects that are found by the filter method in the view. To me, they seem the same, so I must be misunderstanding something. Trying to use the model manager in the view to query, the query doesn't return anything like so: profile = get_object_or_404(Profile, user=request.user) rec_req = FriendRequest.objects.received_requests(to_user=profile.user) However, if I use the filter method in the view directly I get the objects like so: profile = get_object_or_404(Profile, user=request.user) rec_req = FriendRequest.objects.filter( to_user=profile.user ) #models.py class FriendRequestManager(models.Manager): def received_requests(self, to_user): rec_req = FriendRequest.objects.filter(to_user=to_user, status='requested') return rec_req class FriendRequest(models.Model): to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') from_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user') created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=9, choices=STATUS_CHOICES) is_family = models.BooleanField(default=False) objects = FriendRequestManager() I'd really appreciate the help because I am stuck. TIA -
Django User model overrides profile picture and menu data
I created a view to display user profiles. The associated view grabs the username parameter from the URL and gets the user using the get_queryset() function. The problem is: I have the profile picture of the currently logged in user displaying at the top right of my menu as well as a link to their profile. Now, if I type in a username in the webbrowser[!, I successfully land on their profile but at the same time, the profile picture inside the menu as well as the link which should direct the user to their own profile gets overwritten with the data from the user profile that is currently displayed. Below is the class that I use to display a user profile. class ProfileView(LoginRequiredMixin, DetailView): model = User template_name = 'users/profile.html' def get_object(self): return get_object_or_404(User, username=self.kwargs.get('username')) def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return User.objects.filter(username=user).first() Here is a picture of the menu as a reference. I use the user.username object inside my template to display the link of the currently logged in user. Now, I found a way to basically fix this problem by using the request.user.username which successfully shows me the link and the profile picture of the currently logged … -
how make a conditions in django annotate?
i'm, trying to do something like this : c = if x > y return x else return y inner annotate function class factura (models.MODEL): price = Model.integerField(max_length=50, null=False) articles = Models.charField(Max_length=50, default=0, null=False) iva = Models.integerField(max_length=50) discount = Model.integerField((max_length=50) factura.objects.annotate( total = if total_articles > price return iva else return thnks -
Module Not Found Error inside virtual environment
I am working on a project inside virtual environment and suddenly I got this error: (env) D:\django3_by_example\env\Scripts>pip install markdown3.2.1 Traceback (most recent call last): File "c:\users\lenovo\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\lenovo\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "D:\django3_by_example\env\Scripts\pip3.exe_main.py", line 4, in ModuleNotFoundError: No module named 'pip' It was working fine till now and after a moment it gave me this error. I checked the path from 'where pip' command and it showed me its installed inside virtual environment. -
Issue with dates when displaying on Page
The issue I have is the following: When I display dates on the page, they show up 1 day less than what is stored on the database. How do I fix this issue? -
DjangoRelatedObjectDoesNotExist at /profile/
I've been through in similar topics for days for a possible solution, however none of them solved my issue which seems pretty simple to me but I stucked on this error right after I created a user: RelatedObjectDoesNotExist at /profile/ Error I'm getting I know there must be something missing in my singlas.py which does not create the Profile after creation of a User but I'm lost in solutions after tried many. Any help will make my day after long frustration period; In project main folder; settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7aa*ng4p*o!9h4%hyfgu=9xy69aumg6hzbz3g)1mf^4!+gi+e0' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition DEFAULT_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.daily_brief', 'apps.users', 'apps.crm', ] THIRD_PARTY_APPS = [ 'crispy_forms', 'django_cleanup', 'social_django', ] LOCAL_APPS = [] INSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'project_folder.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR … -
Email confirmation class view
I'm currently trying to display a confirmation html page when a user clicks the link in their email. The URL I send in the email is http://localhost:8000/confirm/?email=hello@example.com&conf_num=639836786717 My class view for this, in order to validate if it's the right conf_number and email is as such class ConfirmView(DetailView): template_name = 'confirm.html' def get(self, request, **kwargs): context = super(ConfirmView, self).get_context_data(**kwargs) email = request.GET['email'] sub = Newsletter.objects.get(email=email) if sub.conf_num == request.GET['conf_num']: sub.confirmed = True sub.save() action = "added" else: action = 'denied' context["email"] = email context['action'] = action return context but I get this error AttributeError: 'ConfirmView' object has no attribute 'object' now I'm unsure that's because I'm calling Super on my custom class view?