Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am creating a Web project, Frontend on Reactjs backend on Python Django and use Firebase realtime data base for store data
I Know first create restful api to get data from client side but, dont know the flow of project to make connections for CRUD operations in my project -
Link automatically OneToOneField when creating an objects
Considering this two models in my project: MODEL class Movie(models.Model): user = models.ForeignKey(UserInformation, on_delete=models.CASCADE) title = models.CharField(max_length=250) year = models.DateField(default=auto_now_add=True) def __str__(self): return self.title class List(models.Model): user = models.ForeignKey(UserInformation, on_delete=models.CASCADE) movie = models.OneToOneField(Movie, on_delete=models.CASCADE) [...] I'd like to link the List model to the Movie model when the System objects are created. This is my views file: VIEWS def movie_view(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): [...] List.objects.create( user = request.user.userinformation, list_movies = request.list_movies.list, [...] ) return redirect('add_movie') else: return redirect('index') else: form = FileForm() context = { 'form': form, } return render(request, 'add_movie.html', context) This part list_movies = request.list_movies.list may be the problem since I'm getting this error Django: 'WSGIRequest' object has no attribute error. How can I assign correctly the OneToOneField? -
How can i generate backup codes for two factor authentication
I am try to generate backup codes for the users of my system after they enable two factor authenciation -
Django Find difference in the same model instance
I've been searching around and I don't think I've found my answer quite yet. But I'm looking to be able to find differences in data and have a list of column names that show that. Take for instance I have a model just called my_model that has some columns. object = my_model.objects.get(id=1) # Perform edit some values. old_object = my_model.objects.get(id=1) object.save() # Check for differences model_fields = [field.name for field in my_model._meta.get_fields()] filtered_list = filter(lambda field: getattr(object, field, None) != getattr(old_object, field, None), model_fields) Purpose of this is to notify the user after they make an update on their end to send an email to that user to just give them a reminder that they changed whatever values they changed. -
Protected member accessed from outside the class, Django
I'm trying to condition if a value exist as a property in a model or not. I'm trying to do this Mode()._meta.get_field("id") But I got the following error from pylint Protected member accessed from outside the class Can someone help me please? -
How to assign a default choice value to a user when they sign up in django framework
I am writing a logic where when a users creates and account, i want to automatically assign the free membership to them and i know this should be done in the register view but i don't know why it's not working as expected. I still have to manually go to my admin page and manually assign a value to newly created user and that's not what i really wanted. Models.py class Membership(models.Model): MEMBERSHIP_CHOICES = ( ('Enterprise', 'Enterprise'), # Note that they are all capitalize// ('Team', 'Team'), ('Student', 'Student'), ('Free', 'Free') ) PERIOD_DURATION = ( ('Days', 'Days'), ('Week', 'Week'), ('Months', 'Months'), ) slug = models.SlugField(null=True, blank=True) membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) duration = models.PositiveIntegerField(default=7) duration_period = models.CharField(max_length=100, default='Day', choices=PERIOD_DURATION) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) def __str__(self): return self.membership_type #### User Membership class UserMembership(models.Model): user = models.OneToOneField(User, related_name='user_membership', on_delete=models.CASCADE) membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True) reference_code = models.CharField(max_length=100, default='', blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=UserMembership) def create_subscription(sender, instance, *args, **kwargs): if instance: Subscription.objects.create(user_membership=instance, expires_in=dt.now().date() + timedelta(days=instance.membership.duration)) views.py def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.all() categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') obj = request.user get_membership = Membership.objects.get(membership_type='Free') instance = UserMembership.objects.create(user=obj, membership=get_membership) … -
Multiple Django Apps using one database/model
New to Django...I'm trying to create a project with the following structure: CompanyName <--Project ingredients < -- Application CompanyName supplier <-- Application My issue is that my project is going to use a database/model like the following: suppliers (table) - name - created_by (foreign_key, auth.User) ingredients (table) - name - supplied_by (foreign_key, supplier.name) My question is do I create all the tables in a single models.py or do I break up each table into each application's manage.py? If I use separate models.py, how do you create the suppliers table and then the ingredients table since the ingredients table has a foreign key to suppliers? -
How to create a link that takes me to my DjangoRest api
I started studying Django a few days ago and i want that when I click on a button it takes me to the url of my api. This is my urls from my app: from django.urls import path, include from animes import views from rest_framework import routers router = routers.DefaultRouter() router.register('animes', views.AnimesViewSet, basename='animes') router.register('nota', views.NotasViewSet, basename='notas') urlpatterns = [ ... path('api/', include(router.urls), name='api') ] the problem from my template is here: <a class="botao__link" href="{% url 'api' %}"><button class="botao__botao" type="submit">API</button></a> when i write the url manually i can go to the api without problems , but I can't go clicking the button -
Django ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'
I know others have had a similar issues with and getting this same error, but I think my situation is unique. I am running Django 3.1.4 and on my local machine, I can run python manage.py shell with no issue. On the server instance, running what should be the same project, and the same version of Django, I get: Django ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' When trying to run manage.py shell. To make things more cryptic, if I open the shell on my local machine and run: from django.utils.encoding import python_2_unicode_compatible I get the same error. So for some reason when I call manage.py shell from my local machine it doesn't try to import python_2_unicode_compatible, but when I run it from the server it does. I can't find where the discrepancy is. Here is the full stacktrace if that is helpful: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/chase/Env/mantis/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], … -
I can't manage to import and use a javascript function from a .js into a django template. Ideas?
I have a javascript file project_dashboard.js with a few things defined inside of it and an html file where I try to call such function (amont other things). For some reason, I keep getting the error that the function is not defined at HTMLButtonElement.onclick. What drives me crazy is that the first part of the .js is loaded and works (the css is changed if I click on table). So the script is there, but I can't use the function. project_dashboard.js $('table').on('click', 'tr.parent .fa-chevron-down', function(){ $(this).closest('tbody').toggleClass('open'); }); function EnablePositionEdit(position_id) { const checked_events = [] $("#edit_button_____" + position_id).toggle() $("#save_button_____" + position_id).toggle() $("#delete_____" + position_id).toggle() inputs = document.querySelectorAll(".availability_____" + position_id + " input") inputs.forEach(input => { input.removeAttribute("disabled") }) } html {% extends 'action/base.html' %} {% block extrastylesheets %} {% endblock extrastylesheets %} {% block content %} <head> {% load static %} <link rel="stylesheet" href="{% static 'action/css/project_dashboard.css' %}"> <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> </head> ... <div id="edit_button_____{{ position.id }}" style="display: block;"> <button class="btn" style="font-size:10px; color: rgb(59, 89, 152);" onclick = EnablePositionEdit('{{ position.id }}')> <i class="fa fa-pencil"></i> </button> </div> ... {% endblock content %} {% block extrascripts %} <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script> <script type="text/javascript" src="{% static 'action/js/project_dashboard.js' %}"></script> <script> $(document).ready(function() { $('.summernotable').summernote({ toolbar: [], }); }); … -
The intermediary model has no field
i'm newbie in Django world i'm creating a web app to manage products in an online store i created the models for Catergories and Products here are my models : from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=255, unique=True, ) description = models.TextField(max_length=1500) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) categories = models.ManyToManyField('Category', through='CategoryProducts', through_fields=('category_name','product_name')) def __str__(self): return self.name class CategoryProducts(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, ) product = models.ForeignKey(Product, on_delete=models.CASCADE, ) When i try to make migrations , Two errors apear : products.Product.categories: (fields.E338) The intermediary model 'products.CategoryProducts' has no field 'product_name'. HINT: Did you mean one of the following foreign keys to 'Category': category_name? products.Product.categories: (fields.E339) 'CategoryProducts.category_name' is not a foreign key to 'Product'. HINT: Did you mean one of the following foreign keys to 'Product': product? -
Mongodb result and python result difference
when I query in studio3t, I get a response in .net uuid type, and when I query in python, I get UUID Version=1. How can I translate this output in python? mongo response; pyton response; {'_id': UUID('0fc97e3a-8f0c-be4f-a5dc-b166af761afd'), 'Version': 1, -
Django test not created testing database and not work
everyone I created TestCase, but when I put the command "python manage.py test", this test don't work. Can you help me, please? from django.test import TestCase from accounts.models import UserProfile class AccountsTestCase(TestCase): def setUp(self): print('test_setUp') UserProfile.objects.create(email='test@test.com', password='user111333') def get_user(self): user = UserProfile.objects.get(email='test@test.com') -
How to transfer from datatable data to python variable
Good day, guys! does anyone know how I can pass a data from my table to a python variable? Here's my snippet <table class="table table-hover table-dark"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Filename</th> <th scope="col">Date Uploaded</th> </tr> </thead> <tbody> {% for row in files %} <tr> <td>{{ row.0 }}</td> <td>{{ row.1 }}</td> <td>{{ row.3 }}</td> </tr> {% endfor %} For Example, I clicked a table row 2 then it supposedly get the row.1 value then it will transfer to my variable (get_name_from_table) in python. Here's my code in python get_name_from_table = "" return send_file(BytesIO(data_v), attachment_filename= get_name, as_attachment=True) ``` My main activity is to have a download file button, it's so hard for me to find a dynamic download button. :( -
Import "django..." could not be resolved from source Pylance (reportMissingModuleSource)
I created a new virtual environment in my folder "Django 2021", by typing "python -m venv env" in the cmd which was in the same directory as the folder "Django 2021", then I "pip install django" in the already active env, after that I used the command "django-admin startproject devsearch" (also in the venv). Now I had the "env" and "devsearch" subfolders of "Django 2021", then I dragged my "env" folder into my "devsearch" folder. After that I opened my VS Code (IDE) and selected my "devsearch" folder inside "Django 2021" as my workspace. Opened a new terminal (and also activated my venv) and ran the server (python manage.py runserver), everything still worked perfectly. However, after that, I tried coding something (can't remember) but I couldn't test it because django wasn't imported. I hovered my mouse over the problem and it displayed: "Import "django..." could not be resolved from source Pylance (reportMissingModuleSource)". Here is a bit of visual representation: enter image description here (Folders) enter image description here (VS Code) -
Getting MultiValueDictKeyError while checking if a field is empty
I have a regsitration form where a user chooses a plan. I am trying to check that if the field is empty a message should be displayed. The field name is plan. The code is below if password1==password2: if CustomUser.objects.filter(email=email).exists(): messages.info(request, 'User with same email already exists') return redirect('register') elif plan is None: messages.info(request, 'Please select a plan') return redirect('register') else: user=CustomUser.objects.create_user(full_name=full_name.upper(),age=age, phone_no=phone_no, address=address, plan=plan, email=email.lower(), password=password1) user.is_active = False user.save() usr_otp = random.randint(100000, 999999) UserOtp.objects.create(user = user, otp = usr_otp) mess = f"Hello, {user.full_name},\n Please enter the otp to validate your email and activate your account. \nYour OTP is {usr_otp} .\n Thanks!" return render(request, 'register.html', {'otp': True, 'user': user}) # return redirect('login') I have tried multiple ways to check whether the plan field is empty or not such as elif plan == ' ' elif not plan elif plan is None elif request.POST['plan'] == ' ' for all these I am getting only one error MultiValueDictKeyError at /account/register 'plan' Request Method: POST Request URL: http://127.0.0.1:8000/account/register Django Version: 3.2.8 Exception Type: MultiValueDictKeyError Exception Value: 'plan' Exception Location: C:\Users\rickb\Envs\virenv\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__ Python Executable: C:\Users\rickb\Envs\virenv\Scripts\python.exe Python Version: 3.9.7 Python Path: ['C:\\Users\\rickb\\Envs\\virenv\\jgs', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\rickb\\Envs\\virenv', 'C:\\Users\\rickb\\Envs\\virenv\\lib\\site-packages'] Server time: Mon, … -
import a file from a directory outside Django project
So I am making a UI to manage an ultrasound sensor GPiOs. I have a directory full of sensors' code and then I have a Django project with a django app. I am trying to import a ultrasound.py into views.py to use the main function that gets the distance. The problem is that when I do from Sensores.ultrasonidos import main I get a ModuleNotFoundError: No module named 'Sensores' error. I've seen that I have to add an __init__ file inside the directory. But doesn't work for me. Help is much appreciated. my views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import UltrasonicSensor from Sensores.ultrasonidos import main class IndexView(ListView): template_name = 'index.html' context_object_name = 'sensors' def get_queryset(self): return UltrasonicSensor.objects.order_by('-id')[:5] class SensorDetailView(DetailView): template_name = 'sensor_detail.html' context_object_name = 'sensor' my ultrasound.py: import time from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger def main(): # Grove - Ultrasonic Ranger connected to port D16 sensor = GroveUltrasonicRanger(16) counter = 10 while (counter < 10): distance = sensor.get_distance() distance = (float(distance) / 100) print('{:.4f} m'.format(distance)) if distance < 1: print('Cerca') elif 1 <= distance <= 1.9: print('Medio') else: print('Lejos') time.sleep(1) counter = counter + 1 if __name__ == '__main__': main() -
Select objects from django model based on user input
I have a large django model with about 800 objects and I want to create a view in which the user can select a certain number of those objects to pass to another view for further processing. The fact that there are so many objects of the model makes listing all the objects very unpractical, as the user would have to scroll through 800 objects. In order to address this problem, I want to place an as-you-type search-bar in the top of the view so that the user can type the name of the objects and select them by clicking them. When the objects are selected, they should appear under the search-bar as tags that the user can remove by clicking an "x" next to each one. When the user has made all the required selections, then they should be able to click a button and jump to the next view where those selected objects are accessible. The model I am using can be simplified to: class Song(): song_name = models.CharField(max_length=256) song_author = models.CharField(max_length=256, blank=True) song_content = models.TextField() def __str__(self): return self.song_name class Meta: ordering = ['song_order'] song_order = models.PositiveIntegerField(editable=False, db_index=True) So far I have been able to make a … -
Writing JavaScript function in Django models
I would like to get long, lat variables from my models.py, which looks something like this: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Marker(models.Model): latitude = models.FloatField( validators=[MinValueValidator(-90), MaxValueValidator(90)], ) longitude = models.FloatField( validators=[MinValueValidator(-180), MaxValueValidator(180)], ) And add fetch them to the line myLatLng in JavaScript function initMap() { const myLatLng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: myLatLng, }); new google.maps.Marker({ position: myLatLng, map, title: "Hello World!", }); } the sample code is here: https://developers.google.com/maps/documentation/javascript/examples/marker-simple So I would like to create a marker from my admin page and display it on the map -
TemplateDoesNotExist at / Home.html Exception Type: TemplateDoesNotExist
My Customers urls.py ''' from django import urls from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('', views.Home ,name= 'Home'), path('Hall/', views.Hall ,name= 'Hall'), path('Food_item/', views.Food_item ,name= 'food'), path('About_us/', views.About_us ,name= 'about'), ] ''' My Web_project urls.py ''' from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('customer.urls')), ] ''' Settings.py Templates ''' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Customers View.py ''' from django.http.response import JsonResponse from django.shortcuts import render def Home(request): return render(request, "Home.html", {"title":" Home"}) def Hall(request): return render(request, "Hall.html", {"title": "Hall"}) def Food_item(request): return render(request, "Food_item.html", {"title": "Food_item"}) def About_us(request): return render(request, "About_us.html", {"title": "About_us"}) ''' My cd is web_project>customer>templates>customer>Home.html The error it showing ''' Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Nawaf Bhatti\Desktop\New\web_project\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\rest_framework\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site- packages\django\contrib\admin\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site- packages\django\contrib\auth\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\web_project\customer\templates\Home.html (Source does not exist) ''' -
How to serve premium content base on user subscription in django
Hello guys i hope the way i ask this questions meets the standard way of stackoverflow. I have a projects i'm working on. On this project you need to subscribe a plan (monthly, 3 months or 6 months) to gain access to premium blog post contents and if you are not subscribed but registered, you will only get access to regular blog post contents. I've been able to integrate payment api and also the payment is working, i've also been able to save the payment details on a table in my database. What i need now is how do i filter the user based on their subscription status to serve them the premium or regular contents.Below is my Models and Views. # In models.py class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) username = models.CharField(max_length=200, unique=True, blank=True) email = models.EmailField(max_length=200, unique=True, blank=False) first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) phone_no = models.CharField(max_length=11,validators=[MaxLengthValidator(11)]) profile_picture = models.ImageField(upload_to="images/profile_image",default="default_user_image.jpeg", blank=True, null=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] def __str__(self): return self.username def get_absolute_url(self): return reverse("admin-update-user", kwargs={"pk": self.pk}) class … -
Angular to Django: Unable to upload a file - file is blank
I am creating a File Upload feature in my application where the user has to upload an excel file along with a date (using a date picker). The user then clicks upload and this calls a view in Django which runs a python class that uploads the data onto an oracle database using SQLAlchemy. I have hit an issue where I don't know how to successfully pass through a file in my service call. In the example below, I have assigned the file to the variable fileToUpload but when this is called in the upload service and assigned in a dictionary, the value of that becomes empty. Please see code below: views.py @api_view(('POST',)) @csrf_exempt def uploader(request): if request.method == 'POST': try: instance= uploader(request.data['data'], request.data['selectedDate']) _ = upload_instance.run_upload_process('data') upload_message = "Success" return Response(upload_message, status=status.HTTP_201_CREATED) except Exception as e: upload_message = 'Error: ' + str(e) return Response(upload_message, status=status.HTTP_400_BAD_REQUEST) file-upload.service.ts DJANGO_SERVER: string = "http://127.0.0.1:8000"; constructor(private http:HttpClient) { } public upload(data: any, selectedDate:any) { let postData = { data, selectedDate }; return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, postData); } upload.component.ts onChange(event: any) { this.filetoUpload = event.target.files[0]; } inputEvent(event:any) { this.monthEndDate = event.value; } onUpload() { this.loading = !this.loading; this.fileUploadService.upload(this.filetoUpload, this.monthEndDate).subscribe( (event: any) => { if (typeof (event) === … -
How to create a for loop based lightbox gallery with django
(Newbie Django dev here, with no Javascript knowledge) I'm building a Django website designed to display one page for each notice in the db. Some images can be attached to the notices: sometimes none, sometimes a few, up to maximum a dozen. I'd like to display these images on top of the detail.html page, following the example shown here: https://www.w3schools.com/howto/howto_js_lightbox.asp I understood that I need to adapt the code to use a for loop. I did my best to adapt it but I'm stuck with a non working gallery. Here is my code right now, adapted from the tutorial: detail.html <div id="illustrations" class="galerie"> {% for image in object.illustration_objet_archi.all %} <div class="row"> <div class="column"> <img src="{{ image.image_thumbnail.url }}" onclick="openModal();currentSlide({{ forloop.counter }})" class="hover-shadow"> </div> </div> <!-- The Modal/Lightbox --> <div id="myModal" class="modal"> <span class="close cursor" onclick="closeModal()">&times;</span> <div class="modal-content"> <div class="mySlides"> <div class="numbertext"> {{ forloop.counter }} / {{ image.image.count }} </div> <img src="{{ image.image.url }}" style="width:100%"> </div> <!-- Next/previous controls --> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <!-- Caption text --> <div class="caption-container"> <p id="caption">{{ image.legende }}</p> </div> <!-- Thumbnail image controls --> <div class="column"> <img class="demo" src="{{ image.image.url }}" onclick="currentSlide({{ forloop.counter }})"> </div> </div> </div> {% endfor %} </div> style.css (the body … -
Not Found error after logging in with google using django-allauth
I am using django-allauth package and google provider for authentication in my django project. Everything worked fine in development however when I launched my project on the server, I got an error. When I press the "Log in with Google" button in my sign in page, I get redirected to the page where google asks me to choose my Google account to continue with. Then after this step, where I get redirected to my site, I'm encountered with a Not Found error. I tried a bunch of stuff found online but they didn't work. here is my Google credentials authorized redirect URIs. In my settings.py file I configured allauth as below: # Django-allauth configs AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_SIGNUP_REDIRECT_URL = 'accounts:create_profile_url' ACCOUNT_EMAIL_VERIFICATION = 'none' LOGIN_REDIRECT_URL = 'dashboard_url' ACCOUNT_FORMS = { 'login': 'accounts.forms.CustomLoginForm', 'signup': 'accounts.forms.CustomSignupForm', 'change_password': 'accounts.forms.CustomChangePasswordForm', } ACCOUNT_DEFAULT_HTTP_PROTOCOL='https' and I've added 'allauth.urls' in my urlpatterns too urlpatterns = [ ... path('accounts/', include('allauth.urls')), ... ] I … -
Django - filter queryset until Sum is reached
Let's imagine a model called Roll. It stores the outcome of rolling a six-sided die (D6): class Roll(models.Model): outcome = models.PositiveSmallIntegerField('Roll', null=False, blank=False, default=1) There are many rolls, for example: print(list(Roll.objects.all().values_list('outcome', flat=True))) >>> [1, 5, 6, 3, 5, 4, 4, 3, 2] Now, how should I go about to get the latest N rows whose Sum('outcome') reaches an arbitrary amount, without looping in some way or another, until that amount is reached? If we imagine the rolls: pk | outcome | (accumulated sum) 1 | 3 | 3 2 | 2 | 5 3 | 6 | 11 4 | 1 | 12 5 | 5 | 17 6 | 4 | 21 7 | 3 | 24 8 | 4 | 29 9 | 5 | 34 10 | 1 | 35 and the arbitrary amount 20, then the query should pick the pk 6 as the accumulated sum has now reached the amount needed. Could something similar to the below work?: amount = 100 Roll.objects.annotate( accumulated_sum=Subquery( Roll.objects.filter( pk__lt=OuterRef('pk') ).values('pk').order_by('pk').annotate( sum=Sum('outcome', distinct=True) ).values( 'sum' )[:1] ) ).filter( sum_before__gte=amount )