Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting API data array to chartjs in django
I am trying to create a chart using chartjs and this chart is displaying API data(Stock Data). I have made the API successfully and make the data wanted in the form of an array inorder to put it in the chart. When I define the API data array as a variable and use the variable in the chart data it doesn't display anything: <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script> <script> const ctx = document.getElementById('myChart'); let y=new Array(); let theapi = fetch('api_src') .then(response => response.json()) .then(data => { const thewanted = Object.values(data)[1] for (const [key, value] of Object.entries(thewanted)) { y.push(key); } console.log(y) }) new Chart(ctx, { type: 'line', data: { labels: y, datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], borderWidth: 1 }] } , options: { scales: { y: { beginAtZero: true }}}}); </script> if you look at the labels in the chart you will find that I have used the variable as the value of the labels but it doesn't work and whan I console.log the variable I find that it contains the values that I want. Note: When I closed the pc and opened it again after time I found that it worked but when … -
How to effectively prefetch multiple columns in one model?
I'm not sure if my way of prefetching sets of items are correct. Its nested reverse foreign key fetch (another model objects and another's model's model objects). I believe models example will clarify what I mean. class Created(models.Model): created = models.DateField(default=timezone.now) class Meta: abstract = True class Category(Created): category = models.CharField(unique=True, max_length=200) class Question(Created): question = models.CharField(unique=True, max_length=200) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="questions" ) @property def correct_answer(self): return self.questions.filter(correct=True) class Answer(Created): name = models.CharField(max_length=200) correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="answers") My query looks like following: Category.objects.prefetch_related("questions", "questions__answers") The above statement gives me 3 queries which I believe is too much. Or maybe it's okay? Appreciate any feedback :) -
Check if there is a next value in my django template for loop possible?
I'd like to check if there is a next value inside my for loop; If so set a comma if not do nothing. Is there something like an {% ifnext %}? -
Hosting a Django application using Railway: MIME type ('text/html') is not executable, and strict MIME type checking is enabled
I am trying to publicly host my portfolio website under my domain name: www.floriskruger.com. I have build my application using Django and I am using Railway to communicate with my GitHub profile in order to deploy this site. Everything seems to be working fine except for that none of my .css and .js files are linking properly to my website. This is what the links look like within my html file. <!-- CSS Styling --> <link rel="stylesheet" href="/templates/css/home.css" type="text/css"> <!-- JavaScript --> <script src="/templates/javascript/home.js" type="text/javascript" defer> The error that I am getting within the web console states "Refused to apply style from 'https://www.floriskruger.com/templates/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." which makes me think that there is some sort of linking error with how the files are configured? However I did not have this problem on a local host. This is how my files are configured within my project I will also provide how I have my settings.py configured for my static files. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ALLOWED_HOSTS = ['www.floriskruger.com', 'onlineportfolio-production.up.railway.app/'] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] STATIC_URL = 'staticfiles/' STATIC_ROOT = "/www/floriskruger.com/staticfiles/" MEDIA_ROOT = '' MEDIA_URL … -
What if STATIC_ROOT and STATICFILES_DIRS have different path in Django?
I'm working on my project that is basically some type of blog. But I needed to compile different features in one project, which now it can be a problem or maybe not. In order to work I needed to have STATIC_ROOT and STATICFILES_DIRS but I cannot have them both on same location because I got error (ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting.) So I searched for answer and I one guy here on stackoverflow said that he just changed location... he suggested to do it like this... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets_static') MEDIA_ROOT = '' MEDIA_URL = '/media/' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] For that time it has worked, but now I'm changing some static files and they are not updating. Also, now I have folders static and asset_static. Can someone tell what is the best practice here? -
URL validation in Python - edge cases
I'm trying to write/use URL validation in python by simply analyzing the string (no http requests) but I get a lot of edge cases with the different solutions I tried. After looking at django's urlvalidator, I still have some edge cases that are misclassified: def is_url_valid(url: str) -> bool: # from django urlvalidator url_pattern = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$', re.IGNORECASE) return bool(re.match(url_pattern, url)) we still get: >>> is_url_valid('contact.html') True Other approaches we tried: validators (python package), recommended by this SO Q&A >>> import validators >>> validators.url("firespecialties.com/bullseyetwo.html") # this is a valid url ValidationFailure(func=url, args={'value': 'firespecialties.com/bullseyetwo.html', 'public': False}) from this validating urls in python SO Q&A while urllib.parse.urlparse('contact.html') correctly assess it as a path, it fails with urllib.parse.urlparse('www.images.com/example.html')`: >>> from urllib.parse import urlparse >>> urlparse('www.images.com/example.html') ParseResult(scheme='', netloc='', path='www.images.com/example.html', params='', query='', fragment='') Adapting logic from this javascript SO Q&A -
Naming conventions to be used when creating APIs in django to be consumed in javascript
I am creating a REST API in Django to be used in JavaScript. In python, the fields are all named using snake_case, but in JavaScript it is recommended to use camelCase for variable names. How do I resolve this difference without having to rename them when I use them in JS, or do I just stick to one convention on both front and back end? -
How do I send an email to a user using SMTP in Django?
I use the SMTP server to send the reset password link to the user, but the problem is when the user enters his or her email , the reset password email is not sent to him. Anyone can help me, please? settings.py : EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS= True EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypassword' urls.py : path('ResetPassword/' , views.ForgetPassword,name = "ResetPassword"), path('Test_ChangePass/<token>/', views.Test_ChangePass, name = 'Test_ChangePass'), models.py : class Profile(models.Model): image = models.ImageField(default='default.png', upload_to='profile_pics') user = models.OneToOneField(User, on_delete=models.CASCADE) forget_password_token = models.CharField(max_length=100) def __str__(self): return '{} profile.'.format(self.user.username) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.width > 300 or img.height > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) def create_profile(sender, **kwarg): if kwarg['created']: Profile.objects.create(user =kwarg['instance']) post_save.connect(create_profile, sender=User) views.py : def ForgetPassword(request): try: if request.method == "POST": email = request.POST.get('email') if not User.object.filter(email=email).first(): messages.error(request, 'لا يوجد ايميل مسجل مسبقًا ') return redirect('ResetPassword') user_obj = User.objects.get(email=email) token = str(uuid.uuid4()) profile_obj = Profile.objects.get(user = user_obj) profile_obj.forget_password_token = token profile_obj.save() send_forget_password_mail(user_obj,token) messages.error(request, 'تم إرسال الايميل') return redirect('ResetPassword') except Exception as e: print(e) return render(request, 'user/ResetPassword.html') def Test_ChangePass(request, token): context = {} try: Profile_obj = Profile.objects.filter(forget_password_token = token).first() print(Profile_obj) if request.method == "POST": new_password = request.POST.get ('new_password') confirm_password = request.POST.get('confirm_password') … -
How to list latest posts in Django?
I'm working on my blog. I'm trying to list my latest posts in page list_posts.html.I tried but posts are not shown, I don't know why. I don't get any errors or anything, any idea why my posts aren't listed? This is models.py from django.db import models from django.utils import timezone from ckeditor.fields import RichTextField from stdimage import StdImageField STATUS = ( (0,"Publish"), (1,"Draft"), ) class Category(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") title = models.CharField(max_length=255, verbose_name="Title") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") is_published = models.BooleanField(default=False, verbose_name="Is published?") published_at = models.DateTimeField(null=True, blank=True, editable=False, verbose_name="Published at") title = models.CharField(max_length=200, verbose_name="Title") slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey('auth.User', verbose_name="Author", on_delete=models.CASCADE) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) image = StdImageField(upload_to='featured_image/%Y/%m/%d/', variations={'standard':(1170,820),'banner':(1170,530),'thumbnail':(500,500)}) status = models.IntegerField(choices=STATUS, default=0) class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['-created_at'] def publish(self): self.is_published = True self.published_at = timezone.now() self.save() def __str__(self): return self.title This is views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Category, Post def post_list(request): posts = Post.objects.filter(published_at__lte=timezone.now()).order_by('published_at') latest_posts = Post.objects.filter(published_at__lte=timezone.now()).order_by('published_at')[:5] context = … -
"mysql server has gone away" on 404 or 403
Recently, like a few days ago, I switched my Django application from a SQLite database to a MySQL one. However, since then I'm getting failures that the "MySQL server has gone away" when hitting a 403 or 404 error (maybe more, but I can't test that). The funky thing is, the application runs fine after reloading the gunicorn service, but starts acting weird when restarting the mysql service. The gunicorn logs only gives me a bunch of stacktraces, without the actual sql error (the cause is just a hit on the database), and sadly MySQL doesn't tell me either what the problem is, even after enabling error logging. My Django application is running in a virtual environment, managed with poetry. A gunicorn service is running with uvicorn workers, with the following command: /home/XXX/.cache/pypoetry/virtualenvs/project-py3.10/bin/gunicorn --access-logfile - --workers 3 --bind unix:/path/to/project/project.sock project.asgi:application -k uvicorn.workers.UvicornWorker. The database is configured like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'password', 'CONN_MAX_AGE': 3600, 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': 'SET sql_mode="STRICT_ALL_TABLES"' } } } nginx serves requests to the socket, but that works fine; I can't find any error in the nginx logs, and the request "just returns 500". I'm using mysql … -
How to connect image in Django 4?
I have a project, connected database, one picture and form for send another picture. In home page i want connect all pictures from DB but i don't understand how it's work.Please help me, because i try all what i found in internet settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path("", views.products), path("sell/", views.sell), path("created/", views.created), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) else: urlpatterns += staticfiles_urlpatterns() models.py from django.db import models class Product(models.Model): ... product_media = models.ImageField(upload_to="images", verbose_name="Фотографії товару") views.py from django.shortcuts import render from .forms import SellForm from .models import Product from main.settings import MEDIA_URL, MEDIA_ROOT def products(request): product_list = Product.objects.all() return render(request, "products.html", {"product_list": product_list, "media_url": MEDIA_URL, "media_root": MEDIA_ROOT}) products.html <!DOCTYPE html> <html lang="uk"> <head> <style> ... </style> </head> <body> <h1>Оголошення </h1><a href="sell/">Створити нове оголошення</a> {% if product_list %} <table border="1"> <tr> <th>Id</th> <th>Час створення</th> <th>Профіль продавця</th> <th>Ім'я продавця</th> <th>Прізвище продавця</th> <th>Телефон продавця</th> <th>Електронна пошта продавця</th> <th>Назва оголошення</th> <th>Опис</th> <th>Медіа</th> </tr> {% for object in product_list %} <tr> <td>{{ object.id }}</td> <td>{{ object.product_dt }}</td> <td>{{ object.product_username }}</td> <td>{{ object.product_name }}</td> <td>{{ object.product_lastname }}</td> … -
Can I test the sent email in the register view with "mailoutbox" parameter in pytest_django?
I have a register view that sends an activation email and I want to test sending emails with "mailoutbox" parameter in pytest_django. This is the register view: for EmailMessage I used mail_templated and send from django.http import HttpResponseRedirect from django.shortcuts import redirect, render from django.urls import reverse_lazy from django.views.generic.edit import FormView from django.contrib.auth import get_user_model from rest_framework_simplejwt.tokens import RefreshToken from mail_templated import EmailMessage from decouple import config from .utils import EmailThread from .forms import UserCreationModelForm User = get_user_model() class AccountsRegisterFormView(FormView): """ A view for displaying a register form and rendering a template response. """ form_class = UserCreationModelForm template_name = 'accounts/register.html' success_url = reverse_lazy('task:list') def get_token_for_user(self, user): refresh = RefreshToken.for_user(user) return str(refresh.access_token) def form_valid(self, form): """ If the form is valid, redirect to the supplied URL :param form: registration form :return: if form valid register user. """ user_obj = form.save() if user_obj is not None: email = user_obj.email username = user_obj.username token = self.get_token_for_user(user_obj) domain = 'http://127.0.0.1:8000/' url = 'accounts/activation/confirm/' activation_email = EmailMessage( 'email/activation_account.tpl', { 'user': username, 'token': f'{domain}{url}{token}/', }, 'sender@example.com', [email] ) EmailThread(activation_email).start() return HttpResponseRedirect( reverse_lazy('accounts:activation_send') ) return super(AccountsRegisterFormView, self).form_valid(form) I used EmailMessage from mail_templated package. and this is the test: @pytest.mark.django_db class TestAccountsViews: def test_accounts_views(self, client, mailoutbox): url = … -
Django pass form cleaned data to another view
I want to pass the forms cleaned data (captured from a POST method), to another view (preferably as GET params) ... in this case the Dashboard View. def post(self, request): form = FilterForm(request.POST) if form.is_valid(): response = HttpResponse(reverse('dashboard')) How can I accomplish that? -
which is the best Backend Framework for beginners in 2023? [closed]
node+express+mongodb or django+sql **which stack should choose a beginner for Backend in 2023? **which stack will better for future career? I am a junior react developer. I want to learn Bracken in 2023. please leave your valuable advice on comment. your every advice matter for me. -
Class method in timer thread within Websocket in Django
I try to put a timer within websocket consumer, so that I can check task results (taken from celery) and publish to the client. The first message connection_established is received by the client. But the task result method can't send a message. What's the reason for this? class ProcessConsumer(WebsocketConsumer): ... def publish_task_results(self): self.send(text_data = json.dumps({ 'type': 'task_result', 'result': self.results, # builds results in another method. })) def connect(self): self.accept() self.send(text_data = json.dumps({ 'type': 'connection_established', 'message': 'You are now connected', })) threading.Timer(1.0, self.publish_task_results) # calls the method within same class. -
Django 'RichTextUploadingField' object has no attribute 'needs_multipart_form'
Всем привет! Я подключил в свой проект редактор ckeditor, и в поле description изменил тип поля на RichTextField, так же в admin.py у меня используется inlines для ингредиентов. Проблема заключается в следующем, я не могу использовать редактор и inlines одновременно, когда я это делаю вылезает ошибка: 'RichTextUploadingField' object has no attribute 'needs_multipart_form' models.py class Foods(models.Model): description = RichTextField(verbose_name="Описание") class ingredients (models.Model): title = models.CharField(max_length=250,verbose_name="Название") quantity = models.IntegerField(verbose_name="Количество") food_id = models.ForeignKey(Foods,) admin.py from django.contrib import admin from ckeditor_uploader.fields import RichTextUploadingField from django import forms from ckeditor.fields import RichTextField from .models import Foods, ingredients class ingredientsInline(admin.TabularInline): model = ingredients extra = 1 class FoodsAdminForm(forms.ModelForm): description = forms.CharField(widget=RichTextUploadingField ()) class Meta: model = Foods fields = '__all__' class FoodsAdmin(admin.ModelAdmin): inlines = (ingredientsInline,) form = FoodsAdminForm admin.site.register(Foods,FoodsAdmin) admin.site.register(ingredients) Много чего пробовал, но не получилось и в интернете не нашел, джанго изучаю -
Django user creation where superuser can create admin and admin can create client
I to create a django project where there is a single superuser. Superuser can create multiple unique admins and Admins can create multiple users under them. I am new to this can anyone help with this. Thank You I tried creating a superuser and admin but i am not able to create unique admins and users . -
Please help to get content of the file in request.FILES
"""I'm studying Django and have a problem: i need to upload file to server and then re-write database from this file, without saving file in django storage. But i cant upload file and get its content""" 'urls:' path("purchase/about/new_database", xml_parsing, name="new_database"), 'Html:' <div class="container"> {% if request.user.is_staff %} <a class="btn btn-primary" href={% url "orders:new_database" %}>Кнопка</a> {% endif %} </div> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button class="btn btn-primary" type="submit">Upload</button> </form> </div> 'views:' def xml_parsing(request): myfile = request.FILES["myfile"] root_node = ElementTree.parse(myfile.read()).getroot() """and so on""" """Here i get MultiValueDictKeyError. Error in line: myfile = request.FILES["myfile"]. guess, there is no need to provide other code, it works correctly when opening file from computer xml_parsing works on button 'Кнопка', so whether i need to upload file initially, and then click the 'Кнопка' and call xml_parsing function ?""" -
image file inside css is not loading in django
I unable to display image in Django. It is loading images which is in the img tag defined in the html file just fine. But the image defined in the css file is not loading and displaying on the page. I have configured django for static files. And other images are loading properly which is in the static folder. I have a static folder and inside it I have another folder of css which contains all other css files. HTML files are in the templates folder. css file ` /* Cover Section Styling */ #cover{ background-image: url(static/img/random5.jpg); display:flex ; height: 70vh; background-position: center; align-items:center ; justify-content: center; } ` setting.py file ` STATIC_URL = '/static/' # Added manually STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] ` -
Django Server stuck after updating from python 3.9 to python 3.10 (using Django 4.1.5)
After upgrading python 3.9 to 3.10 the Django Server isn't working locally anymore (I'm using the Django Server Plugin for Pycharm). In my gitlab pipeline it seems to work allright. Below you can see further details: With a Python 3.9 venv some errors occur, but the Django Server works nevertheless With a Python 3.10 venv the same errors occur, but the Django Server doesn't start (after waiting 30 min) (Working on linux and with pycharm) I have the same requirements installed on both venv s except for the python version. I'd expect an error message, but it seems the execution is just stuck. -
Reducing number of repeated queries in Django when creating new objects in a loop
I'm populating a database using Django from an Excel sheet. In the example below, the purchases list simulates the format of that sheet. My problem is that I'm repeatedly using Customer.objects.get to retrieve the same Customer object when creating new Purchase entries. This results in repeated database queries for the same information. I've tried using customers = Customer.objects.all() to read in the whole Customer table into memory, but that doesn't seem to have worked since customers.get() still creates a new database query each time. from django.db import models # My classes class Customer(models.Model): name = models.CharField("Name", max_length=50, unique=True) class Item(models.Model): name = models.CharField("Name", max_length=50, unique=True) class Purchase(models.Model): customer = models.ForeignKey("Customer", on_delete=models.CASCADE) item = models.ForeignKey("Customer", on_delete=models.CASCADE) # My data purchase_table =[ {'customer': 'Joe', 'item': 'Toaster'}, {'customer': 'Joe', 'item': 'Slippers'}, {'customer': 'Jane', 'item': 'Microwave'} ] # Populating DB for purchase in purchase_table: # Get item and customer (this is where the inefficient use of 'get' takes place) item = Item.objects.get(name=purchase['item']) customer = Customer.objects.get(name=purchase['customer']) # Create new purchase Purchase(customer, item).save() -
Django : Only display model items that match with for each category and have at least one item
Here are the models I've created class Jeu(models.Model): nom = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField(blank=True) def courses_a_venir(): return self.course_set.filter(date_evenement__gte = datetime.today()).order_by('date_evenement') def courses_passees(): return self.course_set.filter(date_evenement__lt = datetime.today()).order_by('-date_evenement')[:3] class Course(models.Model): jeu = models.ForeignKey(Jeu, verbose_name='Nom du jeu', on_delete=models.CASCADE) ligue = models.ForeignKey(Ligue, on_delete=models.CASCADE) circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE) date_evenement = models.DateTimeField("Date de la course") Here is the view : def home(request): jeux = Jeu.objects.all() return render( request, 'base_site/home.html', context={'title': 'Accueil', 'jeux': jeux,} ) And then here is the HTML code : {% for jeu in jeux %} <h3>{{ jeu.nom }}</h3><br> <div class="row row-cols-1 row-cols-md-3 g-4"> {% for course in jeu.courses_a_venir %} <div class="col"> <div class="card"> <!--<img src="..." class="card-img-top" alt="...">--> <div class="card-body"> <h5 class="card-title">{{ course.date_evenement }}</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> </div> <div class="card-footer"> <small class="text-muted">{{ course.date_evenement }}</small> </div> </div> </div> {% endfor %} </div><br> {% endfor %} <br><br> The thing is, one "Jeu" can be called by multiple "Course". As it is currently implemented in the HTML code, it retrieves all the "Jeu" in the table "Jeu" and the "Course" associated, no matter if some "Jeu" don't contain any "Course". Does somebody know … -
How can I decode a token sent to a user to know when it was created
Hello I did a reset password system in my web that sends a token link to the client's mail in order to client can reset the password, And I want to check the timestap of the hashed token, to make some condition like... expire in 24h. This file make the token and I "guess" is hashing user.pk and timestap and returning a hashed token. I want to make reverse process to know when that token was created. tokens.py: from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) ) account_activation_token = AccountActivationTokenGenerator() Token link is going perfect and client can change the passord whitn no problems. this is my view that handle this with 2 functions 1st for sending the mail, and 2nd for reset the password. view.py: def reset_password(request): form = ResetPasswordForm(request.POST or None) if form.is_valid(): user = User.objects.filter(email=form.cleaned_data.get('email')) if not user: messages.error(request,'This user does not exist') else: user = user.first() current_site = get_current_site(request) subject = 'Reset Password' message = render_to_string('core/reset_password_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) send_mail(subject,message,conf_settings.EMAIL_HOST_USER,[user.email,]) messages.success(request,'Password reset link sent to your email') return redirect('consumer:consumer_home') context = { 'form':form, } return render(request,'core/password_reset.html',context) def reset_password_confirm(request, uidb64, token): … -
Connecting externally to a website in a windows ec2 container
Im failing to connect externally to a django site running in an ec2 windows instance and the common problems im finding online appear to all be accounted for: eg) my firewall is fine (im permitting inbound private and public) my ports seems fine (im running on port 80, and it seems to be the only thing running and my aws security group rules permit port 80) i also have only 1 acl on my whole account, and its the default 1 that permits everything. There is evidence of all of this in images i have stuck at the bottom. What else should i try / investigate / learn about? i did this once before and it was fine. now i keep trying to recreate what i did before and i just cant connect externally. ################## images below as evidence for stuff ################# below is evidence of stuff inside my ec2 container ################################################### below is evidence from my aws account/ attempting to connect from outside ec2 container. (i did try setting my port to 8000 and opening a custom tcp at port 8000 ) ########################################### the image below shows my acl. its the only one on my account -
'Profile' object has no attribute 'User'
enter image description here I get this error every time I create a profile