Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How store csv file details into a django model
how solve this? how to store the csv file details(not csv file data) like file name,uploaded name,No. of rows into a another django table or model. -
how do i see data by using django listview at chrome
I used listview and confirmed that there was a query set in the terminal. I want to see that data on the Internet. However, even though there is data, row of the table is not added. What should I do? It's so frustrating. I couldn't do anything for five hours because of this. plz heeeeelp me...! # html {% extends 'branches/package-create.html' %} {% block nav %} <form method="get" enctype="multipart/form-data"> {% csrf_token %} {% for i in ps %} <tr class="content-tr"> <td class="td1">{{ i.package_recommandation_date }}</td> <td class="td2">{{ i.package_payment_date }}</td> ... </tr> {% endfor %} </form> {% endblock %} # MODELS.PY class PayHistory(models.Model): branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=True) package_recommandation_date = models.DateField(null=True) package_payment_date = models.DateField(null=True) ... # views.py class PackageListView(ListView): template_name = 'branches/package-get.html' model = PayHistory def get_queryset(self): p=PayHistory.objects.all() print(p) return p # TERMINAL <QuerySet [<PayHistory: PayHistory object (1)>, <PayHistory: PayHistory object (2)>]> -
dajango AttributeError at / 'WSGIRequest' object has no attribute 'get'
This is my views.py from django.shortcuts import render import requests # Create your views here. def mainfun(requests): city="London" url=f"http://api.weatherapi.com/v1/current.json?key=69528a98f894438b88982548221507&q={city}&aqi=no" data= requests.get(url) return render(requests,"index.html",{'d':data}) This is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'weatherapp', ] 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 = 'weather.urls' requests is not working when try to get data from the api.. How to solve this problem..? -
Django selenium: StaticLiveServerTestCase => 'admin' user can not login
I try to use StaticLiveServerTestCase and fixtures. I have created 7 users using fixture and one of them, 'admin' is_superuser=True. My tests pass for all of users except admin that failed to login. I've checked password of admin at the begining of the test method, and I don't know how but (1) password do not correspond to the password set in fixture and (2) password change every runs. That explain failed in login but why only this user has such a behavior? If I try to connect in my dev environnement, using database containing fixtures datas, it works... I try to change is_superuser to false, or 'admin' username with 'myadmin' if there could be a side effect but none works... tests.py class L_access_menu_creation_patient_TestCase(StaticLiveServerTestCase): fixtures = ['dumpdata.json'] @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(1) cls.selenium.maximize_window() cls.date_saisie = timezone.now() cls.selenium.get(cls.live_server_url) # le menu "Ajouter un patient" est disponible (id=menucreate) def test_menu_create_available_admin(self): # ----------------------------------------- connexion ------------------------------- self.admin = User.objects.get(username='admin') print('admin',self.admin.username,self.admin.password) # envoie de données d'identification username_input = self.selenium.find_element_by_name("username") username_input.send_keys('admin') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('admin') fixture dumpdata.json ... { "model": "auth.user", "fields": { "password": "pbkdf2_sha256$150000$qe1v2XJKkik8$jF6iFZ+4GpK1JzBdHzRG0H3XsYY+YphYpxc9Cbgg+7Y=", "last_login": null, "is_superuser": true, "username": "admin", "first_name": "", "last_name": "", "email": "", "is_staff": true, "is_active": true, "date_joined": "2022-03-15T08:32:13.528Z", "groups": … -
Django Mnagement Command conditional command
I am trying to give the command like this, I could not successfully implemmented this bold text condition. (if blacklist == true and active is = false ) (else: no action) 'from django.core.management import BaseCommand from wm_data_collection.models import roses class Command(BaseCommand): help = "Blacklist_TRUE then Active_FALSE." def handle(self, *args, **options): roses.objects.filter(active=False).update(blacklist=True)' -
I am using a service now API for fetching the incident details, but the service now is SSO enabled and my Django request is failing
I am using a service now API for fetching the incident details, but the service now is SSO enabled and my request is failing. Please let me know how to authenticate the APIs -
Django modelform clean_password2
Stumbled this def clean_password2 ModelForm. My question is does every time this we run this view. Does it will automatically run clean_password2 to check the password or do we need to explicitly call it? Form.py class RegisterForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name', 'email',) #'full_name',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.is_active = False # send confirmation email via signals # obj = EmailActivation.objects.create(user=user) # obj.send_activation_email() if commit: user.save() return user https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#a-full-example -
How do i efficiently use redux in react making request to backend server?
I am new to using react and also new to redux, I am working on a project which uses Django for Back-end and React for Front-end. I want to use redux for data state management but i can not seem to be doing it right. Here is my action transaction.js function: import axios from "axios"; export const CREATE_TRANSACTION = "CREATE_TRANSACTION"; export const VIEW_TRANSACTION = "VIEW_TRANSACTION"; export const UPDATE_TRANSACTION = "UPDATE_TRANSACTION"; export const LIST_TRANSACTIONS = "LIST_TRANSACTIONS"; export const DELETE_TRANSACTION = "DELETE+TRANSACTION"; export const GET_TRANSACTIONLIST_DATA = "GET_TRANSACTIONLIST_DATA"; const ROOT_URL = "http://127.0.0.1:8000/api/"; export const getTransactionList = () => (dispatch) => { axios .get(`${ROOT_URL}transactions/`, { headers: { "Content-Type": "application/json", }, }) .then((response) => { dispatch({ type: LIST_TRANSACTIONS, payload: response.data }); console.log(response.data); }); }; Here is my reducer transactions.js function: import { LIST_TRANSACTIONS } from "../actions/transaction"; export function TransactionReducer(state = {}, action) { switch (action.type) { case LIST_TRANSACTIONS: return action.payload; default: return state; } } My store.js: import { createStore, applyMiddleware, compose } from "redux"; import thunk from "redux-thunk"; import rootReducer from "./reducers"; const initialState = {}; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ latency: 0 }) : compose; const store = createStore( rootReducer, initialState, composeEnhancers(applyMiddleware(thunk)) ); export default store; Trying to display data using useSelector() … -
Python/Django - Input radiobutton to autosend email
I'm trying to set up a radiobutton input that let's you choose to send email automatically. What I want is a form that gives input: manual or auto. This will the one row I have in the sqlite3 database for this: class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") So eventually what I want is that in AutoSendMail the type is set to manual or auto, depending on the radiobutton input. I got as far as this: mailindex.html <form action="." method="post" class="card"> {% csrf_token %} <div class="card-body"> <div class="form-group text-right"> <label class="form-label">Send E-mail Automatically</label> <!--<input type="email" class="form-control" placeholder="reply to" value="{{mail.replyTo}}" name="replyTo">--> <input type="radio" name="sendauto" value="On"> Manual <input type="radio" name="sendauto" value="Off"> Auto {{ form.type }} </div> <div class="card-footer text-right"> <input type="submit" value="Submit" name="autoapprove" class="btn btn-primary" /> </div> </div> </form> urls.py path('mailbox/auto_send/', login_required(views.AutoSendView.as_view()), name='auto_send'), forms.py class SendMailSetting(ModelForm): class Meta: model = AutoSendMail fields = ['auto', 'manual', 'type'] widgets = { "manual": DjangoToggleSwitchWidget(klass="django-toggle-switch-dark-primary"), "auto": DjangoToggleSwitchWidget(round=True, klass="django-toggle-switch-success"), 'type': forms.RadioSelect() } models.py class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") views.py class AutoSendView(generic.TemplateView): form_class = SendMailSetting model = AutoSendMail … -
Django: base.html "TemplateDoesNotExist at / error" and project structure
When in my home.html (or any other .html) I try to extend my base.html file with this {% extends "static/src/base.html" %} I get this error: TemplateDoesNotExist at / error Also, I'm about to start my first "serious" project and so I'm trying to do things a little less amateurish starting with my project structure. This is what I've come so far following the clues I got from other site, but I'd like to have some opinion from people with more experience than me if this is a good way to start the project. In particular, I'm a little confused about where to put the base.html file. Is it ok to put it in the src folder or should I put it with the navbar.html/footer.html/etc page or navbar.html/footer.html/etc should go in the src folder instead? This is my project structure: website_name - core (where is the settings.py and where I put homepage, news page, contact and about us page...) - app name_1 (like members) - app name_2 - media -- img -- upload (user ulploaded excel file) --- excel_file.csv -- download (for user to download file) - static -- src --- base.html --- style.css -- dist --- style.css -- node_modules -- … -
Is Django or Flask better for implementing "tracker nodes" and "seeder nodes" for p2p content sharing application?
The image below shows an architecture for video sharing based on the p2p BitTorrent protocol. The video player access the "content tracker" for "video" info The content tracker responds with "content node" info. The video is served from the nearest one or two nodes How should I approach building this network? Should I create a BitTorrent client at content nodes and give them a private "content tracker" address? If I have to expand the three-node structure to 10, what should be the approach while building this kind of software. Which tech stack would be best? If you can share some resources, that would be helpful. I am a newbie; kindly be kind. :) -
Django "ImageField" form value is None
I'm trying to implement profile picture field for users. The following is the code for each file for the implementation I tried, forms.py, models.py, views.py, and urls.py. I use a IDE (vscode) to debug django, and I placed a breakpoint on the user.avatar = form.cleaned_data['avatar'] line in views.py below, to quickly check if cleaned_data['avatar'] is filled as user input, as I expect. However, even after I upload a file on the url, submit, the line shows None while expected a image object, and of course it doesn't save anything so no change to the database either. # # forms.py # accounts/forms.py # from accounts.models import UserProfile # .. class UserProfileForm(forms.ModelForm): avatar = forms.ImageField(label=_('Avatar')) class Meta: model = UserProfile fields = [ 'avatar', ] def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['avatar'].required = False # # models.py # accounts/models.py # from django.contrib.auth.models import User from PIL import Image class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to="images", blank=True, null=True) # note: I also did "python manage.py makemigrations accounts; python manage.py migrate accounts;" # # views.py # accounts/views.py # class UserProfileView(FormView): template_name = 'accounts/profile/change_picture.html' form_class = UserProfileForm def form_valid(self, form): user = self.request.user user.avatar = form.cleaned_data['avatar'] user.save() messages.success(self.request, _('Profile picture has been … -
Celery upgrade from 4.4.6 to 5.1.2 fails with error DatabaseError: ORA-00904: "DJANGO_CELERY_BEAT_PERIODI5B67"."EXPIRE_SECONDS": invalid identifier
I have a working DJango application with python 3.7.12 django==2.2.24 celery==4.4.6 django-celery-beat==1.5.0 I need to upgrade celery to celery==5.1.2 django-celery-beat==2.2.0 I get below error after upgrading the libraries. Exception in thread django-main-thread: Traceback (most recent call last): File "/home/ssin/workspace/djapp/venv3712/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/ssin/workspace/djapp/venv3712/lib/python3.7/site-packages/django/db/backends/oracle/base.py", line 510, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-00904: "DJANGO_CELERY_BEAT_PERIODI5B67"."EXPIRE_SECONDS": invalid identifier I tried to recreate the migration and run the migrations but that also failed with same error. python manage.py makemigrations python manage.py migrate django_celery_beat -
Host both PHP/JS and Django applications with Apache on Windows
I have a WAMP Server 3.2 (Apache 2.4.46) installed on Windows 10 (64-bits), it is exposed to the local company network. I use it to host ordinary php/js applications. My httpd-vhosts.conf is used to look like this: <VirtualHost *:80> ServerName RealNameOfTheServer DocumentRoot "d:/projects" <Directory "d:/projects/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> Now I got a Django app which preferably needs to be hosted with the same server (since I don't have any other) along with other php applications. I tried to follow the example to configure my virtual hosts, but it uses daemon process which is not available on Windows. My httpd-vhosts.conf after applied changes makes Django app work correctly but dumps php/js apps. <VirtualHost *:80> ServerName RealNameOfTheServer DocumentRoot "d:/projects" <Directory "d:/projects/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> WSGIPassAuthorization On ErrorLog "logs/dashboard.error.log" CustomLog "logs/dashboard.access.log" combined WSGIScriptAlias / "d:\projects\dashboard\dashboard\wsgi_windows.py" WSGIApplicationGroup %{GLOBAL} <Directory "d:\projects\dashboard\dashboard"> <Files wsgi_windows.py> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Files> </Directory> Alias /static "d:/projects/dashboard/static" <Directory "d:/projects/dashboard/static"> Require all granted </Directory> </VirtualHost> Is there any way to run both php and Django apps on Windows? -
how to fix error code H10 in heroku with python
i've seen other posts saying to do things with the Procfile but nothing has worked for me when i try to run my server with heroku, I receive this error: at=error code=H10 desc="App crashed" method=GET path="/" host=d1sbot.herokuapp.com request_id=33508569-4287-462f-86b4-12e9a8c6dca8 fwd="150.101.163.59" dyno= connect= service= status=503 bytes= protocol=https my requirements.txt looks like this: asgiref==3.5.0 Django==4.0.3 gunicorn==20.1.0 sqlparse==0.4.2 whitenoise==6.0.0 my settings.py file looks like this: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-#2%rkkxk6&nmlzk-0lc2aw-n@&)dt1o_g)f5e=i6a611*6u3@1' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ '127.0.0.1', 'd1sbot.herokuapp.com', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'botfiles.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(MAIN_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 = 'botfiles.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password … -
How can I display the price of each item Django
I'm trying to return the price of each item but depending on these conditions. i. If no user has placed a bid on the item, return starting bid ii. If a user has placed a bid on the item, update the starting bid to the new bid amount I have tried the below but it is not reflecting the new amount when a user places a bid on the item. DETAILS.HTML <div> <h5>{{ listing.title }}</h5> <hr> <p>{{ listing.description }}</p> <hr> <p>Current price: ${{ listing.bid }}</p> VIEWS.PY def make_bid(request, listing_id): listing = Auction.objects.get(pk=listing_id) bid_item = Bids.objects.filter(auction=listing).order_by('-new_bid').first() #if theres no bid available, use starting bid, if available, update to the latest bid if bid_item == None: bid = listing.starting_bid else: bid = bid_item.new_bid if request.method == 'POST': bid_form = BidForm(request.POST, listing=listing) if bid_form.is_valid(): accepted_bid = bid_form.save(commit=False) accepted_bid.user = request.user accepted_bid.save() messages.success(request, 'Successfully added your bid') return redirect('listing_detail', listing_id=listing_id) else: context = { "bid_form": bid_form, "bid": bid, "bid_item": bid_item, "listing": listing } return render(request, 'auctions/details.html', context) return render(request, 'auctions/details.html', bid_form = BidForm()) FORMS.PY class BidForm(forms.ModelForm): class Meta: model = Bids fields = ['new_bid'] labels = { 'new_bid': ('Bid'), } def __init__(self, *args, **kwargs): self.listing = kwargs.pop('listing', None) super().__init__(*args, **kwargs) def clean_new_bid(self): new_bid = … -
<header> <body> and <footer> tags don't work properly xhtml2pdf | django
I'm using xhtml2pdf to render an html page to pdf and I would like to have a page header and a page footer which repeats for every new page. I've tried to use the tag <header> and <footer> of html but actually these don't work: they just show up in the page right in the position I wrote the code. Any idea of which could be the problem? I've also problems in the pagination: I've already looked in stackoverflow for similar questions but I couldn't handle the problem. -
django + apache + moviepy - MoviePy error: FFMPEG encountered the following error while writing file
I am trying to extract audio from a video uploaded using moviepy. The code works well during development but i keep getting error after deploying the django app. def extract_audio(object_id): """This function extracts audio from video""" # Get the object translator_object = Translator.objects.get(pk=object_id) old_audio_file_path = '' if translator_object.source_audio: old_audio_file_path = translator_object.source_audio.path # raise exceptions if not translator_object: raise Exception("Object not found") if not translator_object.source_video: raise Exception( "Video file not available, try again!") if not os.path.isfile(translator_object.source_video.path): raise Exception( "Video file not available, try again!") video_clip = VideoFileClip(translator_object.source_video.path) new_audio_file_path = str(uuid4())+'.wav' video_clip.audio.write_audiofile(new_audio_file_path) translator_object.source_audio = File(open(new_audio_file_path, "rb")) translator_object.save() try: os.unlink(new_audio_file_path) if os.path.isfile(old_audio_file_path): os.unlink(old_audio_file_path) except: print('Deleting error..') error: OSError at /admin/translator/translator/ [Errno 32] Broken pipe MoviePy error: FFMPEG encountered the following error while writing file 162f5850-943b-483b-b97d-2440cc84a2ef.wav: b'162f5850-943b-483b-b97d-2440cc84a2ef.wav: Permission denied\n' In case it helps, make sure you are using a recent version of FFMPEG (the versions in the Ubuntu/Debian repos are deprecated). Request Method: POST Request URL: https://felix-projects.eastus.cloudapp.azure.com/admin/translator/translator/ Django Version: 3.2.10 Exception Type: OSError Exception Value: [Errno 32] Broken pipe MoviePy error: FFMPEG encountered the following error while writing file 162f5850-943b-483b-b97d-2440cc84a2ef.wav: b'162f5850-943b-483b-b97d-2440cc84a2ef.wav: Permission denied\n' In case it helps, make sure you are using a recent version of FFMPEG (the versions in the Ubuntu/Debian repos are … -
Authorize.net SDK support for Python 3.10
Authorize.net official Github SDK doesn't work as the collections module is deprecated in python. Authorize.net official SDK is not active for months. Will they support the new version of python or do we have to look for a new payment gateway that supports Python 3.10. -
Detection fake profil by using keystroke dynamics
Hello i need to create a Web site for détections of importer bye usine keystroke dynamics biometric i have to do it with python and django for the authentification and also to have idea of the way of writting of my user speech, slowly -
I want i hash my password but some fields should not be required
Please help as soon as posible Please Please Please In django validation when I signup, i don't want to validate some fields becouse the are not required, but if i am creating user from another page there i want those fields, so how to do unrequired some fields class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "username", "password" ,"first_name", "last_name","email", "User_Type","url","sign_up_count", "facebook", "twitter", "linkedin", "instagram", "telegram", "discord", "snapchat"] def create(self, validated_data): user = User( email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], username=validated_data['email'], User_Type=validated_data['User_Type'], facebook=validated_data['facebook'], twitter=validated_data['twitter'], linkedin=validated_data['linkedin'], instagram=validated_data['instagram'], telegram=validated_data['telegram'], discord=validated_data['discord'], snapchat=validated_data['snapchat'], ) user.set_password(validated_data['password']) user.save() return user when i signup a account i dont want facebook, telegram and more..., but if i am creating user from another page that time i neet it. so how to set unrequired thes fields for validate Please help as soon as posible please please please -
Django: Filter by less verbose (database name) on TextChoices class
I have a model: class RegulationModel(models.Model): class Markets(models.TextChoices): EUROPE = 'E', 'Europe' US = 'US', 'US' JAPAN = 'J', 'Japan' KOREA = 'K', 'Korea' BRAZIL = 'B', 'Brazil' INDIA = 'I', 'India' CHINA = 'C', 'China' market = models.CharField(verbose_name='Market:', max_length=2, choices=Markets.choices) [... more fields ..] How do I filter on the more verbose choice in the Markets class? For example say I want to filter with "China", i'd like to do something like: regulation = RegulationModel.objects.get(market__verbose='China') (I know this isn't possible but it's just to get an idea) The reason why I am doing this is because I am getting the choice from AJAX therefore the format is not ["C","US"] .etc. I wouldn't mind a suggestion which would allow me to convert my choice "China" --> "C" and then load this variable into the filter. -
Reset password view without using FormViews in django
I am trying to set a reset password view without using the reset FormViews that Django uses by default. This means that I don't really use the auth application, more than for the tokens and some other small stuff. What I did now is a normal view that displays an email/username form, and send an email to the user with a token: password_reset_token = PasswordResetTokenGenerator() def sendPasswordResetEmail(user, current_site): mail_subject = 'Password reset' message = render_to_string('myapp/password_reset_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': password_reset_token.make_token(user), }) to_email = user.email email = EmailMessage(mail_subject, message, from_email='testing@testing.com', to=[to_email]) email.send() After this, the user should be displayed with a view that asks for the user to fill a SetPasswordForm if the token is correct and it's a GET request. Or it should check for the token and check if the form is valid. If the form and token are valid then the password should be changed. I am trying to replicate a bit Django's PasswordResetConfirmView, but I'm not really sure if I'm doing it right. This is how I would do it, but I can't tell if there's any way to exploit the view somehow: def passwordResetConfirm(request, uidb64, token): if request.user.is_authenticated: return redirect("decks:index") try: uid … -
How to render results from groupby query in html - Django
I'm trying to render results of a group by query from a view to an HTML table but it is returning nothing. I originally had success in listing all results, but after applying the sum aggregation I can't get it to appear. Django View - with Group By def get_asset_price(request): # CryptoAssets is the model obj = CryptoAssets.objects.filter(user_id=request.user.id).values('symbol') obj = obj.aggregate(total_units=Sum('units'), total_cost=Sum('cost'))\ .annotate(total_units=Sum('units'), total_cost=Sum('cost'))\ .order_by('symbol') # Returns list of dictionaries context = { 'object': obj } return render(request, 'coinprices/my-dashboard.html', context) HTML <style> table, th, td { border: 1px solid black; } </style> <div class="container"> <h1>My Dashboard</h1> <table> <tr> <th>Symbol</th> <th>Total Units</th> <th>Total Cost</th> </tr> {% for row in object.obj %} <tr> <td>{{ row.symbol }}</td> <td>{{ row.units }}</td> <td>{{ row.cost }}</td> </tr> {% endfor %} </table> </div> {% endblock %} I'll provide the view below that worked without the group by. Django View - No group by def get_asset_price(request): # CryptoAssets is the model obj = CryptoAssets.objects.all().filter(user_id=request.user.id) # Returns list of objects context = { 'object': obj } return render(request, 'coinprices/my-dashboard.html', context) -
django-filter fieldset dependent on related field polymorphic ctype
class RelatedPoly(PolymorphicModel): common_field = ... class QweRelatedPoly(RelatedPoly): qwe = ... class RtyRelatedPoly(RelatedPoly): rty = ... class A(Model): related_poly = OneToOneField(RelatedPoly, ...) I also have a ViewSet for A model, and I need to implement a filterset_class which should be able to filter by both qwe and rty fields of RelatedPoly subclasses. In which ways could I achieve this?