Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to prevent sentry from logging errors while on Django local server?
I am trying to prevent Sentry from logging errors to my Sentry dashboard while I'm working on my local server (i.e http://127.0.0.1:8000/). The only time I want sentry to log errors to my dashboard is when my code is in production. How can I go about this? I have tried this below, but it doesn't work: if DEBUG == True sentry_sdk.init( dsn=os.environ.get('SENTRY_DSN', None), integrations=[DjangoIntegration()], # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. send_default_pii=True ) -
social-auth-app-django: how to disconnect a user without password
On my site (www.raptors.ru) I'm using social-auth-app-django to authorize users from Facebook. To make their logging in easier I made following setting: ACCOUNT_PASSWORD_INPUT_RENDER_VALUE = True so that users do not need to enter their password. When the FB user logs in the first time, a record is created in the table users. What is important, this user has no password on my site. However, this user is fully functional: he is able to publish posts, make comments, etc. The problems begin if the user wants to disconnect from his social account. First, if one tries to disconnect his account via the LoginCancelledView (direct link is https://raptors.ru/accounts/social/login/cancelled/, he gets a message that he successfully disconnected, but it's not truth since his username is still on the page header (see the the screenshot). Second way to disconnect is from the connections page (https://raptors.ru/accounts/social/connections/). However, if the user clicks the Remove button, Django doesn't do it and report following error: Your account has no password set up. Please tell me, which is the correct and working way to disconnect (or completely remove) the Facebook user from my site? FB insists that I should provide this option. -
Django ORM in multi threading task does not save data into model
In my django app i schedule a threading process for run every n seconds a thread designed for save data into a table. in my init file i do: class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False so, from my init i do: ... rc = RepeatedTimer(300, save_calc) ... ok, my cll start as a thread and in this method a save some data in two different table, but just the first save() call was ok, the second does'n do anything: ... vr = VarsResults(key_res=Results.objects.get(res_key=p.res_key), var_id=v_id, var_val= v_original, var_val_conv = v_conv, var_hash=hash_vars.hexdigest()) vr.save() time.sleep(0.5) # if val trigger alarm save in if v_alarm and v_alarm.alarms_val: if eval(str(v_conv)+v_alarm.alarms_val): av = VarsAlarm(n_occurence=2, var_id=ModbusVariable.objects.get(id=int(v_id))) av.save() time.sleep(0.5) Why after the first vr.save() nothing appen?the second query does not execute (the query is correct, also if i insert a print or a logging code nothing appen) There are ome other way for achieve this in multithreading mode? So many … -
Django Form is not submitting for some reason
My Django form is not submitting for some reason, When I click submit and go to the admin page to see the instance I don't find anything, Here's the code: views.py: from django.shortcuts import render from .models import User from .forms import SignUpForm def signup(request): username = request.POST.get('username') password = request.POST.get('password') data = User(username=username, password=password) return render(request, 'pages/signup.html', {'suf': SignUpForm}) forms.py: from django import forms class SignUpForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(max_length=50) models.py: from random import choice from statistics import mode from django import views from django.db import models from django.forms import ModelForm class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) def __str__(self): return self.username admin.py: from django.contrib import admin from .models import User admin.site.register(User) signup.html: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Sign Up</title> </head> <body> <div class="signContainer"> <form name="signUpForm" method="POST"> {% csrf_token %} {{suf}} <input type="submit" value="Sign Up" class="submitButton" /> </form> </div> </body> </html> {% endblock content %} -
I want to update a small part of my webpage using ajax How can I do that in Django?
Basically I have three models class category(models.Model): name = models.CharField(max_length=40) class subCategory(models.Model): category = models.ForeignKey(category, on_delete= models.CASCADE) name = models.CharField(max_length=40) class product(models.Model): name = models.CharField(max_length= 40) image = models.ImageField(upload_to="media/upload_to") price = models.DecimalField(max_digits=10, decimal_places= 3) price_off = models.DecimalField(max_digits=10, decimal_places=3) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(category, on_delete= models.CASCADE) sub_category = models.ForeignKey(subCategory, on_delete= models.CASCADE) These are the models that I have worked on Now I have to apply ajax on my given template so I don't know how to start There is my image When I clicked on Samsung then Samsungs product will show and as well others This is my index.html <div id="mobile-list" class="section-container bg-silver p-t-0"> <!-- BEGIN container --> <div class="container"> <!-- BEGIN section-title --> <h4 class="section-title clearfix"> <a href="#" class="pull-right">SHOW ALL</a> Mobile Phones <small>Shop and get your favourite phone at amazing prices!</small> </h4> <!-- END section-title --> <!-- BEGIN category-container --> <div class="category-container"> <!-- BEGIN category-sidebar --> <div class="category-sidebar"> <ul class="category-list"> {% for data in mc %} <li class="hit" name="{{ data.name }}" data-name="{{ data.name }}"><a href="#"> {{data.name}}</a></li> {% endfor %} </ul> </div> <div class="category-detail"> <!-- BEGIN category-item --> <a href="#" class="category-item full"> <div class="item"> {% for data in mobilePhone %} {% if forloop.counter == 1 %} <div … -
How to stop the following python code after a certain time?
I have to run a python command function in the following manner: from django.core.management import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('length', type=int) parser.add_argument('breadth', type=int) def handle(self,*args,**options): func= Library_Class() result= func.library_function(length,breadth) return This code gives arguments to the library function which in turn returns the required output. I want to stop this command function after 10 seconds of run time. How Do I use multiprocessing or any other library to do that? -
how to fill a table in my database automatically with data added to another table?
I am currently developing a management application and I have reached a level where I have to ensure that one of my tables, precisely the stock table, must be automatically filled with data from the location and article tables. In other words, the stock is created when there is a location and a product created. I tried to use the signals as in the documentation but it does not work. Can you help me on this please. models.py class Location(models.Model): class CHOICES(models.TextChoices): FOURNISSEUR = 'Fr', 'Fournisseur' VEHICULE = 'Vl', 'Véhicule' DEPOT = 'Dt', 'Dêpot' location = models.CharField(max_length=255, choices=CHOICES.choices) name = models.CharField(max_length=255, verbose_name="Location Name", unique=True) provider = models.ForeignKey(Provider, on_delete=models.CASCADE, null=True, blank=True) depot = models.ForeignKey(Depot, on_delete=models.CASCADE, null=True, blank=True) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name class Stock(TimeStampBaseModel): location = models.ForeignKey(Location, on_delete=models.CASCADE) product = models.ForeignKey(Article, on_delete=models.CASCADE) qty_stock = models.FloatField(verbose_name="Quantity Purchase", db_index=True, default=0) def __str__(self): return self.stock_name class Meta: constraints = [ UniqueConstraint(name='unique_storage', fields=['id', 'location', 'product']) ] signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import Location, Stock from article.models import Article @receiver(post_save, sender=Location) def create_stock(sender, instance, created, **kwargs): if created: attrs_needed= ['location', 'product', 'qty_stock'] Stock.objects.create(location=instance.location, product = instance.product, qty_stock=instance.qty_stock) post_save.connect(create_stock, sender=Location, weak=False) -
I added a Like model but I don't know how to increase the number of like
I created a Blog app, and i want to add a Like button to each post in the Blog, how can i do this ? how can i make this happen in view and the template ? the models: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Photo, on_delete=models.CASCADE) def __str__(self): return str(self.user) the view: def viewPhoto(request, pk): post = get_object_or_404(Photo, id=pk) photo = Photo.objects.get(id=pk) return render(request, 'photo.html', {'photo': photo, 'post': post }) -
Regex validator produce migration without changes
Django detect changes in models with RegexValidator, from django.core.validators import RegexValidator url_regex_validator = RegexValidator( regex=r'^(\w{1,5}:\/\/)([\w\+\/-]+)([\.]\w{1,4})$', message="Error invalid URL") model: class MyModel(models.Model): path = models.CharField(max_length=200, default=None, blank=True, null=True, validators=[url_regex_validator]) Every python manage.py makemigrations Alter field path on mymodel produce a new migrations about regex validator in this model. Any idea? -
How to create multiple text contains filter in Django filters?
I am working with a django site and using django-filters to make filters. so i created a model as follows: class Bids(models.Model): Services=models.CharField(max_length=300) and that field contains many random words like 'services,manpower,security,machines,chemical,.. etc' so i created a django-filter as follows: class BidsFilter(django_filters.FilterSet): Services=CharFilter(field_name='Services',lookup_expr='icontains') class Meta: model=Bids fields="Services" and on my view i am using this filter as follows: def index(request): bidsData= Bids.objects.all() myFilter=BidsFilter(request.GET,queryset=bidsData) bidsData=myFilter.qs context = { 'Bids': bidsData, 'myFilter':myFilter } return render(request,"base.html",context) and on my template i am showing this filter as form: <form method="GET" >{{ myFilter.form }}<button class="btn-btn- primary"type="submit">Apply Filter</button></form> right now what happening is when i type a word eg. manpower the records having this word are printed. and if i type another word 'services' than those records are getting printed. What i want is to create multiple keyword filter for example if someone type 'manpower' than those records which have 'manpower 'are printed and also if someone types 'services' than those records which have 'services' word also printed and so on. its like a Tag filter you know like twitter and instagram can anyone show a good way of doing it. thanks in advance <3 -
Recommended file manager for Django Jazzmin admin
I am using Jazzmin theme in my Django admin panel and I am wondering if there is any recommended library to handle media files? I've installed django-filer but I see no option to integrate it with my summernote/tinyMCE or CKEditor. It doesn't matter for me which one I will be using. The most important is to have an option to insert uploaded images from body field in my model (it is textfield). I want to integrate it only in admin panel. -
what is equivalent to url(r'name/$') using path? I don't want users to access a django path
When considering url() in django, '$' allows you to block the url path. What is equivalent when considering 'path'? To be more precise I have the following path('',views.home,name='home'), path('json', json, name="json"), my home page calls the json file to plot a chart, however if user types in the url '.../json' they can access the json data file. I want users to not have access to the path /json but I still want my home page to access this json path. Thanks -
How to create custom button in Django admin, which create many object?
I have a model Student: from django.db import models from django.contrib import admin class Student(models.Model): name = models.CharField(max_length=30, default='') lastname = models.CharField(max_length=30, default='') grade= models.CharField(max_length=8, default='') class StudentAdmin(admin.ModelAdmin): list_display= ('name','lastname','grade') from django.contrib import admin from .models import * admin.site.register(Student, StudentAdmin) Imagine, that I have an additional model Person ( with name and surname fields). My situation is just an example. I want to create a button in the Django admin (it's very important to implement this in Django admin page), that creates many Student objects at once (name and lastname we take from Person, with empty grade field, which we can fill in the future). -
Async Stripe Function call
I am new to Django and I have been working on a Stripe based application and I found out that my class based views are quiet slow and I need to make them run as fast as possible. I discovered that in Django there is Asynchronous Support available but I am unable to figure how can I use it in class based views everywhere I find there are functional based example just. class BillSerializer(ReturnNoneSerializer, serializers.ModelSerializer): interval = serializers.CharField(read_only=True, required=False) amount = serializers.IntegerField(read_only=True, required=False) date = serializers.DateTimeField(read_only=True, required=False) is_active = serializers.BooleanField(read_only=True, required=False) subscription_expiry = serializers.BooleanField(read_only=True, required=False) active_jobs = serializers.IntegerField(read_only=True, required=False) class Meta: model = Billing fields = "__all__" def to_representation(self, validated_data): stripe.api_key = settings.STRIPE_API_KEY stripe_sub = stripe.Subscription.retrieve( self.context["request"].billing.stripe_subscription_id ) stripe_object = stripe_sub.get("items") quantity = stripe_object.get("data")[0].get("quantity") amount = ( stripe_object.get("data")[0].get("price").get("unit_amount") // 100 * quantity ) interval = stripe_object.get("data")[0].get("plan").get("interval") date = datetime.fromtimestamp(stripe_sub.current_period_end).strftime( "%Y-%m-%d %H:%M:%S" ) if validated_data.subscription_end < make_aware(datetime.now()): is_active = False else: is_active = True if validated_data.subscription_end <= make_aware(datetime.now()): subscription_expiry = True else: subscription_expiry = False return { "date": date, "interval": interval, "amount": amount, "quantity": quantity, "is_active": is_active, "subscription_expiry": subscription_expiry, } -
A better way to orgainize django-channels one to one private chat models?
I want to model the database table of a django channels private chat in the most effective way possible so that retrieving the messages would not take a lot of time. For that I have create a one to one room since every two users should have their unique room. And I created a separate message table with a foreign key relation with the (oneToOneRoom) table.But what bothers me is that since the sender and the receiver of the message can only be one of the two users of the room I do not want set (sender and receiver) as foreign Key to the users table. Can I have a better implementation of that. Or is their any other way of modeling those tables. Any help would be highly appreciated. Here is the models.py file. class singleOneToOneRoom(models.Model): first_user = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="first_user", blank=True, null=True) second_user = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="second_user", blank=True, null=True) room_name = models.CharField(max_length=200, blank=True, unique=True) def __str__(self): return f"{self.first_user}-{self.second_user}-room" class Meta: unique_together = ["first_user", "second_user"] class messages(models.Model): room = models.ForeignKey( singleOneToOneRoom, on_delete=models.CASCADE, related_name="messages") message_body = models.TextField() sender = models.ForeignKey( User, on_delete=models.CASCADE, related_name="msg_sender") receiver = models.ForeignKey( User, on_delete=models.CASCADE, related_name="msg_receiver") date_sent = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.sender}_to_{self.receiver}" -
TypeError: 'module' object is not iterable in django 4
TypeError: 'module' object is not iterable in django 4 Hi Team, I am getting the above error, it has persisted long enough than at this point I really need help. I am using pickle to load an ML model, Django to get user input. Below is the error, my urls.py file and the views.py file. Any Help will be highly appreciated. All Code in my GitHub. ******* When starting the server I get this Error Message ******* (python10_env) D:\Online Drives\MDigital\CIT-Letures\python10_env\smart_health_consult>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\urls\resolvers.py", line 634, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces … -
Why does Environ not set the variable in a Django project root other than the main?
So I have a .env file in my Django project root containing several variables. When I use them within the same project root (e.g. in settings.py) it works, but once I try to access a variable within another root/module it fails: # other root than .env import environ # Initialise environment variables env = environ.Env() environ.Env.read_env() # Get the iCloud application password via env mail_password = env('MAIL_PW') # --> returns django.core.exceptions.ImproperlyConfigured: Set the MAIL_PW environment variable This however works: # same root as .env import os import environ # Initialise environment variables env = environ.Env() environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') -
Initiating a GET request to Django web api and send a list of ids as an array
I'm trying to call a rest API in django and send a list of Ids as a paremeter (I can't use query string). This works if I send only one, but how to specify it for an array of integers: path('details/<int:id>/', views.get_details), def get_details(request, id=0) What if I have a method that will take a list of Ids: def get_data(request, ids=[]) How should the url be defined so that the ids array is populated? -
Requests and requests_toolbelt not uploading file to django
I need to upload a file to a django app from a pyside2 desktop app, the upload code is running on a worker class using a QThread, it works when i upload the file using requests only. # Login login_url = 'http://127.0.0.1:8000/users/login' client = requests.session() client.get(login_url) csrftoken = client.cookies['csrftoken'] login_data = {'username': username, 'password': password, 'csrfmiddlewaretoken': csrftoken} response = client.post(login_url, data=login_data) # Upload upload_url = 'http://127.0.0.1:8000/upload' client.get(upload_url) csrftoken = client.cookies['csrftoken'] file = {'file': open(file[0], 'rb') response = client.post(upload_url, files=file, data={'csrfmiddlewaretoken': csrftoken}) but i'm trying to use requests_toolbelt to keep track of the upload progress. with the code below django says that the form is not receiving the file field. data = encoder.MultipartEncoder(fields={'file': open(file[0], 'rb'), 'csrfmiddlewaretoken': csrftoken}) monitor = encoder.MultipartEncoderMonitor(data, callback) response = client.post(upload_url, data=monitor, headers={'Content-Type': monitor.content_type}) but if i send the file in requests file attribute the QThread doesn't end. data = {'csrfmiddlewaretoken': csrftoken} file = encoder.MultipartEncoder(fields={'file': open(file[0], 'rb')}) monitor = encoder.MultipartEncoderMonitor(file, callback) response = client.post(upload_url, file=monitor, data=data, headers={'Content-Type': monitor.content_type}) -
I want to be able to check multiple users, and only choose a single option per user AND send all selected users in a list in template/html
So, I couldn't get a simple title, sorry for that. Basically, I want to send a message to X users. For this I need to select the users that I want to send this message to, and their type, if they are normal, CC or CCI. Every single type of option has a single name, meaning that in the end I get a list of normal recipients, of CC recipients and CCI recipients. All of this using check-boxes, needing me to create a javascript event to recreate a radio-type of behavior for the options of a single user. I was wondering if there was a better option than this, by using radios? Here is how it's looking: CCI aren't implanted yet since I started to ask myself this question when I was asked to make them... Here is the code for one user, with the onclick event being the function that recreate radio behavior... <label class="dropdown-item text-wrap labelname" style="overflow-wrap: break-word; padding-left: 5px; padding-right: 0px;"> <input class="green form-check-input me-1 checkboxes-recipients recipientsmessage " id="green2" onclick="syncUnCheck(green2, gray2)" type="checkbox" value="invite" name="recipients[]"> <input class="gray form-check-input me-1 checkboxes-recipients recipientsmessage" id="gray2" onclick="syncUnCheck(gray2, green2)" type="checkbox" value="invite" name="recipientsCC[]"> invité </label> The problem of this function is that It doesn't … -
Chart.js is not being load in my Django project
Hi im new in programming and im learning/working on a django project an my im trying to use chart.js to show the chart of my expenses and i got this error occured: Here is my code of my urls django And i wanna add here that this error is occuring after i added 'expense/' in the 1st urls.. i added that because i want my home page to load first.. i mean if i remove 'expense/' from that 2nd path then it seems to work fine.. i'm unable to figure out what i did wrong..i know i did some stupid mistakes but im not being able to identify it. Thanks urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('homepage.urls')), path('expense/', include('expenses.urls')), path('authentication/', include('authentication.urls')), path('preferences/', include('userpreferences.urls')), path('income/', include('userincome.urls')), path('admin/', admin.site.urls), ] Then i have created an app for expenses aswell its urls.py from django.urls import path from . import views from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('',views.index,name="expenses"), path('add-expense', views.add_expense, name="add-expenses"), path('edit-expense/<int:id>', views.expense_edit, name="expense-edit"), path('expense-delete/<int:id>', views.delete_expense, name="expense-delete"), path('search-expenses', csrf_exempt(views.search_expenses), name="search_expenses"), path('expense_category_summary', views.expense_category_summary,name="expense_category_summary"), path('stats', views.stats_view,name="stats"), ] Its views.py from asyncore import write import string from tkinter.tix import COLUMN from unittest import result from urllib import response from … -
DJANGO CKEDITOR with placeholder plugin
I cant seem to get the PLACEHOLDER plugin to show in my django-ckeditor ... anyone else experience this? The latest version seems to be v4.11 (when clicking on the ? in the editor) though the pyp version says 6.2... and their release history says "ckeditor updated to 4.7" As the plugin for placeholder already exists in the ckeditor, i expected it to work str8 out of the box one i added it to the toolbar .... no luck If i cant get it to work, ill probably create my own [[ placeholder ]] and have a string replace function in python to merge db fields. Any suggestions would be appreciated. -
Django ORM - add rows to the result until the SUM('column') reaches to a given number
I have a model created using Django ORM - class Orders: units = models.IntegerField(null=False, blank=False) sell_price_per_unit = models.FloatField(null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False) order_status = models.ForeignKey(OrderStatus, on_delete=models.PROTECT, null=False, blank=False) property = models.ForeignKey(Property, on_delete=models.PROTECT, null=False, blank=False) order_type = models.ForeignKey(Property, on_delete=models.PROTECT, null=False, blank=False) ... ... I want to write a query to select_for_update() and the rows should be selected until the Sum('sell_price_per_unit') reaches a given number. Additionally I have to apply certain filter and exclude certain rows based on the condition. filter() & exclude() were pretty straight forward so I already took care of it but I have no idea of how to select rows until the Sum('sell_price_per_unit') reaches to a given number. queryset = ( Orders.objects.select_for_update() .exclude(created_by=created_by) .values( "id", "property", "units", "created_by", "sell_price_per_unit", "order_status", ) .filter( property=order_obj.property, order_type__name=SELL, order_status__in=[PARTIALLY_COMPLETED[1], OPEN[1]], sell_price_per_unit__lte=order_price, ) .order_by("sell_price_per_unit", "created_at") ) Is it possible to accomplish this? -
login issue for imported users in django
i have 2 django application and i want importing users with passwords to another application when i do this, i have problem for login imported users cant login Note : i have custom user model this 2 application have SAME SECRET_KEY and here is my login code GetDomain = Domains.objects.filter(domain=get_domain(HTTP_HOST=request.META['HTTP_HOST'])).first() Email = request.POST.get('mail', None) raw_password = request.POST.get('pass', None) recaptcha_response = request.POST.get('g-recaptcha-response', None) if Email is None: return HttpResponse(ajax_result(Code=200, message='ایمیل خالی است')) if raw_password is None: return HttpResponse(ajax_result(Code=200, message='پسورد خالی است')) if recaptcha_response is None: return HttpResponse(ajax_result(Code=200, message='کد امنیتی را وارد کنید')) GetUser = User.objects.filter(email=Email).first() if GetUser is not None and GetUser.is_active: if GetUser.aff != GetDomain.UseBy.username: return HttpResponse(ajax_result(Code=200, message='کاربر یافت نشد')) if RecaptchaValidator(recaptcha_response): if not GetUser.is_superuser and not GetUser.is_staff: DeleteLastSessions(GetUser) user = authenticate(username=GetUser.username, password=raw_password) try: login(request, user) except AttributeError: return HttpResponse(ajax_result(message='اطلاعات ورود اشتباه است')) GetUser.Browser = request.META['HTTP_USER_AGENT'] GetUser.IsLogin = True GetUser.LastLoginIP = GetIP(request) GetUser.save() if GetUser.is_superuser or GetUser.is_staff: SubmitLog(user=request.user, Part='ورود به پنل', Number=None, Information=None, IP=GetIP(request)) threading.Thread(target=WriteUserExtraInformation, args=(request, GetUser,), name='WI').start() if GetUser.NeedVerify: Context = '{"result" : "ok", "data": {"url":"/tickets/send?verify=1"}}' else: if 'next' in request.GET.keys(): Context = '{"result" : "ok", "data": {"url":"' + request.GET['next'] + '"}}' else: Context = '{"result" : "ok", "data": {"url":"/profile/"}}' response = HttpResponse(Context) response.set_cookie('app', 'True', secure=True) return response else: … -
Django ORM - Search Function Across Multiple Models
I am struggling to get my search function to pull in results from multiple models into a single table. I have a Person Model and a Dates Model: class Person(models.Model): personid = models.AutoField() name = models.CharField() etc.... class Dates(models.Model): datesid = models.AutoField() personid = models.ForeignKey(Person, models.DO_NOTHING) date_type = models.CharField() date = models.CharField() etc.... There will be multiple Dates per personid (many to one) what I am trying to do is return the newest date from Dates when a search is performed on the Person Model - View below: def search(request): if request.method == "POST": searched = request.POST.get('searched') stripsearched = searched.strip() results = Person.objects.filter( Q(searchterm1__icontains=stripsearched) | Q(searchterm12__icontains=stripsearched) | Q(searchterm3__contains=stripsearched) ).values('personid', 'name', 'address_1', 'address_2', 'address_3', 'code', 'number') How would I add in the Top 1 newest related Dates.date into this for each Person found in the "results" field ? View: {% for Person in results %} <tr> <td>{{ Person.name }}</a></td> <td >{{ Person.address_1 }}</td> <td >{{ Person.code }}</td> </tr> {% endfor %}