Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve XLRD error on excel upload to a model
This is the error I get from a view that tries to upload an excel data file into a django model. Traceback (most recent call last): File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Django\Links Online Exams\Links_Online_Results\teachers\views.py", line 106, in UploadTeacherView book = xlrd.open_workbook(path) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\__init__.py", line 172, in open_workbook bk = open_workbook_xls( File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\book.py", line 79, in open_workbook_xls biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\book.py", line 1284, in getbof bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8]) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\xlrd\book.py", line 1278, in bof_error raise XLRDError('Unsupported format, or corrupt file: ' + msg) xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'code,fir' [05/Apr/2021 22:54:31] "POST /teachers/upload HTTP/1.1" 500 87102 Below is the view that am trying to work out from. I have actually been unable to figure out the right solution to this problem. I believe one of us must have caught this error in one or more instances. def UploadTeacherView(request): message='' if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['file'] fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'wb') as tmp: tmp.write(excel_file.read()) … -
I want to get all anime related to specific Genre,
model class Genre(models.Model): genre = models.CharField(max_length=100, null=True) def __str__(self): return self.genre class anime(models.Model): anime_name = models.CharField(max_length=100, default="") description = models.CharField(max_length=1000, null=True) Genre = models.ManyToManyField(Genre) Season = models.IntegerField(null=True) Episodes = models.CharField(max_length=100,null=True) IMDB_Rating = models.FloatField(null=True) #Image = def __str__(self): return self.anime_name view def g(request, G): animes = anime.objects.filter(Genre=G) x = {'animes': animes} return render(request, 'Anime/genre.html', x) urls path('genre/<G>/', views.g, name="main"),` -
Python API to Generate Mask Number
I am working on a web app. This web app need a voice call features. When a client click on the Call Button then a call will be connect with the receiver. Call Here receiver is a registered user. But I need to keep private the contact number of the user. I have to ensure that from the web app i.e. site, when a client make call, client or caller will not be able to see the original phone number of the receiver i.e. I need to do Call Masking. For that reason I am looking for an API to generate a Mask Number. When a new user will sign up into the site then a mask number will be generate for that user using the original number of that user by the API. My Web app is python (django) based. So is there are any API available in Python for call Making. -
Problem not display datetime field form in browser in django
What I can't see input datetime form.form django in my browser? the program that I run in the browser, The following code displayed instead of the input datetime i have brought the codes of all the pages, please check Thank you for your reply forms.py from django import forms from django.contrib.auth.models import User from datetime import datetime class ExpenseForm (forms.Form): text = forms.CharField( widget=forms.TextInput(attrs={'placeholder':'توضیحات' ,'class':'form-control'}), label='توضیحات', ) date = forms.DateTimeField( initial=datetime.now(), widget=forms.DateTimeInput(attrs={ 'placeholder':'تاریخ' , 'class':'form-control', 'type': 'datetime-local'}), label='تاریخ', ) amount = forms.IntegerField( widget=forms.NumberInput(attrs={'placeholder':'مقدار' ,'class':'form-control'}), label='مقدار' ) view.py @login_required() def submit_expense(request): expense_form = ExpenseForm(request.POST or None) if expense_form.is_valid(): text = expense_form.cleaned_data.get('text') date = expense_form.cleaned_data.get('date') amount = expense_form.cleaned_data.get('amount') Expense.objects.create(text=text , date=date , amount=amount , user_id=request.user.id) return redirect('/submit/expense') context ={ 'expense_form':expense_form } return render(request,'hello.html',context) hello.html {% extends 'shared/_MainLayout.html' %} {% load static %} {% block content %} <div class="login-form"><!--expense form--> <div class="col-sm-4 col-sm-offset-1"> <div class="login-form"><!--expense form--> <h2>پولهای خرج شده :</h2> <form method="post" action="#"> {% csrf_token %} {{ expense_form.text }} {{ expense_form.amount }} {{ expense_form.data }} <button type="submit" class="btn btn-default">ثبت</button> </form> </div><!--/login form--> </div> {% endblock %} please check the image to see my problem browser page -
Django make migrations returns ModuleNotFoundError
I'm just starting to learn Django through online lectures and I'm trying to run this command python3 manage.py makemigrations It returns the following error Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", … -
Uncaught SyntaxError: missing ) after argument list at line 1
I get the error down below at line one. Uncaught SyntaxError: missing ) after argument list {% extends 'main/base.html' %} {% load static %} {% block title %} Decont {% endblock title %} {% block meta %} <script> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); $(document).ready(function () { // Decont Lista // const URL_DECONT = "/api/decont-list/"; let decont_lista = []; $.getJSON(URL_DECONT, function(result){ $.each(result, function(i, field){ decont_lista.push(field); }); function compare(a, b) { if (a.data < b.data) { return 1; } if (a.data > b.data) { return -1; } return 0; } decont_lista.sort(compare); $.each(decont_lista, function(i, field){ $("#table_decont").append(` <tr> <th class="align-middle text-center" scope="row">${field.pk}</th> <td class="align-middle text-center">${field.user}</td> <td class="align-middle text-center">${field.data}</td> <td class="align-middle text-center"><a id="atasament_nume${field.pk}" href='${(field.file!==null)?field.file:"#"}' style="color: black; font-weight: 500;">${(field.file_name!==null)?field.file_name:"Fără atașament"}</a></td> <td class="align-middle text-center"> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapse${field.pk}" aria-expanded="false" aria-controls="collapse${field.pk}"> Edit </button> </td> </tr> <tr> <td colspan="7" style="padding: 0 !important;"> <div … -
django signals does not save m2m model field
// signals.py @receiver(pre_save, sender=AcademicLesson) def take_attendance(sender, instance, **kwargs): new_file = instance.class_img if new_file: sub = instance.sub_id # this for loops gives all student from each branch having comman subject(sub = instance.sub_id) for branch in sub.universitybranch_set.all(): for std in branch.studentprofile_set.all(): if std.profile_encode: # for understanding, student present or not print('-------------------------added') instance.student.add(std) else: print('---------------------not-added') print('no. of student=', len(instance.student.all())) # // models.py class AcademicLesson(models.Model): date = models.DateField() sub_id = models.ForeignKey('UniversitySubject', on_delete=models.CASCADE, limit_choices_to={'is_elect': True}) class_type = models.CharField(max_length=7, choices=[('lecture','Lecture'),('lab','Lab')]) slot = models.CharField(max_length=1, choices=[('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6','6')]) class_img = models.ImageField(upload_to=path_to_upload_media, blank=True) student = models.ManyToManyField('StudentProfile', blank=True) def __str__(self): return f"{self.date} | {self.sub_id}" class Meta: verbose_name = 'Academic Lesson' form which I submited from admin panel debug console look like whene I verify with django shell, it return <QuerySet []> lesson = AcademicLesson.objects.get(date='2021-04-05') lesson.student.all() what I tried. override models.Model.save method but same problem occurs. forms.ModelForm does not suitable for our project If I run code shown in signals.py in django shell then it work properly but, same logic does not work in signals.py where did I go wrong? -
Django pass parameters to URL in render
I'm building a commerce site and the user could access any listing through site_url/<id:listing_id>. Through the listing page, the user can bid on an item. If the form is valid, the user is redirected to the same listing page using the following logic return HttpResponseRedirect(reverse("listing", args=[listing_id])) However, if the form is not valid (the new bid is less than the current bid), the user should be redirected to the main page and an error message should be shown. I figured out that I may have to use render function to pass a context which will include the message to be displayed in HTML template. However I couldn't pass the listing id. This is the logic of this function: def listing_page(request, listing_id): """Shows the listing page based on id""" if request.method == "POST": # Create a form instance and populate it with data from the request: form = BidForm(request.POST) if form.is_valid(): # Get the current bid current_bid = Listing.objects.get(pk=listing_id).current_bid # Get the new bid from the cleaned_data new_bid = form.cleaned_data["bid"] # If the new bid is less than the current, return an error if new_bid < current_bid: return render(request, "auctions/listing.html", listing_id=listing_id) # Here I failed # Save a new bid object … -
Problem not display datetime field form in browser in django
What I can't see input datetime form.form django in my browser? Thank you for your reply forms.py forms.py views.py views.py my_html.py my_html.py browser page browser page -
Django: Reference user's first_name using AbstractUser?
My goal is to add non-authentication values to a user. Like, bio, nationality, etc. I am trying to use a custom user model. I am having trouble accessing the values. I can use the new ones I created, but not the original ones like first_name, last_name, email. my model.py looks like from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.CharField(max_length=500, blank=True) phone = models.CharField(max_length=20, blank=True) Settings.py I added: AUTH_USER_MODEL = 'publication.User' INSTALLED_APPS = [ 'publication.apps.PublicationConfig, ... My admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) How to I add bio and nickname to the admin page? And how do I access first name, email, bio, phone outside in forms and such? Many thanks. -
Django - Changing a graph using dropdown values
I have a pandas dataframe (created by pulling data from an API) that has information on various assets, such as name, price, time, volume, ect. My goal is to display a graph that changes based on information that a user selects in a couple dropdowns above, such as name and a time range. On a high level, I'm a bit unsure on how to begin implementing this. Should I render the graph in views and connect those views to the app html file? Should I store the dataframe in some sort of SQL database via the models file? Any and all information or examples for implementing this idea would be appreciated. -
test async task that retries a couple of times and revokes if fails
I want to test a task that is called 5 times incase there's an error, and the worker stops after that. Below is my code: @app.task(bind=True) def my_func(self): try: print('---------retrying') try: # check if the object exists and do something except Exception as exc: # some other thing my_func.retry(max_retries=5, countdown=15) return False except MaxRetriesExceededError as mexc: print('*****revoking') revoke(task_id=self.request.id, terminate=True, state='REVOKED') tests.py class TestTasks(TestCase): @patch('app.tasks.my_func') @override_settings(CELERY_ALWAYS_EAGER=True) def test_my_func(self, mock): # create an object my_func() assert mock.assert_called_once() The test crashes with an error that Expected 'my_func' to have been called once. Called 0 times. Please help Thanks in advance. -
Connection refused error when using Stripe webhooks
I'm constantly getting a connection refused error when trying to receive webhooks. (venv) alexa@main:/etc/nginx/sites-available$ stripe listen --forward-to localhost:5000/webhook/ go package net: built with netgo build tag; using Go's DNS resolver > Ready! Your webhook signing secret is whsec_************************* (^C to quit) 2021-04-05 18:13:03 --> customer.subscription.updated [evt_1Icwv5HrsuAsSZROjKy4Z5CK] 2021-04-05 18:13:03 [ERROR] Failed to POST: Post "http://localhost:5000/webhook/": dial tcp 127.0.0.1:5000: connect: connection refused) The port is enabled through my firewall: To Action From -- ------ ---- 5000 ALLOW Anywhere 5000/tcp ALLOW Anywhere 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 443/tcp ALLOW Anywhere 5555 ALLOW Anywhere 5000 (v6) ALLOW Anywhere (v6) 5000/tcp (v6) ALLOW Anywhere (v6) 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 443/tcp (v6) ALLOW Anywhere (v6) 5555 (v6) ALLOW Anywhere (v6) My webapp is running on Ubuntu 20.10 -
django development show plugin (DjangoQLSearchMixin) but not in production
I have a develop env (local run on windows pycharm terminal with --insecure set) that is working properly with this plugin DjangoQLSearchMixin - I can see it on the search engine. But for some reason it is not activated on the production admin panel (nginx + ubunto + django). The code is the same, not sure what went wrong. Maybe I need to recreate static files ? Suggestions ? -
'ReverseManyToOneDescriptor' object has no attribute 'filter'
'ReverseManyToOneDescriptor' object has no attribute 'filter' why?) I'm trying to create a blog in django, got to the stage of adding comments and categories and got stuck I get an error. views.py from django.shortcuts import render, get_object_or_404 from .models import Post, Comment from django.views import generic from django.http import HttpResponse from .forms import CommentForm def blog_list(request): post = Post.objects.all().order_by('-date') return render(request,'blog/blog_list.html', {'posts':post}) def blog_detail(request, slug): #return HttpResponse(slug) detail_post = Post.objects.get(slug=slug) comments = Post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render(request,'blog/blog_detail.html', {'detail_post':detail_post, 'comments':comments, 'new_comment': new_comment, 'comment_form': comment_form}) I hope someone helps, also with the problem of adding a category 14.comments = Post.comments.filter(active=True) … ▶ Local vars here is my models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) first_src = models.CharField('первоисточник', blank=True, max_length=100) author = models.ForeignKey(User, on_delete= models.CASCADE ) thumb = models.ImageField(default='default.png', blank=True) # add AND GO TO MIGRATE AND MAKEMIGRATIONS … -
How do i serve Media files on production in Django in Apache
I currently have a Django site running on amazon lightsail, i ran python manage.py collectstatic an had all static files running fine but i have issues with my media files..i can't upload to my project. Below are my codes settings.py DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) /opt/bitnami/apache2/conf/vhosts/messages-http-vhost.conf (edited also for messages-https-vhost.conf) <IfDefine !IS_MESSAGES_LOADED> Define IS_MESSAGES_LOADED WSGIDaemonProcess messages python-home=/opt/bitnami/python python-path=/opt/bitnami/projects/messages </IfDefine> <VirtualHost 127.0.0.1:80 _default_:80> ServerAlias * WSGIProcessGroup messages Alias /robots.txt /opt/bitnami/projects/messages/static/robots.txt Alias /favicon.ico /opt/bitnami/projects/messages/static/favicon.ico Alias /static/ /opt/bitnami/projects/messages/static/ Alias /media/ /opt/bitnami/projects/messages/media/ <Directory /opt/bitnami/projects/messages/static> Require all granted </Directory> <Directory /opt/bitnami/projects/messages/media> Require all granted </Directory> WSGIScriptAlias / /opt/bitnami/projects/messages/messages/wsgi.py <Directory /opt/bitnami/projects/messages/messages> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> models.py message_audio = models.FileField(upload_to='audio/', null=True) message_image = models.ImageField(upload_to='message-pics/', null=True) When i try to upload a file i get "Server Error (500)" -
How to connect marg ERP api to django e-commerce website website database
I am working on a project in which client has multiple store and these store has its products with different price and category. Client has marg ERP api and he wont to connect his ERP to our django e-commerce database so that he managed all his sold product by website through ERP. Please help me to connect marg ERP api to my django project. -
Why can different URLs give the same result. Please advise where to look for the bug
I am not sure how to provide the code. I have "views", "models", "urls" files and don't know where to look. Here is my GitHub project link: https://github.com/zaliubovskiy/horder I presume that the bug is here: /horder/products/templates/search.html The "for" cycle probably wrongly linked <div class="product-list"> <div class="product-container"> {% for product in product_list %} <a href="{{ product.get_absolute_url }}" class="card"> <div class="image"> <img src="http://drive.google.com/uc?export=view&id={{ product.image }}" alt="image"> </div> <div class="title"> {{ product.name }} </div> </a> {% endfor %} </div> </div> -
How to eliminate Permission error in django xlrd
I try creating model fields by importing an excel with the details but get the permission errors. What could be the problem... The view. def UploadTeacherView(request): message='' if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['file'] try: import os import tempfile import xlrd fd, tmp = tempfile.mkstemp() # create two temporary file with os.open(fd, 'wb') as out: # create new file objects out.write(excel_file.read()) book = xlrd.open_workbook(tmp) print(book) sheet = book.sheet_by_index(0) obj=TeacherData( code = sheet.cell_value(rowx=1, colx=1), first_name = sheet.cell_value(rowx=2, colx=1), last_name = sheet.cell_value(rowx=3, colx=1), email = sheet.cell_value(rowx=4, colx=1), phone = sheet.cell_value(rowx=5, colx=1), ) obj.save() finally: os.remove(tmp) else: message='Invalid Entries' else: form = NewTeachersForm() return render(request,'new_teacher.html', {'form':form,'message':message}) Below is the error I get upon uploading a file. PermissionError at /teachers/upload [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\FRGULI~1\\AppData\\Local\\Temp\\tmpm87yli8l' -
How to delete a row in table with Django
I am new in Django. I am trying to add a delete button to delete the row. However, the output is not what I want because it outputs multiple times because I create a loop to get data for other columns. For this reason, is there a solution the delete button can run outside the loop? add_stock.html {% extends 'base.html' %} {% block content %} <h1>Add Stock</h1> <form action="{% url 'add_stock' %}" class="form-inline my-2 my-lg-0" method='POST'> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="Add Stock" aria-label="Search" name="ticker"> <button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Add Stock</button> </form> <br/> <table class="table table-striped table-bordered"> <thead> <tr> <th scope="col">Symbol</th> <th scope="col">Company Name</th> <th scope="col">Last</th> <th scope="col">Extended Hours</th> <th scope="col">Change</th> <th scope="col">% Change</th> <th scope="col">Volume</th> <th scope="col"></th> </tr> </thead> <tbody> {% if ticker %} {% for list_item in output %} {% for item in ticker %} <tr> <th scope="row"> {{ list_item.symbol }} </th> <td>{{ list_item.companyName }}</td> <td>${{ list_item.latestPrice }}</td> <td>${{ list_item.extendedPrice }}</td> <td>{{ list_item.change }}</td> <td>{{ list_item.changePercent }}%</td> <td>{{ list_item.volume }}</td> <td><a href=" {% url 'delete' item.id %} "> Delete </a></td> </tr> {% endfor %} {% endfor %} </tbody> </table> {% endif %} urls.py from django.urls import path from . import views urlpatterns = [ path('', … -
Forgot Password - Django Rest Framework
I need to create an endpoint that sends the token to reset the lost password in Django Rest Framework, for that I installed the django-rest-passwordreset package and followed the steps below: However, when accessing the endpoint created with the POST method with the email in the body, it does not even return the token in the terminal, much less send the email, what am I doing wrong? settings.py: INSTALLED_APPS = [ ... 'rest_framework', 'django_rest_passwordreset', ] EMAIL_BACKEND = 'django_amazon_ses.EmailBackend' AWS_SES_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', None) AWS_SES_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', None) AWS_SES_REGION = 'us-east-1' urls.py: from django.urls import path, include urlpatterns = [ ... path('api/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), ] models.py: from django.dispatch import receiver from django.urls import reverse from django_rest_passwordreset.signals import reset_password_token_created from django.core.mail import send_mail @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): email_plaintext_message = "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key) send_mail( # title: "Password Reset for {title}".format(title="Some website title"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: [reset_password_token.user.email] ) Execute in my venv: python manage.py migrate -
Python application doesnt work on GoDaddy Shared Hosting after SSL Certifcate change
I had my django application hosted on the GoDaddy shared hosting platform which i set up using the SetUp Python Application. It was all working fine but then the free CloudFare SSL certificate. Hence i had to rename the DNS servers and replace the old Cloudfare SSL certificate with a new GoDaddy SSL certificate. But since then the website has been showing Incomplete response received from application. I called goDaddy support but they asked me to check my code. I did and I find no issues in it. I am unable to find the reason behind this issue. When i checked the network tab, it is showing a 502 error. The link to my website is Mint Chalk Media Can anyone pls help me find a solution? -
Django best practice for varying querysets dependant on user permissions and database values
I am new to Django and just trying to work out the best way of implementing some business logic. I am representing access to AV devices in a building with multiple floors. Each floor is leased by a separate tenant. Each tenant has one or more users than can access one or more of the AV devices on the floor. There is a tenant admin responsible for defining the users and their devices per tenancy. I have three roles - superuser, tenant admin and tenant user. I have a set of tables in the DB that define the floors, AV objects on the floors and which tenants can access which objects. The admin of this in Django works fine. I now want to display this in a simple front end so that the following is possible: super user - sees each floor and then can see devices on a selected floor and operate them tenant admin - sees just their floors and can operate all devices on their floor(s) tenant user - sees just the floor and devices they have been allocated access to To my mind this can all be done in one one template with some view based … -
Django: annotate count of replies by user through relation of field
I am struggling with this queryset for days, here's the model with three classes, User, Category, Post: from django.db import models from django.db.models.deletion import CASCADE class User(models.Model): name = models.CharField() @property def most_reply_to(self): return self.post_setvalues('reply_to')\ .annotate(reply_to_count=Count('user'))\ .order_by('user') @property def most_replied_by(self): pass class Category(models.Model): name = models.CharField() class Post(models.Model): title = models.CharField() user = models.ForeignKey(on_delete=models.CASCADE) category = models.ForeignKey(on_delete=models.CASCADE) url = models.URLField() reply_to = models.URLField() The reply_to filed contains the information of user interactions, unfortunately it's not ForeignKey'ed to the Post model itself, but only to point to the url field of other post. What I'd like to achieve here, is to annotate each user with: the counts of replies received, grouped by (source) user; the counts of replies given to, grouped by (target) user; For the most_reply_to method, I have experimented as seen in my code, but the code only gave me count of replies to each individual post (from the user), not the total count of replies to each other users, I have lost in the aggregate/annotate logic here. For the most_replied_by method, I understand I need to start with the entire Post.objects.all() queryset, but I have no clue as how should I filter out those that are replies to … -
How to paginate a class-based list view with django-filters
Do you guys know how to paginate a generic class-based ListView that uses django-filters as a search bar? When I read some articles regarding this issue(which wasn't a lot for class-based views), it seems that django-filters and pagination don't work together very well. Here is my view: class StudentListView(OrganisorAndLoginRequiredMixin, generic.ListView): template_name = "leads/student_list.html" context_object_name = "leads" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = StudentFilter(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self): organisation = self.request.user.userprofile return Lead.objects.filter(organisation=organisation).order_by('first_name') I would really appreciate it if you guys could tell me what code I need to write for my view as well as what code I need to add into my template to make this work. I don't think the code for the actual filter and the template is necessary, but if you guys need it, I can add it to this question. Thanks.