Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What exactly is the cause to my InconsistentMigrationHistory in Django
I've noticed that there's some question on this website about this and i've got some solution from them. but my goal with this question is to know the exact problem so I can avoid this in the future and some extra solution is fine I've had this issue after I applied my custom user model account.models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models class Account(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) username = models.CharField(max_length=255) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email fakeapp.models.py from django.db import models from django.conf import settings # from django.contrib.auth.models import User # Create your models here. class Text(models.Model): text = models.CharField(max_length=30) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.text for some more context before I made this custom user model I was using default User model and I've already made data stored in the Text table with it. So by best guess is that is why this error occurred. Is that true or maybe there's other things that caused this?. -
django production server allow user to access requirements.txt and other file like manage.py
I find a big security breaches server allow user to access files example: a user can access https://example.com/app_directory/requirements.txt and the worst is i can download all file.py by doing https://example.com/app_directory/site/manage.py Content-Encoding deflate can be the cause. How can i fix that? -
Can't Send Mails on given schedule using Django Crontab
Hi i want to send emails to clients in every 1 minute. I follow this https://pypi.org/project/django-crontab/ documentation but it works only when i want to create objects in my models but it will not work on sending mail. The data i want to send through my mail is fetch from mysql database and i want to send this data as a tabular form in HTML. Code Not work and also i can't find my error. Here is my cron.py from django.shortcuts import render from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from .models import Test from project.settings import EMAIL_HOST_USER from django.http import HttpResponse def my_scheduled_job(): query= Test.objects.all() html_content = render_to_string("email.html",{'result':query}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives( "Today Test Report", text_content, EMAIL_HOST_USER, ['reiever@gmail.com'] ) msg.attach_alternative(html,"text/html") msg.send() Here is my email.html file <!DOCTYPE html> <html> <head> <title>Report</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </head> <body> <table class="table table-dark"> <thead> <tr> <th scope="col">Testing Name</th> <th scope="col">Testing Date</th> </tr> </thead> <tbody> {% for i in result %} <tr> <td>{{ i.test_name}}</td> <td>{{ i.test_date}}</td> </tr> {% endfor %} </tbody> </table> </body> </html> Here is my models.py file from django.db import models … -
Django webhooks
Need help in creating and understanding webhooks in Django.From where should I start ? How should I get to learn to implement a simple webhook in which I pass 2,3 parameters like id and name and it should get printed through the URL into the view without any third party or package. -
Django api stopped working as postgres uses 100% cpu on ubuntu server?
I have deployed a Django application on a 32GB ram ubuntu server while calling an API CPU uses reaching 100% due to Postgres, which I track through the top command. Postres configuration is already tuned up. Please suggest how to resolve thi. -
Filter queryset using child object fields
I have two models Parent, Child class Parent(models.Model): id = models.IntegerField(...) class Child(models.Model) id = models.IntegerField(...) parent = models.ForeignKey(Parent, ...) wanted = models.CharField(default="yes") I want to filter all Parent objects where all the children present with that parent will have 'wanted' as 'yes' My code: def containsYes(self): yes_ids = [] qs = self.get_queryset() for q in qs: children = Child.objects.filter(parent_id = q.id) count = children .count() if children.filter(wanted = 'yes).count() == count yes_ids.append(q.id) return qs.filter(id__contains = yes_ids) I know that this code is dead inefficient, and want a better solution using only querys PS: Im new to django -
Query on BooleanFields using string representations of the fields
How can I filter on the boolean fields of a model, given a string representation of the attribute, taken to mean true for that attribute? As an example, given: class MealBooking(models.Model): breakfast = models.BooleanField() lunch = models.BooleanField() dinner = models.BooleanField() meal = "breakfast" How can I filter on all MealBookings containing True for the field represented by meal? -
Django DRF unit tests added with dynamic mixins via metaclass not being executed
I am trying to test DRF endpoints, and trying to add mixings dynamically to a test in order to execute tests again each method allowed in the endpoint (get, post, put, patch, delete) So, my idea is to make a base test class that will automatically add some mixings to test endpoints if they are allowed. And I can create the actual test that will inherit from this base class. The code: from rest_framework.test import APITestCase class GetTestMixin: def test_get_all(self): response = self.client.get(self.uri) self.assertEqual(response.status_code,status.HTTP_200_OK) class AutoMixinMeta(type): def __call__(cls, *args, **kwargs): allowed_methods = ['get', 'post'] # cls would be the Test class, for example TestExample # cls.__bases__ is a tuple with the classes inherited in the Test class, for example: # (<class 'unit_tests.endpoints.base_test.RESTTestCase'>, <class 'rest_framework.test.APITestCase'>) bases = cls.__bases__ for method in allowed_methods: bases += (cls.method_mixins[method.lower()],) # Create a new instance with all the mixins cls = type(cls.__name__, bases, dict(cls.__dict__)) return type.__call__(cls, *args, **kwargs) class RESTTestCase(metaclass=AutoMixinMeta): uri = None method_mixins = { 'post': PostTestMixin, 'get': GetTestMixin, } class TestExample(RESTTestCase, APITestCase): uri = reverse('somemodel-list') I was expecting test_get_all to be executed, but it is not. Mixings are in place. I made a dummy method inside TestExample and put a debugger in place, and … -
Django Tenant with permissions
I'm working on a small project using Django Tenants package https://django-tenants.readthedocs.io/en/latest/install.html, and i would like to know how can i use permissions since i'm using different schemas, Thank you -
Is there a way to force usage of the DB Router, even if some model queries have specific the database using
We have a legacy project where traditionally developers explicitly specified the database to be used like so:- Fruits.objects.using('db_xyz').filter(id__in=12,23) But now we have introduced a custom DB Router that decides the DB to be used, thus taking away the decision from every individual that writes such code. This works very well. But we still need to fix all older code to avoid passing "using", since doing this causes the DB Router to get bypassed. My question is, is there any way that we can force usage of the DB Router, even for model usage that specifies the database to be used? Basicall, the above code exists in 100s of places, and we don't want to have to fix it in all places to look like Fruits.objects.filter(id__in=12,23) -
what exactly does request.user return in django, can we compare it with a string?
I am new to Django and trying out somethings. I am thinking to return a page named "in_accessable.html" if a normal user access the "\create" page (which calls the function named medicine_create_view"), else medicine_create.html. The name of admin is "npend" so I gave a if statement to check if the user name is 'npend' or not, I used request.user method to get the user name, even if I access the page with admin I am getting a false in if statment I tried printing request.user == "npend", which prints False every time. Can anyone help me rectifing this problem, Thank You. Code Used: def medicine_create_view(request, *args,**kwargs): my_form = Raw_Medicine_Form() if request.method == 'POST': my_form = Raw_Medicine_Form(request.POST) if my_form.is_valid(): print(my_form.cleaned_data) Medicine.objects.create(**my_form.cleaned_data) else: print(my_form.errors) my_form = Raw_Medicine_Form() context ={ "form" : my_form, } #print(request.user=="npend") if(request.user=="npend"): return render(request,"App_1/medicine_create.html",context) else: return render(request,"error_files/not_acessable.html",{}) -
Member is not adding in Group after Accept Request
I am building a simple BlogGroupApp in which users can make a group and post blogs init, AND i build feature of join group by Request, in which user have to send a join request and then creater will approve it, BUT When i click on accept_it then members is not adding in group. models.py class Group(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.ForeignKey(max_length=30,default='') members = models.ManyToManyField(User,related_name='group_member',blank=True) class GroupRequest(models.Model): group = models.ForeignKey(Group,on_delete=models.CASCADE) request_sender = models.ForeignKey(User, on_delete=models.CASCADE) views.py def accept_it(request,pk): group_request = get_object_or_404(Group,pk=pk) sent_request = get_object_or_404(GroupRequest,pk=pk) group_request.members.add(sent_request.request_sender) return redirect('home') Group_detail.html {% for requests in group_requests %} {{ requests.request_sender }}<a href="{% url 'accept_it' requests.id %}">Accept it</a> {% endfor %} When i click on Accept it then it redirects on another group BUT is is not adding the member in the group. AND When i try <a href="{% url 'accept_it' requests.request_sender.id %}">Accept it</a> Then it is saying :- Page not found (404) I have no idea, what am i doing wrong. Any help would be much Appreciated. Thank You in Advance. -
What is the thing wrong with my code ? It is not working
enter image description here This is the code in image :- <div class="m-3 p-3"> <a href="#" data-toggle="modal" data-target="#exampleModal" class="btn btn-outline-info border rounded col-lg-3 float-right">Check out</a> </div> -
How to use same backend (django) api cookie to frontend(vuejs)?
I've got confusion when dealing with cookies on frontend vs backend. I've a cookie generated in backend as class JWTAuthentication(BaseAuthentication): def authenticate(self, request): token = request.COOKIES.get('jwt') if not token: return None try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed('unauthenticated') user = get_user_model().objects.filter(id=payload['id']).first() if user is None: raise exceptions.AuthenticationFailed("Unauthenticated") return (user, None) When i use login in frontend vuejs, a cookie is generated through api , which cookie is a also added by frontend and marked as httpOnly . I want to use same cookie without making new one in frontend. In frontend When I console.log document.cookie the generated cookie is not available , although it shows cookies generated, but at same time at backend when i access api and see console.log(document.cookie) it is available there. How can i access access that cookie even in frontend, through vuejs/javascript through document.cookie , so that i can do authentication and global guards in frontend. Thank you for helping. -
POST request authentication from django to link another apps
Login on my django "localhost" want to authenticate user login at http://mylink.com/api/login token is "123123123123". how to make authentication and session after login? -
Integrate Django as a consumer with AWS Api Gateway Websockets
I'm not sure how to do it. I've looked for in almost all the network and information is not clear and confuse. I have a websocket done in AWS ApiGateway Websocket. I'm trying to connect to my websocket path from Django, the idea is to pass the information retrieved by Django to HTML to do a dynamic website. I know I can do this directly from the HTML template using javascript but, the websocket is would be open for whatever person and couldn't protect it. For that reason I'm trying to do it by Django. I've found information about channels library but the examples found are not clear due to the Websocket server used on these examples are localhost while my websocket server has a AWS path. I really appreciate your help -
How to get the product title name in the product image model
class Product(models.Model): TYPE_CHOICES = ( ('T-Shirt', 'T Shirt'), ) title = models.CharField(max_length=120) description = models.TextField() price = models.CharField(max_length=10) type = models.CharField(max_length=12, choices=TYPE_CHOICES) bestselling = models.BooleanField() def __str__(self): return self.title class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='images/' + str(product.)) def __str__(self): return self.image.url -
Issue with Django rendering raw queryset to template
i'm pretty new to Django so still trying to understand some concepts. I'm trying to render the text from a simple CharField in a template. I would like this to be used throughout the project so i've made a context_processors.py file to handle this Models.py class HeaderCustomisation(models.Model): small_banner_text = models.CharField(blank=False, null=False, max_length=200, default="Welcome") class Meta: verbose_name_plural = 'Header Customisation' def __str__(self): return self.small_banner_text Views.py def header_customisation(request): header_customisation = HeaderCustomisation.objects.all() context = { 'header_customisation' : header_customisation, } return render(request, 'includes/header.html', context) Context_processors.py from home.views import HeaderCustomisation def header_customisation_processor(request): header_customisation = HeaderCustomisation.objects.all() return {'header_customisation': header_customisation} header.html <div id="delivery-banner" class="row text-center bg-black"> <div class="col free-delivery-wrap"> <h5 class="free-delivery-text my-1">{{ header_customisation }}!</h5> </div> </div> This renders the text from the Model but renders the raw query, like so: If anyone can help or point me in the right direction to only returning the CharField value, that would be much appreciated. Also, if any additional info is needed i'll be happy to provide. Thanks! -
ERROR: Could not find a version that satisfies the requirement Django==1.10.5 from versions: none ERROR: No matching distribution found Django==1.10.5
[enter image description here] [1]WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)",)': /simple/django/ C:\dev\django\entornos\srh\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py:164: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecurePlatformWarning, enter image description here -
Django virtual env locate
I've bought a new pc, and I downloaded my django project, which was saved in one drive, but when I open it in vs code, I can manipulate the .py files but not any other. I suppose this is because of not having the pipenv enabled. I had saved the pipenv on a pendrive, but how can I activate it now? Here goes a picture of the pipenv folder I saved: 1 2 -
The filter function on my model return me <QuerySet []>
I have this models in my models.py I'm trying to send my Purchase details and return that as a json, but the myModel.objects.filter function return me a void QuerySet objects class Purchase(models.Model): total = models.IntegerField() date = models.DateTimeField(auto_now=True) user_phone = models.CharField(max_length=50) id_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) class Purchase_detail(models.Model): id_product = models.ForeignKey(Product, on_delete=models.CASCADE) id_purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE) quantity= models.IntegerField() price = models.IntegerField() But when a trying to do Purchase_detail.objets.filter don't work def see_purchase_detail(request, id): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': purchase_detail = json.loads(serializers.serialize( 'json', Purchase_detail.objects.filter(id_purchase=id) )) print(purchase_detail, Purchase_detail.objects.filter(id_purchase=id)) return JsonResponse({'details': purchase_detail}, safe=False) else: return JsonResponse({None}, safe=False) -
One Project Two Apps Two Static Folder - django
I have a problem about static files, I have two apps and I want to use different static file in each. Like {% load static1 %} <html><h1>App1</h1></html> {% load static2 %} <html><h1>App2</h1></html> STATICFILES_DIRS = [ BASE_DIR / "app1/static1", BASE_DIR / "app2/static2", ] How can I do that ? -
Django how to save object status in signals?
I am using signals in my model. The status of blog post will be pending for admin approval when any user try to edit existing blog post. But when I trying to change status from pending to published from my admin panel, it's keeping the old status "pending". here is my code: models.py def post_update(sender,instance,*args,**kwargs): if instance: instance = Blog.objects.filter(is_published="published").update(is_published="pending") post_save.connect(Blog.post_update,sender=Blog) -
Copy a directory recursively from Google Cloud Storage Bucket to another Google Cloud Storage Bucket using Django
I intend to copy a whole directory with all files and directories recursively from one Google Cloud Storage Bucket to another Google Cloud Storage Bucket. The following code works fine from local to a Google Cloud Storage Bucket : import glob from google.cloud import storage def upload_local_directory_to_gcs(local_path, bucket, gcs_path): assert os.path.isdir(local_path) for local_file in glob.glob(local_path + '/**'): if not os.path.isfile(local_file): upload_local_directory_to_gcs(local_file, bucket, gcs_path + "/" + os.path.basename(local_file)) else: remote_path = os.path.join(gcs_path, local_file[1 + len(local_path):]) blob = bucket.blob(remote_path) blob.upload_from_filename(local_file) upload_local_directory_to_gcs(local_path, bucket, BUCKET_FOLDER_DIR) How can I copy a directory recursively from one bucket to another in the same project ? -
Different django rest approach for urls.py, INSTALLED_APPS, apps.py
reading few similar topics in stackoverflow and https://docs.djangoproject.com/en/3.2/ref/applications/#configuring-applications Im still facing issue understanding proper way of handling urls. I'm following two REST API tutorials in which they differ from each other about urls.py's, settings.py, apps.py files. Having structure like this: ├───my_project │ └───api │ ├───apps.py | └───urls.py │ └───my_project | ├───urls.py | └───settings.py | └───manage.py Tutorial #1 my_project\api\apps.py from django.apps import AppConfig class ApiConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "api" ########### DIFF my_project\api\urls.py from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(prefix="symbols", viewset=views.SymbolsViewSet) urlpatterns = [ ########### DIFF path("", include(router.urls)), ########### DIFF ] ########### DIFF my_project\my_project\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/", include("api.urls")), ########### DIFF ] my_project\my_project\settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "api", ########### DIFF ] Tutorial #2 my_project\api\apps.py from django.apps import AppConfig class ApiConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "my_project.my_project.api" ########### DIFF my_project\api\urls.py from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(prefix="symbols", viewset=views.SymbolsViewSet) ########### DIFF Lack of 3 lines my_project\my_project\urls.py from django.contrib import admin from django.urls import path, include from my_project.my_project.api.urls import router urlpatterns = [ path("admin/", admin.site.urls), path("api/", include(router.urls)), ########### DIFF ] my_project\my_project\settings.py …