Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django using bulk_update to update all records
With 2.2 we now have the option to bulk update: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#bulk-update I have a model with say millions of rows and I want to efficiently update all the records. I am trying to use bulk_update, but which means I still have to load all the model objects in the memory, modify the field one by one and then use bulk update: What I am doing: def migrate_event_ip_to_property(apps, schema_editor): Event = apps.get_model('app' 'Event') events = Event.objects.all() for event in events: if event.ip: event.properties["$ip"] = event.ip Event.objects.bulk_update(events, ['properties'], 10000) Since there are millions of records, can I avoid doing Event.objects.all() and load all objects into the memory even while using bulk_update? -
djang-bootstrap avoid label tag being added when calling `field|bootstrap`
How to avoid label tag being added when calling field|bootstrap. I have the below code filter.py import django_filters from .models import Issue class IssuesFilter(django_filters.FilterSet): summary = django_filters.CharFilter(label="Summary", lookup_expr="icontains") class Meta: model = Issue Views.py def index(request): issues = IssuesFilter(request.GET, queryset=Issue.objects.all()) context = { 'user': request.user, 'message': 'LogedIn', 'filter': issues } return render(request, 'testApp/index.html', context) index.html {% extends "firstPage/base.html" %} {% load bootstrap %} {% load render_table from django_tables2 %} {% load crispy_forms_tags %} {% block body %} <form method="GET"> <table> {% for field in filter.form %} <tr class="table table-borderless"> <td>{{ field.label_tag }}</td> <td>{{ field|bootstrap }}</td> </tr> {% endfor %} </table> <button type="submit" class="btn btn-primary">Search</button> </form> {% endblock %} When I add field|bootstrap I could see the label tag of the field is displayed. Is it possible to remove additional label tag from being added? -
How to filter useing look up method "in or range" and make sure if any of the item in the list is not available then returns empty queryset
My code snippet: filtered_queryset = Model.objects.filter( Q(model_one__status="OPEN") & Q(model_two__date__range=[start_date, end_date]) & Q(model_two__model_three__pk__in=model_three_id_list) & Q(model_two__something_to_sell__gte=F("model_two__already_sold") + requested_amount) ) In the above snippet I want the following line to work such a way that if some date is missing then it should not return others. What actually happens in range/in operator is that if it finds one or more matching data it returns those data in the queryset. But that's not what I need. I need to make sure that if all the date matches then only return the queryset otherwise it should be empty. Q(model_two__date__range=[start_date, end_date]) We can also use "in" operator if the solution for in operator is possible. In this case code snippet will be: Q(model_two__date__in=date_list) -
Django: implement multiple user levels / roles / types
I have been using Django for quite a while but never have I thought of this until now. Currently, I have a project that contains different user levels. Usually, in my past experience, I only developed systems using Django with only two user levels which are superuser and normal/regular user. So my question is what are the effective ways to present these different user levels in the model/database? Here, I'm going to use a school system as an example and also provide some of my initial thoughts on implementing it. User levels: Admin (superuser & staff) Principle Teacher Students Method #1: Add new tables based on each user level from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): user = models.CharfieldField(max_length = 10, unique = True) class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class Priciple(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) Method #2: Add additional user types attributes in the User model from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): user = models.CharfieldField(max_length = 10, unique = True) is_superuser = models.BooleanField(default = False) is_staff = models.BooleanField(default = False) is_principle = models.BooleanField(default = False) is_teacher … -
Django Many to Many Varible errot
when i add to user from many to many relation with this code Profile.objects.get(user=request.user).sad.add(Sad.objects.get(id=15)) it add but when i replace them with variable like this Profile.objects.get(user=request.user).playlist2[name].add(playlist3[name].objects.get(id=request.POST.get(playlist2[name]))) and i print varibale and it return with same sad Sad 15 get this error -
Django deletes table data on its own
iam using Django rest framework , react.js for the frontend and postgresql...the problem which i think its weird django deletes product table data on its own after a while i dont know why ...iam using django since a year and i have never seen this before. this is my model class products(models.Model): name=models.CharField(max_length=50) Barcode=models.CharField(max_length=50) category=models.ForeignKey(category,on_delete=models.CASCADE) description=models.TextField() quantity=models.IntegerField(default=100) price=models.FloatField(default=100.0) image=models.ImageField(upload_to='pics',default='') cost=models.FloatField(default=100.0) branch=models.ForeignKey(branch,on_delete=models.CASCADE) def __str__(self): return self.name -
Django installation issues
i configured django and apache on an ec2 server with a connection to a remote rds server. which is working fine. i can access the ec2 server and the database (via ssh to the ec2 server and then to the rds server) i tried to run a migration with sudo python manage.py and it worked. the database shows my tables. i use virtual environment with the python mod_wsgi installed which is loaded in the apache2.conf and in the 000-default.conf i have the wsgi daemon process, and script references. when i try to run the application through my browser i get a 500 internal server error with the following error message: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? mod_wsgi (pid=7875): Target WSGI script '/var/www/wuyeguanli/wuyeapp/wuyeapp/wsgi.py' does not contain WSGI application 'application'. the complete error message -
Django - accessing related objects in a template
How can I access a related object in a django template? I simply want to display the post title of the the bookmark at my template. Assuming the following view and model(s): def my_bookmarks(request): if request.method == 'GET': list_my_bookmarks = sorted( chain( UserBookmarks.objects.filter(user=request.user), ), key=attrgetter('date_added'), reverse=True ) paginator = Paginator(list_my_bookmarks, 20) # Show 20 bookmarks per page page = request.GET.get('page') my_bookmarks = paginator.get_page(page) user = request.user args = {'user': user, 'my_bookmarks': my_bookmarks, } return render(request, 'App/my_bookmarks.html', args) bookmarkable_post_models = models.Q(app_label='App', model='post') | models.Q(app_label='App', model='model-b') | models.Q(app_label='App', model='model-c') class UserBookmarks(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) content_type = models.ForeignKey(ContentType, limit_choices_to=bookmarkable_post_models, related_name='bookmarks', related_query_name='bookmark', on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=50, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=20) content = models.TextField(verbose_name="Content of Post") ... bookmarks = GenericRelation(UserBookmarks, related_query_name='post') Accessing the bookmark objects itself does not seem to be a problem if I do: {{ my_bookmarks }} at my template but i dont understand how to access the post element behind the bookmark Thanks for reading -
issue in setting up tornado.web.Application
In tornado (python) instead of creating an instance of tornado.web.Application(), I tried to make changes in the class while calling it using init. import tornado.web import tornado.httpserver import tornado.ioloop import tornado.options import os.path from tornado.options import define, options define("port", default=8000, help="run on the given port", type=int) class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html", page_title="My Bookstore | HOME", header_text="Welcome to My Bookstore!") class Application(tornado.web.Application): def __init__(self): handlers = [ (r'/', MainHandler), ] settings = dict( template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirname(__file__), "static"), debug = True ) tornado.web.Application(self, handlers, **settings) if __name__ == "__main__": tornado.options.parse_command_line() #Note: not creating an instance of application here ('app'), just creating a list of handlers and a dict of settings and passing it to the superclass. http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() But I'm getting this error, Traceback (most recent call last): File "main.py", line 44, in <module> http_server = tornado.httpserver.HTTPServer(Application()) File "main.py", line 27, in __init__ tornado.web.Application(self, handlers, **settings) File "C:\Python\Python37\lib\site-packages\tornado\web.py", line 2065, in __init__ handlers = list(handlers or []) TypeError: 'Application' object is not iterable What is the error, and how can I solve it? -
Dramatiq: Attempted relative import with no known parent package
Using Django framework with Dramatiq for multithreading. Currently when trying to initiate a worker I receive the following error. I have no issue compiling this import through the initial boot of the server. Is there anything I'm missing in the below code? Lower Half of Error [2020-04-05 18:28:24,920] [PID 5520] [MainThread] [dramatiq.WorkerProcess(0)] [ERROR] Failed to import module. Traceback (most recent call last): File "c:\program files\python38\lib\site-packages\dramatiq\cli.py", line 330, in worker_process module, broker = import_broker(args.broker) File "c:\program files\python38\lib\site-packages\dramatiq\cli.py", line 120, in import_broker module, broker = import_object(value) File "c:\program files\python38\lib\site-packages\dramatiq\cli.py", line 109, in import_object module = importlib.import_module(modname) File "c:\program files\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File ".\splitter.py", line 10, in <module> from .models import Highlight, Testdata, Video ImportError: attempted relative import with no known parent package from splitter.py - the … -
conditional editing in django model
I am trying to find a way to update fields values automatically like when a user update the Type Action, Status and finish time fields get updated also.for example: if Type == 'On store' Action == 'Requested' and Status == 'Pending' and Time_Finished == Today the model goes like this class order(models.Model): Time_Registered = models.DateField(blank=False) Number = models.CharField(max_length=500) Type = models.ForeignKey(Type, on_delete=models.CASCADE) Action = models.CharField(max_length=500, blank=True, null=True, choices=ACTION) Status = models.ForeignKey(Status, on_delete=models.CASCADE) Time_Finished = models.DateField(blank=False) -
How do I model a registration system with the following relationship constraints in Django?
I am trying to create a hackathon management system web application using Django. Each hackathon can have as many participating universities as possible (No constraints here).Now, each participating university can have at most 3 teams and each team can have at most 4 persons (1-4). I'm new to Django so help would be much appreciated. from django.db import models class Hackathon(models.Model): name = models.CharField(max_length=50,blank=True,default='') eventId = models.CharField(max_length=50, blank=True, default='') startDate = models.DateField(null=True) endDate = models.DateField(null=True) location = models.TextField(max_length=100, blank=True, default='') description = models.TextField(max_length=800, blank=True, default='') #participants = models.ManyToManyField(...)?? def __str__(self): return self.name class University(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Team(models.Model): team_name = models.CharField(max_length=50) member_count = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(4)]) uni = models.ForeignKey(University, on_delete = models.CASCADE) def __str__(self): return self.team_name class Person(models.Model): name = models.CharField(max_length=50) belongs_to = models.ForeignKey(Team,on_delete = models.CASCADE) -
ConnectionError in Twilio Django
when i try to integrate with twilio service to verify a mobile number: client = twilio.rest.Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) verification = client.verify \ .services(TWILIO_SERVICE_SID) \ .verifications \ .create(to='+'+country_code+phone, channel='sms') i get that error HTTPSConnectionPool(host='verify.twilio.com', port=443): Max retries exceeded with url: /v2/Services/V*****************/Verifications (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f4a3884f150>: Failed to establish a new connection: [Errno -2] Name or service not known',)) any help? -
Manager isn't available; 'auth.User' has been swapped for 'account.Account'
I get always the error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'account.Account' When I go on http://127.0.0.1:8003/register everything works, when I press the "submit" button i get that error. I tried different solutions but still I can't understand the error. account/admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from account.models import Account class AccountAdmin(UserAdmin): list_display = ('email','username','date_joined', 'last_login', 'is_admin','is_staff') search_fields = ('email','username',) readonly_fields=('date_joined', 'last_login') filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Account, AccountAdmin) account/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm #CustomUserCreationForm from django.contrib.auth import authenticate from account.models import Account class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Add a valid email address.') class Meta: model = Account fields = ('email', 'username', 'password1', 'password2', ) account/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", … -
django using cached database query problem
I have django application witch save traffic logs . the problem is when we refresh page doesnt show new logs its like query set cached some where. I made a manager to return last n log. this is my code from django.db.models import Manager class LogMannager(Manager): def _last(self,num,server=None,camera=None): if camera: return self.get_queryset().filter(camera=camera).order_by('-id')[:num] elif server: return self.get_queryset().filter(server=server).order_by('-id')[:num] else: ret = self.get_queryset().all().order_by('-id')[:num] print(ret) return ret the server is in production and using uwsgi -
how to access child model from parent model
I am trying to get data from child model through the parent model, I don't know if it possible or there is a way of doing it, I would be grateful for any solution models.py class Client_Data(models.Model): RC = models.CharField(max_length=50) Raison_social = models.CharField(max_length=254) NIF = models.CharField(max_length=50,unique=True) AI = models.CharField(max_length=50,unique=True) NIS = models.CharField(max_length=50,unique=True) Banque = models.CharField(max_length=50,unique=True) CB = models.CharField(max_length=50) adresse = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) active = models.BooleanField(default=True) class Contact(models.Model): client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE) Nom = models.CharField(max_length=50) post = models.CharField(max_length=50) Tel = models.CharField(max_length=50) email = models.EmailField(max_length=255,unique=True) contact_type = models.CharField(default='Client_contact',max_length=50) views.py def client_update(request,slug): book = get_object_or_404(Client_Data, slug=slug) contact = Contact.objects.select_related().filter(client=book.id) print(contact) if request.method == 'POST': form = ClientForm(request.POST, instance=book) contact_form = Contact_Form(request.POST, instance=contact) else: form = ClientForm(instance=book) contact_form = Contact_Form(instance=contact) return save_client_form(request, form,contact_form ,'Client_Section/partial_client_update.html') -
TypeError: save() missing 1 required positional argument: 'self' in djjango
my code: from django.shortcuts import render,redirect from django.contrib.auth.models import User # Create your views here. def register(request): if request.method=='POST': first_name=request.POST['first_name'] last_name=request.POST['last_name'] username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] email=request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): print("usernmae taken") elif User.objects.filter(email=email).exists(): print("email taken") else: user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) User.save(); print("user created") else: print("passwords not matching") return redirect('/') else: return render(request,'register.html') my console log: File "E:\coding\fyp\travel\accounts\views.py", line 21, in register User.save(); TypeError: save() missing 1 required positional argument: 'self' [05/Apr/2020 11:49:59] "POST /accounts/register HTTP/1.1" 500 69154 E:\coding\fyp\travel>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 05, 2020 - 11:52:09 Django version 2.2.5, using settings 'travel.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ignore lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll -
RelatedObjectDoesNotExist: User has no seller
Here I am trying to save the Seller into the Order model after a Customer places a successful order. As the logged in User is a Customer so it shows RelatedObjectDoesNotExist: User has no seller. But I want to save the Seller after a Customer places an order, so that the Seller can be notified that the Seller has a new order. But in the Order Model where seller = models.ForeignKey(Seller, blank=True, null=True, on_delete=models.CASCADE), here it doesn't save the seller. 'cart views.py` def checkout(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect('cart:cart') login_form = CustomerLoginForm() signin_form = CreateCustomerForm() address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) address_qs = None customer = request.user.customer seller = request.user.seller if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter(billing_profile=billing_profile) order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj, customer, seller) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get(id=billing_address_id) del request.session["billing_address_id"] if billing_address_id or shipping_address_id: order_obj.save() if request.method == "POST": is_done = order_obj.check_done() if is_done: order_obj.mark_paid() request.session['cart_items'] = "" del request.session['cart_id'] return redirect("cart:success") context = { 'object':order_obj, 'billing_profile':billing_profile, 'login_form':login_form, 'signin_form': signin_form, 'address_form':address_form, 'address_qs': address_qs, } return render(request, 'cart/checkout.html', context) accounts models.py … -
How do I make Django CRUD front-end easy to use like WordPress? Are there any libraries or plugins?
we are trying to create a crowdsourced open database on the temple. We have started using Django as the backend. One issue we have is the frontend where users will contribute is not as easy as WordPress. For example, while entering tags a popup opens when you want to create new(Whereas WordPress automatically cerates). Same with Images. Uploads one by one. So is there a frontend plugin or addition which will make it more user friendly. -
no such table: main.auth_user__old while saving tables in the section area
I am following the net ninja tutorial for Django and I ran into this problem in the admin section while saving the tables in the admin section area. -
How to bind form in Django when it has others parameters
I'm trying to perform .is_valid() after a POST request with my form. form = DrinkForm(request.POST) Like this, the "problem" is that this form has other parameters. forms.py: class DrinkForm(forms.Form): def __init__(self, language, account_id, configurations, *args, **kwargs): super(DrinkForm, self).__init__(*args, **kwargs) translation.activate(language) With this, I don't know how to make my form bound (and I can't find any guide or example about this case). When I print my form called in view with its regular parameters it's everything ok, but if I add request.POST I get nothing. form_ok = DrinkForm('english', request.session['account_id'], configurations) # OK form_not_ok = DrinkForm(request.POST) # Needs parameters form_how_to = DrinkForm('english', request.session['account_id'], configurations, request.POST) # How to? -
How to implement an object specific modal in Django?
I'm new to Django and I have a problem moving my stuff to the front end of my website. I want to do fantasy-style website. My main page will display a list of NHL players. These players will be picked by the user and added to their team in order . My problem is this: I want a popup-style modal to open when a user clicks a player on the main page. This modal would contain a confirmation before this specific player is added to the user's team. Here is my player model: class Player(models.Model): name = models.CharField(max_length=30) position = models.CharField(max_length=5) Here is my main page view: def main_page(request): players = Player.objects.all() my_dict = {"players":players} return render(request, 'my_app/main_page.html', context=my_dict) Here is my template for the main page: {% extends "my_app/base.html" %} {% block body_block %} <button onclick="document.getElementById({{player.name}}).style.display='block'" class="w3-button w3-black">Open Modal</button> <div class="w3-modal-content"> <div class="w3-container"> <span onclick="document.getElementById({{player.name}}).style.display='none'" class="w3-button w3-display-topright">&times;</span> <p>{{player.position}}</p> </div> </div> {% for player in players %} <tr> <th>{{player.name}}</th> <th onclick="document.getElementById({{player.name}}).style.display='block'" class="w3-button w3-black" width="100%">Open Modal</th> </tr> {% endif %} {% endblock %} As you can see, I would like the modal popup to display the player's position. Unfortunately, not only is the modal not working, I have no clue how … -
Advance String/JSON formatting using a multilevel JSON/dict/Template in python
I want to replace text in 1 JSON using the keys mapped from a second json. Both the JSONs are dynamic and first JSON can be modified to use keys from second JSON. text_to_replace = json.dumps([{"type": "data", "layerName": "THIS IS Mohit", "property": "Source Text", "expression": "time > 4 ? 'This is {groom.first_name}' : 'This is {groom.first_name}'", "composition": "01 Oliver"}, {"type": "data", "layerName": "THIS IS {bride.first_name}", "property": "Source Text", "expression": "time > 4 ? 'This is Aashi' : 'This is {bride.first_name}'", "composition": "02 Amelia"}, {"type": "data", "layerName": "January 2020", "property": "Source Text", "expression": "time > 4 ? '21st January 2021' : '21st January 2021'", "composition": "03 November"}, {"type": "data", "layerName": "JANUARY 2020", "property": "Source Text", "expression": "time > 4 ? '21st January 2021' : '21st January 2021'", "composition": "02 Date"}]) context = {'function_list': [ {'name': 'Xbbd', 'venue': 'Xbxb\nXnx', 'time': '06:00 AM', 'date': '19th April 2020', 'date_d_m_y_hyphen': '19-Apr-2020', 'timestamp': 1587234600.0, 'date_hindi': '19 अप्रैल 2020', 'date_hindi_A': 'रविवार', 'date_hindi_B': 'अप्रैल', 'effective_date': '19th Apr 2020', 'effective_day': 'Sunday', 'effective_time': '06:00 AM Onwards', 'effective_month': None}], 'primary': {'first_name': 'Bride Name', 'last_name': 'Gshs', 'fathers_name': 'Sbsb', 'mothers_name': 'Bsb', 'grand_fathers_name': 'Sbdb', 'grand_mothers_name': 'Sb', 'effective_name': 'Bride Name Gshs', 'effective_parents_message': 'Daughter of \nSbsb & Bsb', 'effective_grand_parents_message': 'Grand Daughter of \nSbdb & Sb'}, 'secondary': … -
Issue with Hiding Django SECRET_KEY Using environment variables
I am running my programs and Django Project on an AWS EC2 Ubuntu instance in a virtual environment. The django project is run on an apache server. For purposes of this question I will say that my secret key is 'AAAA'. I have an environment variable set ("SECRET_KEY"). It is properly setup, and when I put: import os print(os.environ['SECRET_KEY']) in the python shell, it prints the proper secret key, AAAA. Therefore, I know python is able to access the proper environment variable. In settings.py, when SECRET_KEY='AAAA', the project works, and everything executes properly. However when I change this to: SECRET_KEY=os.environ['SECRET_KEY'] the server doesn't work (500 Internal Server Error). Everything seems like it should work. Any suggestions or ideas on what I missed here? -
using a property method in list_filter in custom admin
I have a model like this: class CustomUser(AbstractUser): @property def is_paid(self): return self.apayment4thisuser.all().filter(expirydate__gt=timezone.now().date()).count()>0 in the customadmin I am able to add this under my list display, but it is throwing error when I add it to my list filter: class CustomUserAdmin(UserAdmin): model = CustomUser list_filter = ['app_user','is_paid'] list_display = ['id', 'username', 'email', 'is_paid', ] This is the error: ERRORS: <class 'users.admin.CustomUserAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'is_paid', which does not refer to a Field. I was wondering is there not any way to add this to list_filter? Thanks,