Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to apply a custom function to a specific field in a number of queries in Django
I have a simple model class Person(models.Model): name = models.CharField(max_length=20,default="") when I do Person.objects.all() I get Queryset with 20 results I want to apply a custom function def foo(name): return "Hello" + str(name) I don't want to use any loops is there any better method so that when I query I directly get these values -
How do I fix the warning "Cookie 'cookie_name' will be rejected soon ..." that I get after deleting the cookie?
Firefox throws the following warning after deleting a valid cookie: Cookie “cookie_name” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute. To know more about the “SameSite“ attribute, read https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite Scenario After a valid login I send a cookie to the frontend. This cookie can be used during my session without any problems or warning. The development console also shows me the expected values: SameSite: "Strict" and Secure: true. During the logout process the set cookie is removed by setting max-age=0 or expire=<date_in_past>. The browser deletes the cookie immediately as expected but I also get the warning mentioned above. It doesn't matter if I remove the cookie in the backend or frontend - the message will always be shown. Code Set Cookie - Backend (django): class Login(): def post(self, request): ... response = Response(status=status.HTTP_200_OK, ...) response.set_cookie("cookie_name", value, max_age=60*60*5, secure=True, httponly=False, samesite='strict') return response Remove Cookie - Frontend: (preferred way for this cookie in my scenario so far) function removeItem(key, path, domain) { ... document.cookie = encodeURIComponent(key) + // "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + "=; max-age=0" + (domain ? "; domain=" + domain : "") + … -
ModuleNotFoundError: No module named 'tastypie'
I am new to Django and coding in general. When I try to use the django-tastypie (0.14.4) in my virtual env using pipenv, I get the following error when I try to launch the server ModuleNotFoundError: No module named 'tastypie'. I tried the solutions in here and in here Here is my models.py of my api app: from tastypie.resources import ModelResource from movies.models import Movie class MovieResource(ModelResource): class Meta: queryset = Movie.objects.all() resource_name= "movies" excludes = ["date_created"] and my urls.py: from django.contrib import admin from django.urls import path, include from api.models import MovieResource movie_resource = MovieResource() urlpatterns = [ path('admin/', admin.site.urls), path("movies/",include("movies.urls")), path("api/",include(movie_resource.urls)) and the full error: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x10e6d9090> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import … -
django hidden page available only after loging in
I have made a simple login form in django. after a typing a correct details it redict to other page (result.html) but you can also get to the page after typing page address in browser. I don't know how to make available only after loging in. home.html {% extends "index.html" %} {% block content %} <div class="card border-secondary"> <div class="card-body"> <h4 class="card-title">Login form</h4> <form method="post"> {% csrf_token %} <label>Login</label> <input class="m-3" type="text" name="txtLogin" placeholder="login (admin)"> <br> <label>Password</label> <input class="m-3" type="text" name="txtPassword" placeholder="Password (admin)"> <hr> <button name="btnSend" type="submit" class="btn btn-secondary">Log in</button> </form> </div> </div> views.py def home(request): if request.method == 'POST' and 'btnSend' in request.POST : login = request.POST.get('txtLogin') password = request.POST.get("txtPassword") if login=="admin" and password=="admin": return HttpResponseRedirect('/main/result') else: return HttpResponseRedirect('/main/home') template = loader.get_template('home.html') context={} return HttpResponse(template.render(context,request)) def result(request): template = loader.get_template('result.html') context={ } return HttpResponse(template.render(context,request)) -
URLValidator throw the error when correct URL
I have URLValidator When I try to validate this url from django.core.validators import URLValidator from django.core.exceptions import ValidationError url = 'https://webapl-test.exxample.co.jp/company/senpai/index? type=data&code=0001&utm_source=line&utm_medium=topics&utm_campaign=20220720' URLValidator(schemes=['https','http']) url_val(path) Some how it returns exception... How can I fix it or can I customize the URLValidator for this kind of case?? -
Django rest spectacular - Customizing get_queryset()
I am trying to customize the redoc documents using DRF-Spectacular. For some reason, the extend_schema class is not updating the description, summary or tags on the document. How can I customize this? @extend_schema( summary="Get All Classes", description='This endpoint will return all the classes created by your account.', tags=["Class"] ) def get_queryset(self): return super().get_queryset().filter(taxonomy__is_public=True) | super().get_queryset().filter(taxonomy__client=Client.objects.get(user=self.request.user)) -
Django Models disappear from app deployed in Heroku
I am building a personal portfolio website with Django which I'm hoping to host on Heroku. I am aware of the platform's ephemeral storage problem so all of the images are served from an s3 bucket. After deploying the app though and running the python manage.py migrate from the dyno and check the postgresql database on the dashboard I can see rows and columns created but they're not populated. Therefore, there are no models stored in this database. I'm not .gitignore-ing the db.sqlite3. I'm also using a virtual environment. Ih short here's the output of the tree command from the root folder: ├── Procfile ├── db.sqlite3 ├── manage.py ├── media │ └── images │ ├── angular.png │ ├── bash.png │ ├── c.png │ ├── calibration.png │ ├── commerce_img.png │ ├── css3.png │ ├── django.png │ ├── git.png │ ├── html.png │ ├── image-processing-api.png │ ├── js-logo.png │ ├── mail.png │ ├── my_store.png │ ├── network.png │ ├── nodejs.png │ ├── programmer.svg │ ├── python.png │ ├── rest_with_node.png │ ├── sql.png │ ├── typescript.png │ └── wiki_image.png ├── portfolio │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── settings.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ └── wsgi.cpython-39.pyc … -
How to cancel an add django
I have a model and there are relevance values. how can I make it so that while one object (101) is false so that it cannot be added, and when the value is true, you can IN ADMIN PANEL class Rooms(models.Model): objects = None room_num = models.IntegerField(verbose_name='Комната') room_bool = models.BooleanField(default=True,verbose_name='Релевантность') category = models.CharField(max_length=150,verbose_name='Категория') price = models.CharField(max_length=105,verbose_name='Цена (сум)') def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Комнату' verbose_name_plural = 'Комнаты' class Registration(models.Model): objects = None rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE,verbose_name='Номер',help_text='Номер в который хотите заселить гостя!') first_name = models.CharField(max_length=150,verbose_name='Имя') last_name = models.CharField(max_length=150,verbose_name='Фамилия') admin = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name='Администратор') pasport_serial_num = models.CharField(max_length=100,verbose_name='Серия паспорта',help_text='*AB-0123456') birth_date = models.DateField(verbose_name='Дата рождения') img = models.FileField(verbose_name='Фото документа',help_text='Загружайте файл в формате .pdf') visit_date = models.DateTimeField( default=datetime.datetime(year=year, month=month, day=day, hour=datetime.datetime.now().hour, minute=datetime.datetime.now().minute, second=00,),verbose_name='Дата прибытия') leave_date = models.DateTimeField( default=datetime.datetime(year=year, month=month, day=day + 1, hour=12, minute=00, second=00),verbose_name='Дата отбытия') guest_count = models.IntegerField(default=1,verbose_name='Кол-во людей') room_bool = models.BooleanField(default=False,verbose_name='Релевантность',help_text='При бронирование отключите галочку') price = models.CharField(max_length=105,default='Появится после сохранения!',verbose_name='Цена (сум)') def __str__(self): return f'{self.rooms},{self.last_name},{self.first_name},{self.room_bool}' class Meta: verbose_name = 'Номер' verbose_name_plural = 'Регистрация' -
django orm .values() is not working in for loop
menu_group = MenuGroup.objects.filter(is_deleted=False,store_id=store_id,version=version).values('id','name','color') menu_group_serializer = MenuGroupMixSerializer(menu_group, many=True) for menu_group_data in menu_group_serializer.data: menu_item_group = MenuItemGroup.objects.filter(menu_group_id=menu_group_id, is_deleted=False).values('id','name','starting_price','menu_group') .values() in second for loop is not working the menu_group is foreign key -
Django filter in prefetch_related object
I have a class where I am using prefetch_related. I'd like to apply a filter so it only shows categories that contain products and if product status is equal to 1. Below is the code that I am using but it shows me the whole area multiple times and it renders all items from Needs model. Moreover, I am getting errors when clicking on the product link. It gives the following error: Cannot resolve keyword 'product' into the field. Choices are: category_area, category_area_id, category_need, category_need_id, id, products, slug, title Do you know why am I getting this error? models.py class Area(models.Model): title = models.CharField(max_length=75, blank=False) body = models.CharField(max_length=150, default='-', blank=False) publish = models.DateTimeField('publish', default=timezone.now) class Need(models.Model): title = models.CharField(max_length=75, blank=False, null=False, help_text='max 75 characters') body = models.CharField(max_length=150, default='-', blank=False) publish = models.DateTimeField(default=timezone.now) need_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='need_area') class ProductCategory(models.Model): title = models.CharField(max_length=400, blank=False, null=False, help_text='max 400 characters') body = models.TextField(default='-') publish = models.DateTimeField('publish', default=timezone.now) category_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='category_area', null=True) category_need = models.ForeignKey(Need, on_delete=models.CASCADE, related_name='category_need', null=True) class Product(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=400, blank=False) category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE, blank=True, related_name='products') def get_absolute_url(self): return reverse("product", kwargs={'slug': self.slug}) views.py class Search(LoginRequiredMixin, ListView): template_name = 'search/product_search.html' model = Product queryset … -
Adding functionality to a signup buttom on Django
I am using the following html example taken from https://www.w3schools.com/howto/howto_css_signup_form.asp <!-- Button to open the modal --> <button onclick="document.getElementById('id01').style.display='block'">Sign Up</button> <!-- The Modal (contains the Sign Up form) --> <div id="id01" class="modal"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">times;</span> <form class="modal-content" action="/action_page.php"> <div class="container"> <h1>Sign Up</h1> <p>Please fill in this form to create an account.</p> <hr> <label for="email"><b>Email</b></label> <input type="text" placeholder="Enter Email" name="email" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" required> <label for="psw-repeat"><b>Repeat Password</b></label> <input type="password" placeholder="Repeat Password" name="psw-repeat" required> <label> <input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me </label> <p>By creating an account you agree to our <a href="#" style="color:dodgerblue">Terms & Privacy</a>.</p> <div class="clearfix"> <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button> <button type="submit" class="signup">Sign Up</button> </div> </div> </form> </div> What it does is add a 'signup' button.. When input is eventually filled it sends back an error How do we add functionality to it using python? -
How to get the name of ContentType foreign key in database
I have field like this below from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class MessageLog(BaseModel): receiver_type = m.ForeignKey( ContentType, related_name="receiver_%(class)s_set", on_delete=m.CASCADE,null=True) receiver_id = m.PositiveBigIntegerField(null=True) receiver = GenericForeignKey('receiver_type', 'receiver_id') I can access member like this, and both returns the number. m = MessageLog.objects.get(id=1) print(m.receiver_id) // 2 print(m.receiver_type) // 12 However print(m.receiver) object has no attribute 'receivor' I want to get the name of receiver_type name. How can I do this? -
ReactJS & Django Cross-domain
I am trying to connect a ReactJS app (running on localhost:1234) to a Django API HTTPS site. Although I am successfully requesting CSRF with axios (withCredentials: true), still the token is not set. Here is the response: enter image description here This is my Django settings: CORS_ALLOWED_ORIGINS = [ 'http://localhost:1234' ] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS =[ 'http://localhost:1234' ] Any suggestions what I might be missing? Could it be something wrong with the browser (I am testing on Chrome)? -
Embedding documents from static folder in Django
I am not expert in Django, but I am doing a web site where I would like to embed a ppt, which is saved into the static folder. The code of the html is: {% extends 'base.html' %} {% load static %} {% block content %} <iframe src="{% static 'ppt/pptexample.pptx' %}" style="width:800px; height:600px;" frameborder="0"/> {% endblock %} When I load the site, the ppt is perfectly downloaded, but I would like to visualise it online. Then, I have tried to add embedded=true, that is to say {% static 'ppt/pptexample.pptx' %}&embedded=true, which did not work. Could you recommend me or letting me know how to embed such a PowerPoint document in the Web? Many thanks in advance -
Mayan edms with s3 amazaon
Can any one guide with s3 integration of mayan edms? https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html -
How to Customize Django Permission Model and Still Have Admin Panel Support
I want to add several fields to the original Django Permission model and add custom permision checking logics. The catch is that I'd like to have Django admin support as well. What's the best way to do it? P.S.: I don't care about the relationship between the Permission class and ContentType and I don't need it. P.S. 2: I'm using django to create a Centralized Authentication and Authorization Service. What I've tried: I added a Custom user model that inherits from AbstractBaseUser. I also Added PermissionModel and PermisionMixin (with all the methods defined by original Django) Except that I removed the ForeignKey to ContentType which I presume is the main reason that I don't see Groups and Permissions in the Admin panel. So, back to original question? What's the best way to add custom fields to Django Permission model and still have the Admin Panel Support for CRUD on Users, Groups, and Permissions? -
How to set permissions for CRUD operations in ModelViewSet Django
I have a viewset for model News. I want to do next permissions: All people can see news. Only authorized users and admin can create news. Only owner and admin can update news. Only admin can delete news. How can I set different permissions for each operation? For create I want to use: IsAuthenticated and IsAdminUser. For update I want to use IsAdminUser and I create my own permission for owner. For delete I want to use also IsAdminUser. view: class NewsViewSet(viewsets.ModelViewSet): queryset = News.objects.all() serializer_class = NewsSerializer permission: class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user -
How can i use django url inside of an option tag in a dropdown menu?
At the moment I have been able to use a for loop that lists all the relevant urls using this: <H2> Your Visuals are located here: </H2> <ul class="main-navigation"> {% for i,j in files%} <H3>{{j}}</H3> <ul> <li><a href="{% url 'visualisation:network_multi_graphs' %}?database={{i}}">Multiple Graphs</a></li> <li><a href="{% url 'visualisation:customer_locations' %}?database={{i}}">Customer Locations</a></li> <li><a href="{% url 'visualisation:product_quantity' %}?database={{i}}">Product Quantity</a></li> <li><a href="{% url 'visualisation:demand_time' %}?database={{i}}">Demand over Time Period</a></li> </ul> {% endfor %} </ul> I've tried to implement a drop down menu for ll the links using the code below with just 1 link as a test but nothing seems to render. <label>values in z<label> <select id="the-id"> {% for i, j in files %} <option value=" href="{% url 'visualisation:customer_locations' %}?database={{i}}">Customer Locations</option> {% endfor %} </select> Anyone know where i'm messing up? -
'int' object is not subscriptable django Overlapping check
When I am checking overlapping in Django forms with this code i could not check the overlapping, geting the error of tuples record=[] if count > 1: for i in range(count): start_run = self.data.get(f'runningdefinition_set-{i}-start_run',[]) end_run = self.data.get(f'runningdefinition_set-{i}-end_run',[]) application_run =self.data.getlist(f'runningdefinition_set-{i}-application_run') record.append((i, start_run, end_run, application_run)) tp=0 for x in record[0]: for y in record[-1]: if (x[0] < y[0] < x[1]) or (x[0] < y[1] < x[1]): tp += 1 else: raise ValidationError( "Overlapping not allowed" ) -
how to update using SIGNALS
from django.db.models.signals import post_save from django.dispatch import receiver from .models import Registration @receiver(post_save, sender=Registration) def create_profile(sender, instance, created, **kwargs): if created: instance.rooms.room_bool = False instance.rooms.save() this is the code in the signals that updates the value from another model according to the value of another WHEN I CREATE (if in model 1 it will be False, then in model 2 it will also be False) how can I make it so that when EDITING changes the values -
Django model with multiple foreign keys
I want to create a list of products that are categorized by area, need, and product category. I created 3 separate models that reply on each other so users will easily add categories and select from the dropdown list area and need. For now, I have 3 areas and under each area I have needs. What I want is to render a list of items from Area model, under each item from Area model all items from Need model and under each item from Need model all items from Product model (only titles). ProductCategory model is not used here but I need it somewhere else and it is a connector between products and areas/needs. It is much easier to define categories and just select them from the dropdown list when adding a new product. I need to create a loop that will show me something like above. I know it will not work but I wanted to show the logic. My question is what is the best approach to render something like this? How can I get the title from Area model and title from Need model in my views.py file and show product titles under these objects? What is … -
Getting Error in Django Application on Azure App Service
I am getting since yesterday on appliction from yesterday it's working fine early some upgradtion on cloud breaks the application This is the error Error : module 'typing' has no attribute '_ClassVar' My python env is 3.7 and Django version 2.1.3 -
Problem with Jquery in django project template
am facing a problem in this Django project where I am working to get a dynamic dependent drop-down.This part of the script is not sending any Ajax request. As a beginner, I am trying to do random projects.I didn't know more about Ajax and Javascript. Is there any problem in this code? enter image description here -
VSCode not autocompleting all Django modules
It looks like autocompleting is not working for all the functions for some Django modules? For example, I am importing from django.contrib.auth.models import User but when trying to create a new user: user = User.objects.create_user(etc) is not showing the create_user function. Any thoughts please? FYI: I am running VSCode on Ubuntu and django is installed in a venv. Interpreter is set to .../venv/bin/python3.10 -
How to properly use asyncio semaphore in djangos views? and where i can trace if it works?
I have to limit the number of calls to this run_annotation function to a maximum of 3 because the server does not support it, the below code works but i don't know how can i check if i am doing it in the right way LIMIT = 2 async def run_annotation(self, id): sem = asyncio.Semaphore(LIMIT) do_something()