Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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() -
Django's UserCreationForm's Errors isn't working?
few months ago i made a website where it worked but similar code this time isn't working! it returns : **ValueError at /registration/ The User could not be created because the data didn't validate.** this is my form.py in bottom: class CreateUserForm(UserCreationForm): class Meta: model = User fields = ["username", "email", "password1", "password2"] my views: from .form import CreateUserForm def registrationPage(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid: form.save() return redirect("login") else: form = CreateUserForm() context = {"form": form} return render(request, "store/registration.html", context) in HTML previously i used : {{form.errors}} & it used to show me work on the page but not anymore -
AttributeError: 'Request' object has no attribute 'query_param'
Views.py - @api_view(['GET']) def view_items(request): if request.query_params: items = Item.objects.filter(**request.query_param.dict()) #error line else: items=Item.objects.all() serializer=ItemSerializer(items,many=True) if items: return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) -
Django, using GraphQL, Problem with 3rd party auth
So I'm working on a Django app where I'm using GraphQL instead of REST. And I have got auth to work using Django-GrapQL-auth, but it is using the local database (SQLite). What I want to do is have a 3rd party services like Firebase, AWS cognito, auth0 or similar to store passwords, since I don't want to store that locally. SO in the end I want to be able to do authentication by a 3rd party. How do I do this in Django? Any library that can help me? Or recommendation? Thanks. -
File Sharing in Django Application between admin and other user
I have a user_type named a staff_user and Admin here the admin in supposed to share the file with staff_user.On the file_list page of admin we are supposed to have an option called share_with_staff_user when clicked it will display the list of staff_users when selected and shared the file should be displayed on the page of staff_user file page. how can i acheive this. models.py class StaffUserDocument(BaseModel): staffuser = models.ForeignKey(StaffUser, related_name='documents', on_delete=models.CASCADE) uploaded_by = models.ForeignKey('User', related_name='+', null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255) file = models.FileField(upload_to='protected/') class AdminDocument(BaseModel): uploaded_by = models.ForeignKey('User',related_name='+',null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) file = models.FileField() views.py class AdminDocumentListView(LoginRequiredMixin, CustomPermissionMixin, TemplateView): template_name = 'admin_document_list.html' permission_classes = [IsStaff] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['urlParams'] = self.request.GET context['instanceData'] = {} return context @login_required def staff_user_profile_documents(request): staffuser = request.user.person.staffuser data = {'neutral': staffuser, 'documents': staffuser.documents.all()} return render(request, template, data) -
Celery Limit the Number of Tasks Running per User
I have a task in Celery that looks like this: @app.task(name='task_one') def task_one(user_id, *args, **kwargs): # Long running task This task is created in views every time a user submits a form, the task requires a lot of resources and takes around 10 minutes on average to complete. (views.py) ... if request.method == 'POST': task_one.delay(user.id) ... I want to limit the number of task_one tasks created per user to one (either active or reserved) What I'm doing so far, is checking if there is a task active or reserved for that user before creating the task: def user_created_task(active_tasks, reserved_tasks, user_id): for task in list(active_tasks.values())[0] + list(reserved_tasks.values())[0]: if task['name'] == 'task_one' and task['args'][0] == user_id: # Check if there is a `task_one` task created for the user return True return False def user_tasks_already_running_or_reserved(user_id): inspect = app.control.inspect() active_tasks = inspect.active() reserved_tasks = inspect.reserved() if active_tasks is None and reserved_tasks is None: # Celery workers are disconnected return False return user_created_task(active_tasks, reserved_tasks, user_id) (views.py) ... if request.method == 'POST': if not user_tasks_already_running_or_reserved(user.id): task_one.delay(user.id) ... I was wondering if there is a more efficient way of doing this, instead of inspecting all the workers on every user request, maybe there's a way of adding …