Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unsure of how to manage email configurations
I am attempting to create Reset Password functionality using Djoser. I am successfully hitting my API's auth/users/reset_password/ endpoint, which is then sending an email as expected. But the problem is occurring in the content of the email. It is sending a redirection link to my api, rather than to my frontend. Please note, any <> is simply hiding a variable and is not actually displayed like that Here is an example of what the email looks like: You're receiving this email because you requested a password reset for your user account at <api>. Please go to the following page and choose a new password: <api>/reset-password/confirm/<uid>/<token> Your username, in case you've forgotten: <username> Thanks for using our site! The <api> team The goal with this email is to send the user to the /reset-password/confirm/ url on my frontend, not on my api, which is currently occurring. Here are my DJOSER settings: DJOSER = { 'DOMAIN': '<frontend>', 'SITE_NAME': '<site-name>', 'PASSWORD_RESET_CONFIRM_URL': 'reset-password/confirm/{uid}/{token}', } The expected behavior is for the DOMAIN setting to alter the link that is being placed in the email, but it is not. I can't seem to find reference to this particular problem within the docs. Any help here would … -
Book choices django
My models: class Book(models.Model): # book types and placed BIOGRAFIA = 1 FANTASTYKA = 2 HISTORYCZNY = 3 HORROR = 4 POEZJA = 5 PRZYGODA = 6 ROMANS = 7 DRAMAT = 8 BRAK = 0 B00K_CHOICES = ( (BIOGRAFIA, 'Biografia'), (FANTASTYKA, 'Fantasy/Sci-Fi'), (HISTORYCZNY, 'Historyczny'), (HORROR, 'Horror'), (POEZJA, 'Poezja'), (PRZYGODA, 'Przygoda'), (ROMANS, 'Romans'), (DRAMAT, 'Dramat'), (BRAK, 'Brak informacji'), ) gatunek = models.IntegerField(choices=B00K_CHOICES, default=BRAK) My views: @login_required def gatunek_lista(request): ksiazki = Book.objects.all() return render(request, 'ksiazki.html', {'ksiazki': ksiazki, 'gatunek': Book.B00K_CHOICES}) My template: For sure something is wrong here for gatunek in B00K_CHOICES: print(choice) ('Biografia', 1, 'Biografia'), ('FANTASTYKA', 2, 'Fantasy/Sci-Fi'), ('HISTORYCZNY', 3, 'Historyczny'), ('HORROR', 4, 'Horror'), ('POEZJA', 5, 'Poezja'), ('PRZYGODA', 6, 'Przygoda'), ('ROMANS', 7, 'Romans'), ('DRAMAT', 8, 'Dramat'), I have a question, how to make my template (html) show all options = B00K CHOICE Please help -
Authentication always return none even though username and password is correct with the database - DJANGO
Before that , i want to say that i already see for many solutions and it still not working , thats why i ask this question So i try to make a login form and a login module , when i insert the username and password correctly -> i already copy the value from the database so it will same 100% ---> but authentication always return none i already print the value into the cmd and what i put is the same as the value in database .. this is the login.html <div id="login-page"> <div class="container"> <form class="form-login" method="post"> {% csrf_token %} <h2 class="form-login-heading">sign in now</h2> <div class="login-wrap"> <input type="text" name="username" class="form-control" placeholder="User ID"> <br> <input type="password" name="password" class="form-control" placeholder="Password"> <br> {% if messages %} <ul class="messages"> {% for message in messages %} <font color="red"><li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li></font> {% endfor %} </ul> {% endif %} <button class="btn btn-theme btn-block" type="submit" href=""><i class="fa fa-lock"></i> SIGN IN</button> <hr> </form> </div> </div> and this is the views for login and register def login_view(request): if request.method == 'POST': print("yes") username = request.POST.get('username') password = request.POST.get('password') print(username) print(password) guest = User.objects.get(username=username) rolee= UserProfileInfo.objects.get(user_id = guest.id).role print(rolee) user … -
Django Database Model Sum
I have business logic to ranking user by closing rate (selling some item) this is my models class Payments(models.Model): method = models.CharField(max_length=50) class Status(models.Model): status_name = models.CharField(max_length=50) class DataCustomer(models.Model): name = models.CharField(max_length=100, blank=True, null=True) payment_method = models.ForeignKey(Payments, on_delete=models.CASCADE, default=None) sales_name = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE) status = models.ForeignKey(Status, default=None, on_delete=models.CASCADE, blank=True, null=True) If sales selling something with payment method CASH with status Deal get point 13 and if with payment method CREDIT with status Deal get point 8 how can i impelement the query in views.py and in template tag? -
No Post matches the given query. while there are items with same slug
Hi I have been working on a blog app, I can create posts and view them on local host. I then hosted the blog and I get No Post matches the given query. I suspect the problem is with my url from what how others have solved the same problem, but it doesn't work for me. Views.py ]5 -
Combine views in views.py into a single view?
I am building a project in which I have a couple of views in my views.py that I want to combine in a dashboard format (4 views side by side). They are sufficiently complex because each view takes in a number of variables and has a lot of logic server side, and I also intend to use them elsewhere alone. The question I have is what is the best way to combine separate views from views.py into a single view if I want to create a dashboard view (ie. I have a base template with header/footer, and then 4 views embedded in that base). My proof of concept was to call the view with the right variables and decode the rendered return, then pass it as a variable onto the template, and finally just insert it as safe code. See below. My gut tells me this is terrible practice, but I'm not sure the includes/extends system is appropriate for such a use. views.py def view1(request, r1_level, r2_level, d_level, call_code): ... return render(request, 'modules/logic/levels/' + call_code + '.html', { 'indicators': indicators, 'd_level': d_level, 'prof': prof, 'a_flag': a_flag } ) def dashboard(request, level_code): view1 = view1(request, r1_level, r2_level, d_level, call_code).content.decode("utf-8") ... return … -
Django - 'NoneType' object has no attribute 'year'
So every time I try to view someone's profile when they haven't entered a birth day I get this error 'NoneType' object has no attribute 'year'. I followed this post to add the birthday/age to the user profile so no reason to include my code since I got it from here https://stackoverflow.com/a/39761072/12229283. I tried adding a default to the model but that doesn't seem to work how do I make it so if a user doesn't enter a birthday just skip it and ignore it? Thanks -
Django - @login_required decorator while passing arguments with form POST
I am passing a variable from template to view with form POST method. And view uses @login_required decorator as it is needed. If user is not logged in it goes login page and come backs to the view again but the passed variable information was not there anymore. Is there any way to solve this? I found a old stackoverflow post here but it's not working for me. Below is my view function @login_required2 def become_booster(request): print(request.method) if request.method == "POST" or request.method == "GET": email = request.POST.get('email') print(email) user = CustomUser.objects.get(email= email) tiers = Tiers.objects.filter(user=user) form = SubscriptionForm return render(request,'select_tier.html',{'tiers':tiers,'form':form,'creator':user}) -
deploy django to AWS Elastic Beanstalk
I would like to deploy my django project to AWS Elastic Beanstalk. My project was not create through eb-virt. Do I need to redo the project again in eb-virt? I have no idea of how to deploy my project directly. -
Django, display certain hyperlinks based on user group
{% extends 'base.html' %} {% block content %} <p>Welcome to home page.</p> <p>{% user.groups.all() %}</p> {% endblock %} At the moment I'm trying to figure out how I could even get all the user's groups to show on the page. This results in an error.... Invalid block tag on line 5: 'user.groups.all()', expected 'endblock'. Did you forget to register or load this tag? I have tried to do if statements, but it seems break as soon as it meets one condition. For example if user is a part of test1 and test2 groups, I'd like for it to display test1 and test2, but it only displays test1. {% extends 'base.html' %} {% block content %} <p>Welcome to home page.</p> {% if user.groups.all.0.name == "test1" %} <p>test1</p> {% if user.groups.all.0.name == "test2" %} <p>test2</p> {% endif %} {% endblock %} -
issue with bootstrap table plugin when extended from base html
I have issue with extended from base html , to display correctly table with DataTables the table appear but not how its should be with show ,search etc.. its appear as simple table . good table look enter image description here bad table enter image description here in the extended html i use follows shown below structure Any idea? Please advice Thanks {% extends 'base.html'%} {% load staticfiles %} {% block content %} <!--accordion css--> <link href="{% static 'css/tasks_view_style.css' %}" rel="stylesheet"> <!---CSS Bootstrap 4Table--> <link href="{% static 'css/dataTables.bootstrap4.min.css' %}" rel="stylesheet"> <!---Table content--> <div class="card"> <div class="card-body"> <h5 class="card-title">Basic Datatable</h5> <div class="table-responsive"> <table id="zero_config" class="table table-striped table-bordered"> <thead> <tr> <th>Task Name</th> <th>Person Assign</th> <th>Date Sterted</th> <th>Due Date</th> <th>Status</th> <th>Completed</th> </tr> </thead> <tbody> <tr> <td>< alt="user" data-toggle="tooltip" data-placement="top" title="" data-original-title="Steave"> Tiger Nixon</td> <td>System Architect</td> <td>2019/04/25</td> <td>2019/05/25</td> <td><button type="button" class="btn btn-success text-white">In Progress</button></td> <td><div class="progress mt-2" style="height: 20px"> <div class="progress-bar progress-bar-striped font-weight-bold bg-info" style="width: 10%"> 10% </div> </div></td> </tr> </tbody> <tfoot> <tr> <th>Task Name</th> <th>Person Assign</th> <th>Date Sterted</th> <th>Due Date</th> <th>Status</th> <th>Completed</th> </tr> </tfoot> </table> </div> </div> </div> <!---End of Table Content --> </div> </div> <!---End content Table--> </div> </section> {% endblock content %} {% block extra_js %} <!-- Optional JavaScript --> <script … -
Dango/React axios and CSRF Failed: CSRF token missing or incorrect
I know there are all kinds of answers to this sort of question. I have read them. I have tried to implement their suggestions and still I get 403 Forbidden Errors and `CSRF Failed: CSRF token missing or incorrect.' responses. My front end is React and my backend Django with DRF django-rest-auth installed. I have a Login page: Here's the code for that page, pages/Login.js: import React, {useState} from "react"; import {Link, Redirect} from 'react-router-dom'; import axios from 'axios'; import logoImg from "../img/logo.svg"; import {Button, Card, Error, Form, Input, Logo} from '../components/AuthForms'; import {useAuth} from "../context/auth"; import Cookies from 'js-cookie'; function Login(props) { const [isLoggedIn, setLoggedIn] = useState(false); const [isError, setIsError] = useState(false); const [userName, setUserName] = useState(""); const [password, setPassword] = useState(""); const {setAuthTokens} = useAuth(); const referer = props.location.state.referer || '/'; const url = 'http://localhost:8000/rest-auth/login/'; const withCredentials = true; const method = 'post'; const data = {"username": userName, "password": password}; function postLogin() { console.log('XXX postLogin called.'); console.log('postLogin called. username is ' + userName); let cookies = Cookies.get(); const headers = {"Content-Type": "application/json", 'X-CSRFToken': cookies.csrftoken}; console.log('Headers is:', headers); console.log('AAA Cookies:', cookies); const something = axios.request({url, withCredentials, data, method, headers}).then( result => { console.log('postLogin called. username is ' + userName); … -
Sending data from Django application to another Python script
I have a Django application where some data can be saved on my database using a form. I would like to create a Python script that, as soon as a new record is created, sends that data to an external Python script as json, and this external Python script should perform some operation with this data. This question is not about code, but i'm trying to be as specific as possible: is there a way to create a system that sends data to another system? In this case the data i need to send is the records submitted from forms of my Django app to another Python script. I'm supposing that the external script should be listening to some sort of URL, maybe? How could i accomplish this? Maybe with Webhooks? -
Django doesn't recognize relation when I define AUTH_USER_MODEL
I'm trying to implement a logout view with JWT. My User inherits used to inherit from django.contrib.auth.models.User, but I changed to AbstractUser thinking that these problems would disappear. When I define AUTH_USER_MODEL = 'portal.User' in settings.py and try to run ./manage.py migrate, I get this error: django.db.utils.ProgrammingError: relation "portal_user" does not exist settings.py JWT_AUTH = { ... 'JWT_GET_USER_SECRET_KEY': 'portal.models.jwt_get_secret_key', } models.py def jwt_get_secret_key(user_model): return user_model.jwt_secret class User(AbstractUser): USERNAME_FIELD = 'username' NAME_FIELD = 'name' EMAIL_FIELD = 'email' name = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subscriptions = models.ManyToManyField(Subscription, related_name='user_subscriptions') jwt_secret = models.UUIDField(default=uuid.uuid4) ... If I remove the AUTH_USER_MODEL = 'portal.User', it returns: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. portal.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. portal.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to … -
EmployeeFilterSet resolved field 'emp_photo' with 'exact' lookup to an unrecognized field type ImageField
I am trying to set up django filter but keep seeing an error message as shown below EmployeeFilterSet resolved field 'emp_photo' with 'exact' lookup to an unrecognized field type ImageField. Try adding an override to 'Meta.filter_overrides'. See: https://django-filter.readthedocs.io/en/master/ref/filterset.html#customise-filter-generation-with-filter-overrides To the best of my knowledge, I followed the docs as seen here. My models: from __future__ import unicode_literals import django_filters from django.core.validators import RegexValidator from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class Employee(models.Model): # basic information of employee first_name = models.CharField(_('first name'), max_length=40) last_name = models.CharField(_('last name'), max_length=40) emp_photo = models.ImageField(_('passport')) date_of_birth = models.DateField(_('birthday')) gender = models.CharField(_('gender'), max_length=15, choices=GENDER_CHOICES, default=['MALE', 'Male']) house_address = models.CharField(_('house address'), max_length=50) city_of_residence = models.CharField(_('city'), max_length=40) state_of_residence = models.CharField(_('state'), max_length=40, choices=NIGERIAN_STATE_CHOICES) country_of_residence = models.CharField(_('country'), max_length=40, choices=COUNTRY_CHOICES, default=[156, 'Nigeria']) state_of_origin = models.CharField(_('state of origin'), max_length=40, choices=NIGERIAN_STATE_CHOICES) local_govt_of_origin = models.CharField(_('LGA of origin'), max_length=40) town_or_city_of_origin = models.CharField(_('town or city'), max_length=40) nationality = models.CharField(_('nationality'), max_length=40, choices=COUNTRY_CHOICES, default=[156, 'Nigeria']) email = models.EmailField(_("email address")) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="phone number must be entered in the " "format: '+2340000000000'. Up to 15 digits allowed.") phone_number = models.CharField(_('phone number'), validators=[phone_regex], max_length=17, blank=True) class Meta: verbose_name = _('Employee') verbose_name_plural = _('Employees') def __str__(self): return "{} {}".format(self.first_name, self.last_name) Views: from … -
Django Overriding DateTimeField
I currently have a form which allows users to select a datetime, which I display using a custom bootstrap date picker. I have the date shown formatted to MM/DD/YYYY hh:mm A. The problem is the field doesn't recognize this format. I subclassed models.DateTimeField to convert the formatted date passed in to iso format and save it in the database. I updated my models to use it, but it still says enter a valid date/time. widgets.py from django.db import models from datetime import datetime import dateparser class CustomDateTimeField(models.DateTimeField): def to_python(self, value): compared_date = dateparser.parse(value, date_formats=['%m/%d/%Y %I:%M %p']) if isinstance(compared_date, datetime): return compared_date.isoformat() if value is None: return value Model: from django.db import models from django.contrib.auth.models import User from .widgets import CustomDateTimeField class Reminder(models.Model): remind_types = [('Regular', 'Regular'), ('Long Term', 'Long Term')] title = models.CharField(max_length=100) description = models.TextField() remind_time = CustomDateTimeField(blank=True) parent_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) type_of_remind = models.CharField(max_length=12, choices=remind_types, default='Regular') complete = models.BooleanField(default=False) Forms.py: from bootstrap_modal_forms.forms import BSModalForm from bootstrap_datepicker_plus import DateTimePickerInput from .models import Reminder from django import forms class NewReminderForm(BSModalForm): class Meta: model = Reminder fields = ['title', 'description', 'remind_time', 'type_of_remind'] widgets = { 'remind_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm A"}, attrs={'placeholder':'Note: If no time is given, there will be … -
Django Status (Draft - Published) & Time (Published, Created, Updated) Issues
This is my model. Appears on admin side but not working. models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='draft') -
Set maximum value of integer field in template from context Django
I have a regular form with the basic template: <form method="post" action=""> {% csrf_token %} {{ form }} <input type="submit" value="submit"> </form> The form consists of three integer fields defined in forms.py class InitForm(forms.Form): row_1 = forms.IntegerField(initial=1, min_value=1) row_2 = forms.IntegerField(initial=1, min_value=1) row_3 = forms.IntegerField(initial=1, min_value=1) The maximum value is set at runtime using input from the user. I have added it to the context by using get_context_data()... in the form view class, but how do I set the maximum input value for the three integer fields in the template? I can already output the maximum value in the template by {{ maximum_value }} I am just having trouble adding it to the form fields. For reference I need the maximum value on all the fields -
Django Thinking User Is Logged In On One Page Only But on The Rest They Are Not
So I created a user profile by following this tutorial https://www.oodlestechnologies.com/blogs/How-to-Edit-User-Profile-Both-Django-User-and-Custom-User-Fields/ but every time I go the profile page when not logged in it shows that I am logged in I don't know if django thinks im the user that the profile im viewing. I tested it by adding this into the base.html <p>{% if user.is_authenticated %} You are logged in {% endif %}</p> It doesn't show it on any pages because im not logged in unless I go to view someones profile then it says im logged in which I am not models.py class UserProfileManager(models.Manager): pass class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='avatars', blank=True) location = models.CharField(max_length=100, default='', blank=True) date_of_birth = models.DateField(default='00/00/0000', null=True, blank=True) website = models.URLField(default='', blank=True) bio = models.TextField(default='', blank=True) def __str__(self): return self.user.username def age(self): dob = self.date_of_birth tod = datetime.date.today() my_age = (tod.year - dob.year) - int((tod.month, tod.day) < (dob.month, dob.day)) return my_age def createProfile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.created(user=kwargs['instance']) post_save.connect(createProfile, sender=User) views.py def public_profile_view(request, username): user = User.objects.get(username=username) userprofile = UserProfile.objects.all() # date_joined = request.user.date_joined # last_login = request.user.last_login context = { 'user': user, 'userprofile': userprofile, # 'date_joined': date_joined, # 'last_login': last_login, } return render(request, "/account/profile/public_profile.html", context) def profile_edit_view(request): userprofile = … -
How do I fetch all the items in a list from an external API in Django?
So this is my api - https://api.myjson.com/bins/vvjiu Here is a portion of my view.py def postsign(request): product_list = Product.objects.all() product_data = [] for product in product_list: r = requests.get('https://api.myjson.com/bins/vvjiu').json() products = { 'name': r['products'][0]['name'], 'image': r['products'][0]['image'], 'price': r['products'][0]['price'], 'description': r['products'][0]['description'] } product_data.append(products) print(product_data) context = {'products':products} return render(request,"Welcome.html",context) And here's my product view in Welcome.html div class="container carousel-inner no-padding"> <div class="col-xs-3 col-sm-3 col-md-3"> {% for products in product_data %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ products.image }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ products.name }}</h5> <p class="price">{{ products.price }}</p> <p class="card-text">{{ products.description }}</p> <a href="#" class="btn btn-primary">Add to cart</a> </div> </div> {% endfor %} </div> </div> This returns just the first item from the API, that is, the Acoustic Guitar. But I want to get the rest of the items as well. What do i need to fix? -
I am not able to go into my virtual environment
I am new to programming. I recently started learning Django by following the tutorials on Mozilla. I created a python virtual environment by following the steps in the tutorial. However, I am not able to activate the virtual environment that I have created. As . a result, I am not able to progress on the tutorials. I have spent hours trying trying to find a solution on Google, but nothing seems to work. I have attached a picture of the terminal window where you can see the commands I am entering and the results. hemantasundaray@Deepaks-MacBook-Pro ~ % source createdenv/bin/activate source: no such file or directory: createdenv/bin/activate hemantasundaray@Deepaks-MacBook-Pro ~ % ls virtualenv ls: virtualenv: No such file or directory hemantasundaray@Deepaks-MacBook-Pro ~ % workon zsh: command not found: workon hemantasundaray@Deepaks-MacBook-Pro ~ % What am I doing wrong? Kindly help.enter image description here -
Setup Django with webpack-dev-server
setting up webpack-dev-server with Django has not been working. I have looked at many stackoverflow questions and read tuts but I can't seem to find what I am doing wrong. Here are the errors I get: webpack fails compiling with a ton of ERROR in ./node_modules/[package_name]/index.js Module not found: Error: Can't resolve '[tls or fs or net]' in '/Users/user_name/project_folder/sub_folder/node_modules/[package_name]' Even with webpack failing the browser load http://localhost:8080 with Cannot GET / error on it I am using webpack-dev-server : "^3.9.0" Here is my webpack.config.js var path = require("path"); var BundleTracker = require('webpack-bundle-tracker'); var CleanWebpackPlugin = require('clean-webpack-plugin'); var MiniCssExtractPlugin = require('mini-css-extract-plugin'); var TerserPlugin = require('terser-webpack-plugin'); var webpack = require('webpack') var rules = mode => { return [ { test: /\.(ttf|eot|svg|woff|woff2|svg)?(\?[a-z0-9#=&.]+)?$/, loader: 'file-loader', }, { test: /\.(js|jsx|mjs)$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [ ['@babel/preset-env', { corejs: 3, useBuiltIns: 'usage' }], ['@babel/preset-react'], ], plugins: [ ["babel-plugin-styled-components"], ["@babel/plugin-proposal-decorators", { legacy: true }], ["@babel/plugin-proposal-class-properties", { "loose": true }], "react-hot-loader/babel" ], cacheDirectory: true } }, // to transform JSX into JS { test: /\.(sa|sc|c)ss$/, use: [{ loader: MiniCssExtractPlugin.loader, options: { hmr: mode === 'development' ? true : false, }, }, { loader: 'css-loader', options: { importLoaders: 1 } }, 'postcss-loader', 'resolve-url-loader', 'sass-loader', ], } … -
Django set user's language based on IP then remember it in session with custom middleware
I want to play a little bit with language settings and have some problems through [TODO] set users location based on theirs IP - DONE (code below) some customers may want to change language. Example scenario: user lives in germany (and has German IP), middleware sets language to DE based on users IP but then user switch language to EN and want to hold that state in session. For now every time I run this code, it gives me language based on IP. Do you have any ideas where the bug is? . from typing import Callable from django.conf import settings from django.contrib.gis.geoip2 import GeoIP2 from django.http import HttpRequest, HttpResponse from django.utils import translation from geoip2.errors import AddressNotFoundError from utils.middleware import logger DE_COUNTRIES = ['DE', 'AT', 'CH', 'LI', 'LU'] def get_request_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip class UserIpAddrMiddleware: def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None: self.get_response = get_response def __call__(self, request: HttpRequest) -> HttpResponse: if hasattr(request, 'session'): current_language = request.session.get(translation.LANGUAGE_SESSION_KEY, None) if not current_language: request_ip = get_request_ip(request) g = GeoIP2() try: request_country_code = g.country(request_ip)['country_code'] if request_country_code == 'PL': request.session[translation.LANGUAGE_SESSION_KEY] = 'pl' request.session[settings.CURRENCY_SESSION_KEY] = 'PLN' elif request_country_code in DE_COUNTRIES: request.session[translation.LANGUAGE_SESSION_KEY] = 'de' … -
Querying datetime object in django doesn't work
I'm facing the issue of wrong query result due to timezone issue. I've read several answers, but most of suggest USE_TZ = False. But we can't do that because of several dependencies on time zone. blog = Post.objects.filter(date_posted__year=2019, date_posted__month=11) blog[0] Post: asfd random new india safasfd adf hey blog[0].date_posted datetime.datetime(2019, 11, 26, 20, 33, 58, tzinfo=) blog[0].date_posted.day 26 When I query on day 26 it throws error: Post.objects.get(date_posted__year=2019, date_posted__month=11, date_posted__day=26, slug=blog[0].slug) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/insol/webD/trydjango/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/insol/webD/trydjango/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name Blog.models.Post.DoesNotExist: Post matching query does not exist. But it works on day 27. Post.objects.get(date_posted__year=2019, date_posted__month=11, date_posted__day=27, slug=blog[0].slug) Output: <Post: asfd random new india safasfd adf hey> Is there any I can solve this issue? -
Celery-Django, Start and stop reminder emails for survey
I'm trying to implement a recurring daily reminder email task into my program that begins at a specific date/time and is stopped only when the customer completes the required action. Is this something that is possible with Celery and Django? I've already found a way to send a one time task email via ETA- though am unsure how to set up a recurring event that can then be cancelled. Thanks for your time.