Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Provide http_method_names based on REMOTE_ADDR?
I overwrite get_serializer_context method in Viewset and add IP whitelist. if request REMOTE_ADD not int whitelist only return http_method ['GET'], else return ['GET','POST','DELETE','PUT']. class TestModelViewSet(ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer def get_serializer_context(self): context = super().get_serializer_context() context.update({ 'address':['8.8.8.8'] }) return context def _allowed_methods(self): check = self.get_serializer().context['address'] if self.request.META['REMOTE_ADDR'] not in check: return ['GET'] return ['GET','POST','DELETE','PUT'] Now I get error: AttributeError:TestModelViewSet object has no attribute 'format_kwarg -
Is it Possible to create Django Admin form like change_form_template with the help of RESTApi
i want to replace the default form template with my new new_changeform.html with RESTApi with all POST, GET, PATCH,etc. class ContentAdmin(admin.ModelAdmin): change_form_template = "new_changeform.html" -
How add multiple data to Parent with ForeignKey(filter_horizontal) relation with Child in django admin?
I want to add multiple child data to the each parent where i can add and remove child data which belongs to the respective parents. Is it possible to do that thing without ManyToMany Relationship. class ParentIndustry(models.Model): name = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return str(self.name) class Industry(models.Model): industry = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) parent_industry = models.ForeignKey( 'ParentIndustry', null=True, blank=True, related_name='parent_industry', on_delete=models.SET_NULL, default=None) def __str__(self): return str(self.market) How can i modify my admin so that i can do the above operation. I want to filter the child usingfilter_horizontal class ParentIndustriesAdmin(admin.ModelAdmin): list_display = ('id', 'name') search_fields = ['id', 'name', ] filter_horizontal = ['Have to add filter too'] ordering = ['-date_modified'] def save_model(self, request, obj, form, change): obj.modified_by = request.user obj.save() admin.site.register(ParentIndustry, ParentIndustriesAdmin) Thank you -
Page not found (Django)
I'm making website using Python Framework of 'Django'. I have some problems with Django about entering. The page for http://127.0.0.1:8000/blog/archive/2021/1%EC%9B%94/ should be uploaded when the January link is clicked, otherwise Page not found (404) will appear. I'd like to know what's wrong and how to fix it. blog/urls.py contains: from django.urls import path, re_path from blog import views app_name='blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<str:month>/', views.PostMonthArchiveView.as_view(), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<str:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] blog/views.py contains: from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field = 'modify_dt' make_object_list = True class PostMonthArchiveView(MonthArchiveView): model = Post date_field = 'modify_dt' class PostDayArchiveView(DayArchiveView): model = Post date_field = 'modify_dt' class PostTodayArchiveView(TodayArchiveView): model = Post date_field … -
How to raise errors in ListApiView DRF
class GetFollowers(ListAPIView): """ Returns the users who follw user,along with weather the visiter — the one who sent api request — follows them or they follow him/her """ permission_classes = [IsAuthenticated,] serializer_class = None def get_queryset(self,*args,**kwargs): user = self.request.data.get('user',None) if user is None: pass followers_obj, created = Follow.objects.get_or_create(user=user) all_followers = followers_obj.followers.all() Now , when a user sends a request , along with the one's username , in query_params, whose he/ she wants to get followes, how do I return an error if the sender doesn't follow the one whom he wants to get followers. -
ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' in Jenkins
I am trying to deploy Django app in windows using Jenkins. It is getting "no such file or directory" but the file is exists. How do I solve that issue. anyone help me? -
django redis cache bytes
I use django redis. settings.py CACHES = { 'register': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': os.getenv('REDIS_REGISTER'), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } views.py def test(request): register_db = caches['register'] uuid4 = uuid.uuid4().hex image_path = f'./static/uploads/register/1/247688.jpg' print(f'uuid: {uuid4}, image_path: {image_path}') register_db.set(uuid4, image_path) print(register_db.get(uuid4)) output uuid: ddddc2e9b86940619d1b7cef2699bfe2, image_path: ./static/uploads/register/1/247688.jpg ./static/uploads/register/1/247688.jpg mytest.py register_db = redis.Redis(host='localhost', port=6379, db=1, decode_responses=False) for i in register_db.keys(): for key in register_db.keys(): print(f'key: {key}, value: {register_db.get(key)}') output key: b':1:ddddc2e9b86940619d1b7cef2699bfe2', value: b'\x80\x04\x95*\x00\x00\x00\x00\x00\x00\x00\x8c&./static/uploads/register/1/247688.jpg\x94.' Why is it different after Django puts in the data, redis takes it out? Is there any way to solve. I hope the result. value: ./static/uploads/register/1/247688.jpg' -
I'm integrating Stripe payment gateway in my app, but neither token nor the ref_code is being generated?
Please let me know if anyone has the idea how to use it? Thanks in advanced. class PaymentView(View): def get(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False, 'STRIPE_PUBLIC_KEY': settings.STRIPE_PUBLIC_KEY } return render(self.request, 'payment.html', context) else: messages.warning(self.request, "You've not added billing address.") return redirect('e_commerce:checkout') def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total()*100) # cents try: charge = stripe.Charge.create( amount=amount, currency="usd", source=token ) # order.ordered = True # create the payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order_items = order.items.all() order_items.update(ordered=True) for item in order_items: item.save() order.ordered = True order.payment = payment # TODO assign ref code order.ref_code = create_ref_code() order.save() # print("your order placed!") messages.success(self.request, "your order was successful.") return redirect("/e_commerce") except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught body = e.json_body err = body.get('error', {}) messages.warning(self.request, f"{err.get('messages')}") return redirect("/e_commerce") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.warning(self.request, "Rate limit error") return redirect("/e_commerce") except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.warning(self.request, "Invalid parameters ,Please try again!") … -
django.db.utils.OperationalError: no such table in SQLite3 database
I am getting the following error when trying to migrate my data, which I am trying to troubleshoot but I cannot identify where the error is occurring. For context, I created a new app within my project for a webpage on change impacts, and I copied most of the code from my book app to start it out. It looks like somewhere, my code is mixing the two apps (must've been somewhere that I forgot to update) and is trying to add data into a table that doesn't exist (and shouldn't). Any idea how to identify where this is happening, or any flags to look out that would be causing this? Operations to perform: Apply all migrations: admin, auth, books_cbv, books_fbv, books_fbv_user, change_impacts, communications, contenttypes, sessions Running migrations: Applying books_cbv.0006_auto_20210107_2150...Traceback (most recent call last): File "C:\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: books_cbv_changeimpacts The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python38\lib\site-packages\django\core\management\base.py", line 323, in … -
How to settup django login in the header?
I am trying to setup user login in the header, that way, the user can login/logout at any point in the web. However I must have missunderstood the Django tutorials. I am kind of a newbie with Django and I am not entirely sure of how to accomplish this, so any help is welcome. I would like to clarify also, that I do not wish to redirect to another template. If possible, just reload the current page with the user already authenticated. I tried 2 things: add action="{% url 'sign_in' %}" in the header form add action="{% url 'accounts_login' %}" in the header form And neither seems to work. My app name is 'web' My project name is 'core' # core/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('django.contrib.auth.urls')), path('rest/', include('rest_framework.urls')), path('', include('web.urls')) ] # web/urls.py from django.contrib.auth.views import LoginView from django.urls import path from . import views urlpatterns = [ path('', views.base), path('sign_in', views.sign_in, name='sign_in'), path('accounts/login/', LoginView.as_view(template_name='base.html'), name='accounts_login') ] # wev/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.contrib.auth import authenticate, login, logout import requests def base(request): context = { 'user': request.user } return … -
Custom user model in django to use phone and email both for sign up
By default django uses the USERNAME_FIELD for authentication but it takes only one field. But i want my signup form to let users sign up by using phone number or by their email, like it happens in facebook . Can anybody help me how can i achieve this ? -
django.db.utils.IntegrityError: UNIQUE constraint failed: mode_setting.user_id
I am new to Javascript, I am currently learning to debug errors that I am receiving in the Console. In my project I am adding a theme choosing option for each user logged into the website. Currently, it is showing the 2 themes when I click the buttons but it is not saving the theme for each user. I have created an app in my Django Project and everything is as covered in the tutorial I am following except that in the console I am receiving errors every time I select a theme from the buttons: (index):573 POST http://127.0.0.1:8000/update_theme/ 500 (Internal Server Error) and in the Terminal this error: django.db.utils.IntegrityError: UNIQUE constraint failed: mode_setting.user_id Here is the base template: <link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet"> <!-- Mode --> <div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right"> <button onclick="swapStyles('app-light.css')" type="button" class="btn btn-secondary">Light Mode</button> <button onclick="swapStyles('app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button> </div> <!-- Mode --> Javascript <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? … -
Error db_table is used by multiple models: Django
Im confused what does this error mean?, when I tried to transfer my project to another pc and runs using python manage.py runserver this error will display. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance. -
mod_wsgi (pid=*): Target WSGI script '/root/project/wsgi.py' cannot be loaded as Python
getting this error when making website live. When path set in wsgi WSGIDaemonProcess demo python-path=/root/election python-home=/root/venv WSGIProcessGroup demo WSGIScriptAlias / /root/election/election/wsgi.py this is error from my logs mod_wsgi (pid=*): Target WSGI script '/root/election/election/wsgi.py' cannot be loaded as Python m$[time] [wsgi:error] [pid 17712:tid 140454280738560] [remote 43.241.144.192:527] mod_wsgi (pid=*): Exception occurred processing WSGI script '/root/election/election/wsgi.py'. Traceback (most recent call last): File "/root/election/election/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' I verified that path is correctly specified that is as below path to wsgi /root/election/election/wsgi.py virtual env path /root/venv tried reinstalling wsgi by below command. but still error not solved $ sudo apt-get remove libapache2-mod-python libapache2-mod-wsgi $ sudo apt-get install libapache2-mod-wsgi-py3 I even given persmission of 777 to my project directory and virtualevn still geting this error output of these command ask other peoples so. It is as below. >>> django.__file__ '/root/venv/lib/python3.8/site-packages/django/__init__.py' >>> import sys >>> sys.prefix '/root/venv' followed this and googled other answers but although this question asked many time and duplicated but still it is is not answerd. -
How to create a form in Django from a model with multiple ForeignKey and ManytoManyField fields?
I am a Django newbie. I cannot figure out how to create a form that properly displays my model, which has two ForeignKey fields and three ManytoManyFields. I am familiar with creating forms from more simple models, but I'm stuck on this one. So far, I've tried ModelForm and used ModelChoiceField for ForeignKey relationships, but that did not work. When viewing the form, the fields options did not render. I then tried inlineformset_factory but I could not find helpful examples. Any help is appreciated. models.py class Animal(models.Model): name = models.CharField(max_length=500, blank=False, null=False) **type = models.ForeignKey(Type, on_delete=models.SET_NULL, blank=False, null=True)** **ageGroup = models.ForeignKey(AgeGroup, max_length=300, on_delete=models.SET_NULL, blank=False, null=True)** ageYears = models.PositiveIntegerField(blank=False, null=False) ageMonths = models.PositiveIntegerField(blank=True, null=True) sex = models.CharField(max_length=100, choices=SEX, blank=False, null=False, default='NA') city = models.CharField(max_length=200, blank=True, null=True) state = models.CharField(max_length=200, blank=True, null=True) country = models.CharField(max_length=250, blank=True, null=True) **breedGroup = models.ManyToManyField(BreedGroup, blank=False)** **breed = models.ManyToManyField(Breed, blank=False)** tagLine = models.CharField(max_length=300, blank=False, null=False) goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information') goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information') goodWKids = models.BooleanField(null=False, blank=False, default='Not Enough Information') profilePic = ResizedImageField(size=[300, 450], quality=100, upload_to='media/', default='', null=True, blank=True, keep_meta=False) **contact = models.ForeignKey(ContactDetails, on_delete=models.SET_NULL, blank=False, null=True)** forms.py class AnimalDetailsForm(ModelForm): type = ModelChoiceField(queryset=Type.objects.all()) #doesn't work ageGroup = ModelChoiceField(queryset=AgeGroup.objects.all()) #doesn't work #breed = … -
Why django ORM .filter() two way binding my data?
Let's say I store my query result temporarily to a variable temp_doc = Document.objects.filter(detail=res) and then I want to insert some data in said model and will be something like this p = Document(detail=res) p.save() note that res are object from other model to make some FK relation. For some reason the temp_doc will contain the new data. Are .filter() supposed to work like that? Because with .get() the data inside temp_doc don't change -
Using multiple filters for django text?
I have a model called article that has a field for the content of the article: content = RichTextField() I am trying to add two filters to it: safe and linebreaks. However when I do this: {{article.content|safe|linebreaks}} Only the first filter works. Does anyone know the syntax to use multiple filters? Thanks y'all! -
Is there a better way to load Django static directories for multiple apps than this? Thank you
I currently have the following in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') #add app-specific static directory STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'project/static'), os.path.join(BASE_DIR, 'project/apps/blog/static/'), os.path.join(BASE_DIR, 'project/apps/users/static/'), os.path.join(BASE_DIR, 'project/apps/comments/static/'), os.path.join(BASE_DIR, 'project/apps/categories/static/'), ) Should I be doing this in one line? Thanks very much. -
Cannot connect to Websocket after deploying with docker-compose+daphne+nginx
I have an application running in Docker which is using django 2.2 (Django DRF) + channels 3, daphne, nginx. Now I'm trying to deploy the application. DRF APIs are working fine, but supervisord shows that asgi is repeating spawned and exited, and when the frontend app(react) tries to connect to the websocket it shows 500 error. This doesn't occur in my local. I've been looking for the error messages on Google but couldn't find answers. Looks like it comes from my misconfiguration, but I have no idea. This is my docker-compose. version: '2' services: db: build: ../containers/mysql ports: - "3306:3306" env_file: staging.env volumes: - ./mysql:/var/lib/mysql - ../containers/mysql/conf:/etc/mysql/conf.d - ../containers/mysql/init:/docker-entrypoint-initdb.d redis: image: redis ports: - "6379:6379" django: build: ../containers/django command: daphne -b 0.0.0.0 -p 8001 myapp.asgi:application volumes: - ../../myapp:/code - ../../logs/django:/var/log/django - ../../logs/uwsgi:/var/log/uwsgi - ../../logs/supervisor:/var/log/supervisor ports: - "8002:8001" links: - db - redis depends_on: - db - redis entrypoint: ./scripts/wait-for-it.sh db:3306 --strict -- supervisor: build: ../containers/django command: /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf volumes_from: - django volumes: - ../containers/django/supervisord.conf:/etc/supervisor/supervisord.conf - ../../daphne:/run/daphne ports: - "9999" links: - db - redis depends_on: - django entrypoint: ./scripts/wait-for-it.sh django:8001 -- nginx: image: nginx ports: - "80:80" - "443:443" links: - django depends_on: - django volumes: - ../../myapp:/code … -
Django Error: Reverse for 'like_post' with arguments '('',)' not found
Full error: Reverse for 'like_post' with arguments '('',)' not found. 2 pattern(s) tried: ['like/(?P[0-9]+)$', 'home/like/(?P[0-9]+)$'] views.py: def like_post(request, pk): post = Post.objects.get(id=pk) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) post.dislikes.remove(request.user) liked = True return HttpResponseRedirect(reverse('home-new')) The above code works if i put form action to the url that calls the view but it refreshes the page when i like a post so im trying to call the view through javascript instead so i tried this templates: <script> $(document).on('submit','#like_form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url 'like_post' item.id %}', success:function(){ } }); }); </script> {% block content %} {% for item in products %} <div class="item_btns_container"> <div class="like_btn_form_container"> <form id="like_form">//was action="{% url 'like_post' item.id %}" {% csrf_token %} {% if user in item.likes.all %} <button type="submit" class="liked_post" name="post_id" value="{{ item.id }}"><div class="liked_btn" >Like</div></button> {% else %} <button type="submit" class="like_btn" name="post_id" value="{{ item.id }}"><div class="liked_btn">Like</div></button> {% endif %} </form> </div> {% endfor %} {% endblock content %} i also tried this with a different view def like_post(request, pk): post = Post.objects.get(id=pk) liked = False if request.method == 'POST': if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) post.dislikes.remove(request.user) liked = True return render(request, 'new.html') -
Should I sent images through JSON
I'm new to Django, and I'm building a REST backend for my iOS app, I figured out encode an Image to it's Base64 data, and I would like to use it together with some texts, is it a good idea to put it into the JSON for the rest of the data or is it better to use another request to download each image data. I'm guessing that separating concerns is the best way, and have two GET request to retrieve the data, but I just want to be sure!. OPTION A { "owner": { "username": "lilysmith", "email": "lily@email.com", "first_name": "Lily", "last_name": "Smith" }, "is_user_page": true, "title": "Lily Smith", "subtitle": "Photographer", "about": [ { "icon": "🇺🇸", "label": "Austin, TX" } ], "photos": [ { "position": 2, "description": "I love hiking", "photo": "/9j/2wCEAAgGBg....CEAAgGBg" <- (The rest of the binary data) } ] } OPTION B (Separating Concern) The same JSON response, but instead of image data, using it's id. Then getting it just the data through another request, but esencially making the front end handle two or more request to server. -
Django Model default call back not adding beyond 10
I was hoping someone can assist with my issue in that when I used a default callback my 'account_number' field gets an Integrity Error when above 10. Without a default callback, I have no issues and it works. My Account Model: def account_number_increment(): last_number = Account.objects.all().order_by("account_number").last() print("I am the last number") start_from = AccountSettings.account_number_startfrom print("I am the start from") acc_number = '1' if last_number is None: print("I am the initiator") return acc_number if start_from != '' or start_from is not None: while Account.objects.all().filter(account_number=start_from).exists(): acc_number_start = int(last_number.account_number) + 1 print("acc # from start from", str(acc_number_start)) return str(acc_number_start) if last_number: # last_number.refresh_from_db(fields="account_number") # last_number.refresh_from_db() while Account.objects.all().filter(account_number=last_number.account_number).exists(): print("BEFORE addition", last_number.account_number) new_acc_number = int(last_number.account_number) + 1 print("acc # new number", str(new_acc_number)) return str(new_acc_number) class Account(models.Model): name = models.CharField(max_length=100, null=True, blank=True) address = models.OneToOneField(Address, on_delete=models.SET_NULL, blank=True, null=True, related_name="account_address") account_number = models.CharField(max_length=20, default=account_number_increment, null=True, blank=True, unique=True) # account_number = models.CharField(max_length=20, default='1def') # works with for loop in views. date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.name My Account_Settings Model class AccountSettings(models.Model): account_number_startfrom = models.CharField(max_length=100, default='1', blank=True, null=True) def __str__(self): return f'{self.job_number_startfrom}, {self.account_number_startfrom}, {self.invoice_number_startfrom}' My views def index(request): if request.method == 'POST': form1 = AccountForm(prefix='form1', data=request.POST) form2 = AccountForm(prefix='form2', data=request.POST) if … -
Navbar image not loading in production environment
I am building a website with Django and bootstrap. I added an image to my navbar which is in a 'base.html' which I use as a template for my other html files. The image loads in development but doesn't appear in production. I'm using Heroku to host and deploy my app and google drive storage as my backend file storage for user uploaded-files. The navbar also uses another static file with the resume button and it works fine. base.html header <header> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container py-2"> <a class="navbar-brand" href="{% url 'homepage' %}"> <span class="d-flex align-items-center"> <img class="mx-3" src="{% static 'logo (200px).png' %}" width='70' alt=""> <h4> MAVERON AGUARES </h4> </span> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs- target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-end" id="navbarNavAltMarkup"> <div class="navbar-nav ml-auto"> <h5> <a class="nav-link " aria-current="page" href="{% static 'Sample Resume.pdf' %}">Resume</a> </h5> <h5> <a class="nav-link " aria-current="page" href="{% url 'blogHomePage' %}">Blog</a> </h5> </div> </div> </div> </nav> </header> settings.py STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'personalportfolio/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE = 'Mave-Aguares-Portfolio-55b70982536d.json' GOOGLE_DRIVE_STORAGE_MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', projects.views.homepage, name='homepage'), … -
where does "create()" method comes from in django
I just want to know where create method comes from in django. I checked Model class, BaseManager class and so on. I cannot find where create method is defined. Anyone knows about it ? https://github.com/django/django/blob/2d6179c819010f6a9d00835d5893c4593c0b85a0/django/ -
How to optimize Django DateTimeField for null value lookups in postgres
I have a problem with deeper undestanding of indexing and its positive side. Lets assume such model class SupportTicket(models.Model): content = models.TextField() closed_at = models.DateTimeField(default=None) to keep it clean I do not add is_closed boolean field as it would be redundant (since closed_at == None implies that ticket is open). As you can imagine the open Tickets will be looked up and called more frequently and thats why I would like to optimize it database-wise. I am using postgres and my desired effect is to speed up this filter active_tickets = SupportTicket.objects.filter(closed_at__isnull=True) I know that postgres support DateTime indexing but I have no knowleadge nor experience with null/not null speed ups. My guess looks like this class SupportTicket(models.Model): class Meta: indexes = [models.Index( name='ticket_open_condition', fields=['closed_at'], condition=Q(closed_at__isnull=True)) ] content = models.TextField() closed_at = models.DateTimeField(default=None) but I have no idea if it will speed up the query at all. The db will grow in about 200 Tickets a day and will be queried at around 10 000 a day. I know its not that much but UX (speed) really matters here. I will be grateful for any suggestions on how to improve this model definition.