Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to improve tests for models with multiple foreign keys (Django)
I have a MVP for my testing suite, but my current style will be a beast to maintain. I am running into trouble efficiently writing tests for my model which has two Foreign Keys. I include my model.py file and my test.py file below: models.py class Category(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) class ProductCategoryValue(models.Model): value = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="categories") product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="products") class Meta: unique_together = [['category', 'product']] (The idea behind this model structure is that there can be a list of products and a list of categories, with the ProductCategoryValue to serve as the glue between the two lists. The list of categories may change later on in the project and I would like to easily modify the values of each product text with respect to that category. I am open to suggestions to improve this model structure as well!) test.py #... def setUp(self): p = Product(name="Touchscreen") p.save() Product.objects.create(name="Dancer") c = Category(name="Use Case", selection_type="bullets") c.save() Category.objects.create(name="Video Conferencincg", selection_type="text") Category.objects.create(name="Multisite", selection_type="Boolean") ProductCategoryValue.objects.create(value="foobar", product=p, category=c) Is this the canonical way of writing tests for models which have multiple foreign keys? I'm hoping that there is a more efficient way so that my testing … -
Django rest framework large file upload
Is there an easy way to upload large files from the client side to a django rest framework endpoint. In my application, users will be uploading very large files (>4gb). Browsers have a upload limit, here's the chart. My current idea is to upload the file in chunks from the client side and receive the chunks from the rest endpoint. But how will I do that? I saw some libraries like - resumable.js, tus.js, flow.js etc. But how will I handle the chunks in the backend? Is there any library that is actively maintained for a problem like this? Please help me. -
How to use detailview pk in createview
# models.py class NewBlank(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=50) description = models.CharField(max_length=100, blank=True) blank_on_off = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class BlankContent(models.Model): refer = models.TextField() memo = models.TextField() new_blank = models.ForeignKey('NewBlank', on_delete=models.CASCADE, related_name='blankcontent') # views.py class BlankDetail(LoginRequiredMixin, DetailView): model = NewBlank template_name = 'blank_app/blank_detail.html' context_object_name = 'blank' class BlankContentCreate(CreateView): model = BlankContent fields = "__all__" template_name = 'blank_app/new_blank_content_create.html' def get_success_url(self): return reverse_lazy('blank_detail', kwargs={'pk': self.object.new_blank.pk}) # urls.py urlpatterns = [ path('blank/<int:pk>/', BlankDetail.as_view(), name='blank_detail'), path('new-blank-content/', BlankContentCreate.as_view(), name='blank_content_create'), ] There is a creativeview in the detail view and I want to create a model in the detailview when I press it. So even if I don't specify the new_blank part, I want it to be filled automatically according to the pk in the detailview, what should I do? -
Django request + variable issues when Debug = True
I am getting a 500 error on all my pages except admin when I set debug to False in Django. (When Debug is True, everything works just fine.) When I look at my error log, I get a huge litany of errors, starting with the following: [20/Jul/2021 00:10:22] DEBUG [django.template:869] Exception while resolving variable 'self' in template '404.html'. I also get a number of "VariableDoesNotExist" errors for variables that are not even associated with the template in question. -
Django form is not valid in class based view
I'm currently working on a blog project where I have created a custom user model in which I intend on creating a Registration Form from this custom user model. I have my registration form that inherits from the UserCreationForm in Django. The form rendered properly in my template as it should but whenever I try registering a user the form is not valid. I'm not sure what I'm doing wrong. I'm looking forward to get some help from you brilliant people! :-) See the related usages below: models.py from django.contrib.auth import get_user_model from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) username = models.CharField(max_length=200, unique=True) email = models.EmailField(_('email address'), max_length=150, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] class Meta: ordering = ['-date_joined', 'username', 'email'] verbose_name = 'User' verbose_name_plural = 'Users' def __str__(self): return self.username.title() forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model class RegistrationForm(UserCreationForm): # confirm_password = forms.CharField(widget=forms.PasswordInput(attrs=registration_form_fields['confirm_password'])) class Meta: model = get_user_model() fields = ['first_name', … -
Sending a .zip file in Django?
I've been trying to send a .zip file via a POST request in Django but can't seem to work it out, here's what I've tried: def test_1(self): z = zipfile.ZipFile("test.zip") file = (io.BytesIO(b"abcdef"), z) res = self.client.post("/upload/", {"zip":file}, content_type="multipart/form-data") self.assertEqual(res.status_code, 200) def test_1(self): file = (io.BytesIO(b"abcdef"), "test.zip") res = self.client.post("/upload/", {"zip":file}, content_type="multipart/form-data") self.assertEqual(res.status_code, 200) def test_1(self): z = zipfile.ZipFile("test.zip") res = self.client.post("/upload/", {"zip":z}, content_type="multipart/form-data") self.assertEqual(res.status_code, 200) Every time I try to run the test it gets a status code of 400. Any ideas why? Here is the view: def upload(request): z = zipfile.ZipFile(request.FILES['zip']) for fi in z.namelist(): dirname = os.path.splitext(fi)[0] os.mkdir(dirname) content = io.BytesIO(z.read(fi)) zip_file = zipfile.ZipFile(content) for i in zip_file.namelist(): zip_file.extract(i, dirname) sum = os.path.getsize(dirname) shutil.rmtree(dirname) return HttpResponse(f"Success") The program works fine when running it normally, just not when being tested which makes me think I'm not sending the .zip file correctly. Here's the HTML that works: <form method="post" action="/upload/" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="zip"> <button type="submit">Upload</button> </form> -
How to get days from queryset using expressionwrapper
gap_condition = Attribute.objects.filter(Q(register_date__gte='2021-01-01')) \ .annotate(register_gap=ExpressionWrapper(F('create_date') - Cast(F('register_date'), DateTimeField()), output_field=DurationField())).values('register_gap') I Changed 'create_date' field from 'datetime' type to 'date' type to get the date difference between two fields. The result is output as a queryset.<QuerySet [{'register_gap': datetime.timedelta(days=1)}, {'register_gap': datetime.timedelta(days=1)}, {'register_gap': datetime.timedelta( 0)}, {'register_gap': datetime.timedelta(days=7)}, ...]> In this queryset, I want to extract only the days value, but if I use the .days syntax, an error is displayed saying that days cannot be extracted using expressionwrapper . Is there any other way? -
I am trying to create a login view that works for Customuser. Presently,the Loginform just redirects even when the fields are empty /incorrect input
I have allauth installed to handle the login yet, I don't seem to find a breakthrough with having a proper login as the redirect just takes everyone to the destination page without any authentication.. The signup works fine as I can see created users in the admin. Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'useraccount', 'crispy_forms', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', Views.py from django.contrib.auth import logout , login, authenticate from django.shortcuts import render,redirect from .forms import RegisterForm,LoginForm from django.urls import reverse_lazy from django.views.generic.edit import CreateView from django.http import request , HttpResponseRedirect def login_request(request): if request.method == 'POST': form = LoginForm(data=request.POST) email = request.POST.get('email') password = request.POST.get('password') if form.is_valid (): user = form.get_user () user = authenticate ( email=email , password=password ) login ( request , user ) return HttpResponseRedirect(reverse_lazy('dashboard')) else: form = LoginForm () return render ( request=request , template_name="useraccount/login.html" , context={"form": form} )' Urls.py from django.contrib import admin from django.urls import path , include from useraccount import views as c from useraccount import views as m from useraccount import views as a from django.contrib.auth import views as auth_views app_name = 'useraccount' urlpatterns = [ path ( 'admin/' , admin.site.urls ) , path ( '' , … -
Wagtail/Django - How to find the template name of wagtail root home page?
I have a root home page made using the default model that comes out of the box with Wagtail. I'm currently trying to create a navbar header that maps out children pages in the following manner: {% for menu_page in home_page.get_children.live.in_menu %} The problem here is, I'm using the wrong tag. Above I use home_page, but that does not seem to work. I am able to use: {% for menu_page in page.get_children.live.in_menu %} Which then lists out the menu_pages, but this does not work for a navbar because it won't always select children pages from the root, due to the general page tag. Any ideas on how I can locate the actual template or page name before adding the: page.get_children.live.in_menu . To re-iterate, I am using the out of the box home page model: from wagtail.core.models import Page class HomePage(Page): pass The title of the root page is called Home and the type is Home Page Thanks for any possible help. -
Should i have multiple update methods or just one
I am writing an update method to a Book model in python-django. I was wondering which way to write code is "best". I would like all the updates go through this "controller" class and not update the model directly. class Book(object): id: UUID name: str price: float quantity: int ... I can either have 1 update method that takes in **kwargs and updates the fields in the model class BookController: def update(self, **kwargs): for field, value in kwargs.items(): self.field = value self.save() I can have multiple methods that each updates a particular set of fields, based on usecase class BookController: def update_price(self, price) def update_quantity(self, quantity) def update_price_quantity(self, price, quantity) ... The first option obfuscates things, and makes it difficult to understand which fields are being updated. It can be used as a one-size fits all, but may lead to bugs as anyone can add any field in the caller. The second grows exponentially with more fields being added (the only constraint being the use cases needed) and also kinda ugly to look at. Is there a guideline or preferred way to structure this type of code ? -
Nested serializers doesn't return the correct data Django Rest
I have an Order app, with two models, order and order unit. Now the idea is that I need to make a nested serializer to take in both of them and then a nested view to display them. When I create an order, I can also put in how many units I want to order, so basically when product X is selected, I need the code to get the price for the product X so the user doesn't have to enter it. Thats the main issue here. Here's the models: class Order(models.Model): code = models.IntegerField(unique=True) code_year = models.IntegerField(null=True) date_registered = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(Customer, related_name='customer_orders', null=True, on_delete=models.CASCADE) creator = models.ForeignKey(User, related_name='orders', null=True, on_delete=models.CASCADE) class Order_unit(models.Model): order = models.ForeignKey(Order, related_name='orderunits_orders', null=True, on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='orderunits_products', null=True, on_delete=models.CASCADE) amount = models.IntegerField price = models.IntegerField This is the serializer that I set up: class OrderUnitSerializer(serializers.ModelSerializer): class Meta: model = Order_unit fields = ['order', 'product', 'amount', 'price'] class OrderSerializer(serializers.ModelSerializer): orderunits_orders = OrderUnitSerializer(many=True) class Meta: model = Order fields = [ 'id', 'code', 'code_year', 'date_registered', 'customer', 'creator', 'orderunits_orders' ] This is the view: class OrderListCreateAPIView(ListCreateAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer permission_classes = [AllowAny] def unit_detail_view(request): obj=Order_unit.objects.all() obj1=Product.objects.all() context={ 'order': obj.order, 'product': obj.product, 'amount': … -
Opening sweet alert.js on button click
I have the following button: <a class="btn btn-success" href="">Accept</a> I want to display a javascript sweet alert when it is clicked on For example, when the user clicks on it, I call swal("Hello world!"); How would I do this? -
using signals to create a model?
I have instructor and club models. I want when an instructor who is a supervisor is created, he/she will be assigned to a club that is equal to his/her department. I'm new to signals and not sure how to achieve it? models.py class Instructor(models.Model): dep_choice = ( (0, 'ISOM'), (1, 'Accounting'), (2, 'PA'), (3, 'Finance'), (4, 'Management & Marketing'), (5, 'Economics'), ) instructor_user = models.OneToOneField(MyUser, on_delete=models.CASCADE) department = models.IntegerField(choices=dep_choice, default=0) supervisor = models.BooleanField(default=False) def __str__(self): return str(self.instructor_user) class Club(models.Model): ISOM = 0 Accounting = 1 PA = 2 Finance = 3 ManagementandMarketing = 4 Economics = 5 club_name = ( (ISOM, 'ISOM'), (Accounting, 'Accounting'), (PA, 'PA'), (Finance, 'Finance'), (ManagementandMarketing, 'Management & Marketing'), (Economics, 'Economics'), ) instructor = models.OneToOneField(Instructor, on_delete=models.CASCADE) name = models.IntegerField(choices=club_name, default=0) def __str__(self): return self.get_name_display() signals.py from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from .models import Instructor, Student, Adminstrator, MyUser, Club @receiver(post_save, sender=Instructor) def post_save_create_instructor(sender, instance, created, **kwargs): if created: if instance.supervisor == True: Club.objects.create(instructor=instance) -
django null value in column violates not-null constraint postgres
I am attempting to have a form that a user can upload multiple images on their blog. When the user submits the form I get the error null value in column "post_id" of relation "blog_postimages" violates not-null constraint The form has a foreign key to the blogpost. What confuses me is that the value is not null and I am using it else where (pk). I am running a postgres db view def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) if request.method == 'POST': test = PostImagesForm(request.POST, request.FILES) files = request.FILES.getlist('images') if test.is_valid(): for f in files: test.save(commit=False) test.post = Post.objects.get(pk=pk) test.save() else: print(PostImagesForm.errors) context = { 'post':post, 'PostImagesForm':PostImagesForm, } return render(request, 'blog/post_detail.html', context) models class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default='default.jpg', upload_to='hero_car_image') content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class PostImages(models.Model): post = models.ForeignKey('Post', on_delete=models.CASCADE) images = models.ImageField(upload_to='post_images') date_posted = models.DateTimeField(default=timezone.now) I do not have any unapplied migrations and I am positive I am calling it properly. Even if I hard code in a number it still errors out. -
VaulueError: too many values to unpack (expected 2) Django 3.2.5
I have an orders model that displays the order status as a dropdown in the Django admin panel. class Orders(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for Delivery', 'Out for Delivery'), ('Delivered', 'Delivered'), ) customers = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) products = models.ForeignKey(Products, on_delete=models.SET_NULL, null=True) status = models.CharField(max_length=50, null=True, choices=STATUS) date_created = models.DateTimeField(auto_now_add=True, null=True) And I am rendering the models in the dashboard view def dashboard_view(request): customers = Customer.objects.all() orders = Orders.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter('Delivered').count() pending = orders.filter('Pending').count() context = {'customers': customers, 'orders': orders,'total_orders': total_orders, 'delivered': delivered, 'pending': pending} return render(request, "account/dashboard.html", context) while filtering the string 'Delivered' from class Orders, Django throws me a ValueError saying that 'too many values to unpack (expected 2)' This is my first Django implementation, any help is appreciated. Thank you! -
How to change ViewSet retrieve to filter data in Django?
I'm a neewbie building an API integrating a MongoDB with Django. My situation is that I want to retrieve the data of db A filtered against a parameter of db B, but I can't figure out how to properly edit the views(ViewSet). For instance, in db A there are collections of documents containing the fields: _id = ObjectId('some_id'), date = some_date and link = link_of_something, and in db B there are collections of documents containing: date = some_date and ids = list_of_some_ObjectId(str)_from_db_A. So, I want to retrieve just the db A links for which the ObjectId(str) are present in the ids list of db B, how can I do that? Thanks in advance, cheers -
I am building a webapplication using Django. I have created 3 models in models.py and want to connect the models using templates
I am building a web application for my college project.I am referring to the Django beginner book where they have built a blog post. I am using this as a reference to build a construction management application. I currently have 3 models as in the image. This is a screenshot of my models.py with this I have created class based views and the URLS for them. I want to start a new project from the client details page but i am not able to configure the url properly. I get the error TypeError at /client/1/update/ 'str' object is not a mapping I am stuck and not sure how to proceed further. Please let me know i can share more screenshots for the community. This is a screenshot of my models.py and this is my URLs -
Django / PostGreSQL: Create queryset grouped by 'date' when each row has a different timezone
Let's say I have two models: from django.db import model class Company(model.Model): name = models.TextField() timezone = models.TextField() class Sale(models.Model): amount = models.IntegerField() company = models.ForeignKey('Company') time = models.DateTimeField() I want to create a queryset grouped by date and company, where date refers to the calendar date of the sale at the timezone specified on the Company object. This query: result = Sale.objects.values( 'company', 'time__date' ).aggregate( models.Sum('amount') ) This returns the data in a format that works for me. However, the sales are grouped by UTC day. I want them grouped by the timezone on the Company objects. What is the cleanest, quickest way to do this? I know I could dump the entire set of values into Python, like this: result = Order.objects.values( 'amount', 'company__timezone', 'time' ).order_by( 'company_timezone' ) for r in result: r.date = r.time.astimezone(pytz.timezone(r.company_timezone)).date() and then groupby, but is there a better way? -
Django Celery Redis Auth
I'm trying to add Celery to django to schedule tasks. I use Redis backend, and connect via unix socket. Setup was working until I have tried using password auth to redis.conf: My settings.py: CELERY_BROKER_URL = 'redis+socket:///home/username/domain/redis.sock?password=mypasswd' CELERY_RESULT_BACKEND = 'redis+socket:///home/username/domain/redis.sock?password=mypasswd' celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'public_python.settings') # celery settings for the demo_project app = Celery('public_python') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() Result: [2021-07-19 21:22:14,003: ERROR/MainProcess] consumer: Cannot connect to redis+socket:///home/username/domain/redis.sock: Authentication required.. I have already tried adding: CELERY_REDIS_PASSWORD='mypasswd' (any any concievable combination of similar words), with no luck. -
Django template tags all() and count() don't work what should I do
I am very new to Django so bare with me. I have a model called Posts that looks like this: class Post(models.Model): author = models.ForeignKey(User,on_delete=CASCADE, related_name='posts') content = models.TextField(max_length=127) date = models.DateField(auto_now=True) objects = PostManager() def __str__(self): return f"{self.author} : {self.content} -- ({self.date})" And a model of Likes that looks like this: class Like(models.Model): post = models.ForeignKey(Post, on_delete=CASCADE, related_name='likes') user = models.ForeignKey(User, on_delete= CASCADE, related_name='liked') class Meta: unique_together = ('post', 'user') From the Like model I have a foreign key that points to my Post model. If I want to access the amount of likes a post has I write this in the shell: post1 = Post.objects.get(id =1) post1.likes.all().count() This is my view for rendering posts @require_GET def getposts(request): posts = Post.objects.order_by('-date').all() p = Paginator(posts, 10) someposts = p.page(int(request.GET.get('page', 1))) rendered_posts = render_to_string('network/posts.html', context={'page':someposts}) return JsonResponse({'posts': rendered_posts}) This is how post.html looks like {% for post in page.object_list%} <div class="post"> <ul class="post__head"> <li class="author">{{post.author.username}}</li> <li class="date">{{post.date}}</li> </ul> <p class="content">{{post.content}}</p> <div class="post__actions"> <span class="like__button"></span> <p class="like__amount">{{post.likes.all().count()}}</p> </div> </div> {% endfor %} Now this line is what's giving me trouble: <p class="like__amount">{{post.likes.all().count()}}</p> I get an error that I can't use all() and count() in my template I was wondering if there's a … -
'DiscordUser' object is not iterable
I'm trying to do login() with Discord OAuth2 and a custom authentication backend but I get an error. When a user logs in for the first time this error pops up, but if they log out and then log in again, it will work. The error is originating from discord_user_auth = list(discord_user_auth).pop() def discord_login_redirect(request, *args, **kwargs): code = request.GET.get("code") exchange_user = exchange_code(code) discord_user_auth = DiscordAuthenticationBackend.authenticate(request=request, user=exchange_user) discord_user_auth = list(discord_user_auth).pop() login(request, discord_user_auth) return redirect("/app") def exchange_code(code: str): data = { "client_id": client_id, "client_secret": "secret", "grant_type": "authorization_code", "code": code, "redirect_uri": "http://localhost:8000/app/oauth2/login/redirect", "scope": "identify guilds" } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } validate_token = requests.post("https://discord.com/api/oauth2/token", data=data, headers=headers) credentials = validate_token.json() access_token = credentials['access_token'] get_user_info = requests.get('https://discord.com/api/v9/users/@me', headers={ 'Authorization': 'Bearer %s' % access_token }) get_guilds = requests.get('https://discord.com/api/v9/users/@me/guilds', headers={ 'Authorization': 'Bearer %s' % access_token }) global guilds guilds = get_guilds.json() global user user = get_user_info.json() return user Full Traceback: Traceback (most recent call last): File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Internet\Desktop\Programming\Discord\exo_website\website\exo_dashboard\dashboard\home\views.py", line 186, in discord_login_redirect discord_user_auth = list(discord_user_auth).pop() TypeError: 'DiscordUser' object is not iterable -
Microsoft MSAL React SPA, and RESTful Django API
I don't know why I can't find confirmation in the docs, maybe I am not navigating them correctly, although MSAL seems to have options to fit it into any application. This is my first time integrating a SAML sso procedure into any of my web-apps. I am just looking for some clarity on the correct, and secure way to verify the person attempting to login, is actually logged in with the IDP. I am confused at the part after confirmation of login is given to my redirect API, I currently have it all happening on the front-end, then submitting the response to my back-end. Which is a RESTful API built with Django, and postgres database. At this point, I am thinking I need to verify my accessToken for authenticity, but I am unsure if I should be creating another PublicClient instance in python, and then sending the same commands to the IDP. To guess at this point, I'm thinking this is wrong, as I need to verify the token, rather than get another Access and Refresh token. I'm thinking I just need to verify there is a session open with the IDP, and that the Access Token matches. Can anyone … -
Why Django memcached always return none?
I have 2 different cache type as follow: (I am using MySQL connector because the client wants it like this.) import os,sys from pathlib import Path sys.path.append(os.path.dirname(os.path.abspath('.'))) os.environ['DJANGO_SETTINGS_MODULE'] = 'api.settings' import django django.setup() import mysql.connector from django.core.cache import cache,caches db_crawl = mysql.connector.connect( host="xx.xx.xx.xx", user="xxx", password="xxxx", database="xxx" ) cursor_crawl = db_crawl.cursor(dictionary=True) def marketprices(): query = "some query here" cursor_crawl.execute(query) result = cursor_crawl.fetchall() m_cache = caches['marketprice'] m_cache.set('marketprices', result,1024 * 1024 * 1024) The query output has about 18 MB cache and I want to hold the cache 1024 * 1024 * 1024 times. My cache settings: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': BASE_DIR.joinpath('caches'), 'TIMEOUT':None, 'OPTIONS': { 'server_max_value_length': 1024 * 1024 * 1024, } }, 'marketprice': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT':None, }, } I set and start the Memcached in my server and everything works fine. The service Memcached status is: ● memcached.service - memcached daemon Loaded: loaded (/lib/systemd/system/memcached.service; enabled; vendor preset: enabled) Active: active (running) since Mon 2021-07-19 22:33:49 +03; 1h 10min ago Docs: man:memcached(1) Main PID: 2126782 (memcached) Tasks: 10 (limit: 72283) Memory: 1.6M CGroup: /system.slice/memcached.service └─2126782 /usr/bin/memcached -I 256M -m 8192 -p 11211 -u memcache -l 127.0.0.1 -P /var/run/memcached/memcached.pid Jul 19 22:33:49 vmi552735.contaboserver.net systemd[1]: Started memcached daemon. … -
How can I define a base style.css file for a Django application
I am making a project in Django where I have multiple apps. For this project I defined a base.html where I have my navbar and my footer. Now I am looking to add a css file that would be available for all the apps for having a common background image. What I ended up doing is making a static folder into the project folder however django is complaining that it can not get the static file from there. How can I manage this base style.css file? My folder structure is like this: --Project |-- Project | |--static | |--Project | |--style.css |-- App1 |-- App2 |-- App3 My intention is to be able to use the style.css classes in App1, App2 and App3. The message that I get is that django can not collect the Project/style.css file because the ~/Project/Project/static folder does not exist. -
Why is Django taking so long for system checks with PostGreSQL-backend? [import 'django.db.models.sql.compiler' # <_frozen_importlib]
Even though I have used stackOverflow since ages to enlarge my programming-horizone, this is actually my ever first question on this platform and I'm pretty excited . So I set up a webpage/webapplication that is powered by Django. Previously I utilized a MySQL database as backend and everything worked out smooth, but then I tried to switch to PostGreSQL. To set up a PostGreSQL database I leveraged the Postgres.app, and followed the instructions to integrate it into Django. But when I now try to start the server in the shell with python3 manage.py runserver it keeps getting stuck at the following message: Performing system checks... From there it takes a very long time (circa 7-8 minutes) with my computer using a lot of CPU until finally the server starts with no issues: System check identified no issues (0 silenced). July 19, 2021 - 21:17:38 Django version 3.2.5, using settings 'ApolloPostGreDB.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. When I stop the process it returns [skipped lines with "..."]: import 'gc' # <class '_frozen_importlib.BuiltinImporter'> # clear builtins._ # clear sys.path # clear sys.argv # clear sys.ps1 # clear sys.ps2 # clear sys.last_type # clear sys.last_value # clear sys.last_traceback …