Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add reference Parameters in extend_schema decorator in drf-spectacular
I'm using drf-spectacular to generate the swagger/redoc API documentation. I am facing issue in customising the schemas generated. I am trying to generate reference parameter using @extend_schema decorators in drf_spectacular but did'nt get the expected schema. extend_schema - ` from drf_spectacular.utils import extend_schema @extend_schema( parameters=headerParam, responses = {200:Response1,400:errorresponse}, tags = ['User'], )` headerParam - `headerParam = [ OpenApiParameter( name='Accept-Language', location=OpenApiParameter.HEADER, type=OpenApiTypes.STR, description='ISO 2 Letter Language Code', required=True, enum=['en', 'ar'], # default='en', ), OpenApiParameter( name='Accept', location=OpenApiParameter.HEADER, type=OpenApiTypes.STR, description='Type of response you are expecting from API. i.e. (application/json)', required=True, default='application/json', ), ]` The problem I am facing is the schema in drf_spectacular is generating this as below - `"parameters": [ { "in": "header", "name": "Accept", "schema": { "type": "string", "default": "application/json" }, "description": "Type of response you are expecting from API. i.e (application/json)", "required": true }, { "in": "header", "name": "Accept-Language", "schema": { "type": "string", "enum": [ "ar", "en" ] }, "description": "ISO 2 Letter Language Code", "required": true } ],` I want to generate like this - "parameters": [ { "$ref": "#/components/parameters/Accept" }, { "$ref": "#/components/parameters/Accept-Language" } ],` Thank you and Appreciate for the help in Advance :) I have done R&D but didn't find anything related to this. -
i am getting 405 error for get method in my django api, instead, i want a default message for get method
For django API, which we have written, post method is allowed but instead of get method, i am getting 405 error, but instead i want some default message like- "error". I am sharing my code. Please let me know if anyone can help. @api_view(['GET']) @permission_classes([AllowAny]) -
how change database's port dynamically(django)
i have a django project that it should have ability to change the database's port dynamically for security reasons. for example there should be a template like ( port= ) and the administrator should enter a port and change the default one. how to do this? -
500 error on django channels send message to group
I have the following Django channels consumer but when I try to send data to the stocks group، it returns a 500 error. Also, I don't get any error logs. Here is the consumer: class AuthRequiredConsumer(JsonWebsocketConsumer): def connect(self): user = self.scope['user'] print(isinstance(user, AnonymousUser)) if isinstance(user, AnonymousUser): raise DenyConnection("authentication required") self.accept() class ChatConsumer(AuthRequiredConsumer): groups = ['stocks'] channel_layer_alias = "stocks" def stocks_data(self, event): print(event) return self.send_json({'message': event['text']}) def receive_json(self, content, **kwargs): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "stocks", { "type": "stocks.data", "text": "Hello there!", }, ) message = content["message"] self.send_json({"message": message}) Also, I use this middle to authenticate users by the token: @database_sync_to_async def get_user(token_key): try: token = Token.objects.get(key=token_key) return token. user except Token.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) async def __call__(self, scope, receive, send): try: token_key = (dict((x.split('=') for x in scope['query_string'].decode().split("&")))).get('token', None) except ValueError: print("error") token_key = None scope['user'] = AnonymousUser() if token_key is None else await get_user(token_key) return await super().__call__(scope, receive, send) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) And here is the routing config: application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": TokenAuthMiddlewareStack( URLRouter( [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()) ] ) ) , } ) I debugged the receive_json method using breakpoints And I saw self.channel_name and self.channel_layer is None!! Does anyone … -
Does Django save model objects other than `save()` or `create()` methods?
I'm writing something like the following: class Foo(models.Model): a = models.CharField() def f(foo: Foo) -> Foo: y = Foo( **{field.name: getattr(foo, field.name) for field in foo._meta.get_fields()} ) # copy foo with pk y.a = "c" return y My concern is whether y are saved to DB before users call save() method. Could it occur? -
In Django's auth contrib module, how do I correctly return an error when overriding the asswordResetConfirmView view?
I'm using Django 3 and the auth contrib module. I want to override the reset password procedure via an API and so I have a method that looks like this .... class CompleteResetPasswordView(PasswordResetConfirmView): @method_decorator(csrf_exempt) def dispatch(self, request): body = json.loads(request.body) self.data = body # validate user, password, and confirm password if user is not None: ... return Response('Success', status=HTTP_200_OK) ... return Response('Error', status=HTTP_500_INTERNAL_SERVER_ERROR) When the user cannot be validated and the "return Response('Error', status=HTTP_500_INTERNAL_SERVER_ERROR)" is invoked, this error is returned AssertionError at /password-reset-complete .accepted_renderer not set on Response I would liek a JSON response (in addition to the 500 status code) to be returned to the view, but haven't figured out how to manipulate what I have to make this happen. -
Django static url setting is not working in production
I have uploaded stsatic files to Cloudflare R2 with python manage.py collectstatic command, and checked files are there. Also, allowed public access for the R2 bucket. I have these in my settings.py file for static related: STATIC_HOST = env("STATIC_HOST") STATIC_URL = STATIC_HOST + "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATICFILES_STORAGE = ( "django.contrib.staticfiles.storage.StaticFilesStorage" if DEBUG else "myproject.backends.storages.StaticStorage" ) ...and this is my .env file: DEBUG=True AWS_ACCESS_KEY_ID=my_r2_access_key_id AWS_SECRET_ACCESS_KEY=my_r2_secret_access_key AWS_STORAGE_BUCKET_NAME=my_r2_bucket_name # Endpoint for uploads AWS_S3_ENDPOINT_URL=https://my_account_id.r2.cloudflarestorage.com # Public access url STATIC_HOST=https://pub-a1b2c3d4e5f6.r2.dev When I runserver with DEBUG=False and go to localhost:8000/admin it does not load CSS properly, and static file requests are all 4xx and not using provided STATIC_URL but AWS_S3_ENDPOINT_URL. When I runserver with DEBUG=True it loads static files properly from provided STATIC_URL setting. I want to load static files from R2 bucket in production / DEBUG=False and use local static files with DEBUG=True. Please help me what I am doing wrong? -
Filtering multicheckbox on datable
i have a problem with my code, i try to make a datable with multiple checkbox filter on Django environement. i have tried multiple code, but for now, i have this code, for each collumn there is a list and i can check or not the checkbox, but the filter is not applicated. any suggestion would be very welcome. here the code : <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/fixedheader/3.2.3/css/fixedHeader.dataTables.min.css"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <style> .dropdown-menu { max-height: 200px; overflow-y: auto; } </style> </head> <body> <h1>Liste des matches</h1> <table id="table_id" class="display"> <thead> <tr> <th> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownPAYSEQP" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> PAYSEQP </button> <div class="dropdown-menu" aria-labelledby="dropdownPAYSEQP"> {% for match in matches %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{ match.PAYSEQP }}" id="{{ match.PAYSEQP }}"> <label class="form-check-label" for="{{payseqp}}"> {{ match.PAYSEQP }} </label> </div> {% endfor %} </div> </div> </th> <th> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownJOUEURS" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> JOUEURS </button> <div class="dropdown-menu" aria-labelledby="dropdownJOUEURS"> {% for match in matches %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{ match.JOUEURS }}" id="{{ match.JOUEURS }}"> <label class="form-check-label" for="{{joueur}}"> {{ match.JOUEURS }} </label> </div> {% endfor %} </div> </div> … -
Django's remove_stale_contenttypes command fails with DoesNotExist error
I recently tried to run remove_stale_contenttypes in a Django 3.1 app, after deleting some custom permissions. The first time it run it warned me that some entries would be deleted, and I went ahead and entered 'yes'. The command failed with a DoesNotExist error for one of the models, and after that I can't even see the warning, it fails right away, with the following output: Traceback (most recent call last): File "C:\Users\Yamil\Google Drive\Proyectos\monely\manage.py", line 22, in <module> main() File "C:\Users\Yamil\Google Drive\Proyectos\monely\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\contrib\contenttypes\management\commands\remove_stale_contenttypes.py", line 55, in handle collector.collect([ct]) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\deletion.py", line 295, in collect if sub_objs: File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\query.py", line 291, in __bool__ self._fetch_all() File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\query.py", line 1303, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\polymorphic\query.py", line 64, in _polymorphic_iterator real_results = self.queryset._get_real_instances(base_result_objects) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\polymorphic\query.py", line 387, in _get_real_instances if base_object.polymorphic_ctype_id == self_model_class_id: File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\query_utils.py", line 149, in __get__ instance.refresh_from_db(fields=[field_name]) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\base.py", line 635, in refresh_from_db db_instance = db_instance_qs.get() File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( productos.models.DoesNotExist: Producto matching query does not exist. … -
Django MPTT, can't get parent_id for threaded comments reply
My Problems are as follows: Im relatively new to Django. so sorry for this mess. I've tried to implement threaded comments to my blog via MPTT. But when i pressing the 'Reply' Button django throws me a Type Error Normal parent comments working correctly When i just create a comment with via the admin site, i can create parent comments and child comments and they will be indented just as expected in the main Application too... my Database is mySQL. The Error: in _calculate_inter_tree_move_values space_target = target_right - 1 ~~~~~~~~~~~~~^~~ TypeError: unsupported operand type(s) for -: 'NoneType' and 'int' my models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from mptt.models import MPTTModel, TreeForeignKey STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail',args=[self.slug]) class Comment(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) parent=TreeForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') class MPTTMeta: order_insertion_by = … -
Django Filter using Q Objects on two Models
I am working a Django Application where I want to search two Models Profile and Account using Q objects. From what I did, it is searching only one Model (Account) and any attempt to search any value from the other Model (Profile) triggers an error. See my Model Code: class Profile(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', ) def __str__(self): return f'{self.customer.username}-Profile' class Account(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True) account_number = models.CharField(max_length=10, null=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f' {self.customer} - Account No: {self.account_number}' Here is my form: class SearchCustomerForm(forms.Form): value = forms.CharField(label = 'Enter Name or Acct. Number', max_length=30) Here is my views def create_account(request): if searchForm.is_valid(): #Value of search form value = searchForm.cleaned_data['value'] #Filter Customer by Surname, Othernames , Account Number using Q Objects user_filter = Q(customer__profile__exact = value) | Q(account_number__exact = value) #Apply the Customer Object Filter list_customers = Account.objects.filter(user_filter) else: list_customers = Account.objects.order_by('-date')[:8] Someone should help on how best to search using Q objects on two Models. -
How to fix search function in Django?
I have a page with the list of objects. I need a search function, but there is an error. I am in process of studying and I used from . import views and the search function worked, but then I replaced it to from .views import HomeView and modified some code. The list is shown, but as for search there is an error: type object 'HomeView' has no attribute 'Search' Urls.py: from django.urls import path #from . import views from .views import HomeView urlpatterns = [ #path('', views.home, name="home"), path('search/', HomeView.Search.as_view(), name='search'), path('', HomeView.as_view(), name="home"), ] Home.html: <div> <h3>Find</h3> <form action="{% url 'search' %}" method="get"> <input type="search" name="q" class="form-control" required=""> <button type="submit">Find!</button> </form> </div> <h3>Applications</h3> {% for application in object_list %} <div> <p>{{ application.name }}</p> </div> {% endfor %} </div> Views.py: from django.shortcuts import render from django.views.generic import ListView from .models import Application from .forms import ApplicationForm from django.urls import reverse_lazy class HomeView(ListView): model = Application template_name = 'home.html' #ordering = ['status'] class Search(ListView): def get_queryset(self): return Application.objects.filter(title__icontains=self.request.GET.get("q")) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["q"] = self.request.GET.get("q") return context </div> -
CKEDITOR PillowBackend Django disable thumbnail creation
By default, when inserting an image from the clipboard into the CKEDITOR editor, the images are saved in PNG format and take up a lot of disk space. I have enabled PillowBackend to be able to save images in JPG format, but its thumbnail is created along with the image, how can I disable thumbnail creation? Or maybe there is a way when inserting an image from the clipboard into the CKEDITOR editor, you can save the image in JPG format without enabling PillowBackend, so that there is no thumbnail creation? -
Creating a team of users with jobs
I want to make a model where users can create a team of users, and in these teams add the job that they did and choose recipient of the job(that is the member of this team) that they did it for. I don't how to create a choice field for the recipient of the job. from django.db import models from django.contrib.auth.models import User class Team(models.Model): name = models.CharField(max_length=120) members = models.ManyToManyField(User) class Job(models.Model): belonging = models.ForeignKey(Team,on_delete=models.CASCADE) executor = models.ForeignKey(User,on_delete=models.CASCADE) task_description = models.CharField(max_length=180) recipient = models.ManyToManyField(Team.members) # <-- -
django - only call <a href="{% url 'view'%}"> when clicked
In my web page i have a for loop that displays multiple <a> tags. When one of the <a> tags is clicked the user will be redirected to another url. My problem is that all of the href="{% url 'search' theme_path %}{{theme}}" gets called despite not being clicked and causes my page site to crash since the sub_themes list is quite large. I tried using forms as they should only call the {% url 'view' %} when clicked. But this got a bit fiddly. There must be some simple javascript code that can resolve my issue How can i only have the url be called when clicked? html <section id="all-themes-container"> {% for theme in sub_themes %} <div class="theme-container"> <a href="{% url 'search' theme_path %}{{theme}}">{{theme}}</a> </div> {% endfor %} </section> -
Django form request is always response with "GET" instead of "POST" even when I use <form action="" method="post">
Please help me m looking since hours for the solution but i didnt find something. Here is my HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <style> input { width: 10%; margin: 0 auto; display: block; margin-left: auto; margin-right: auto; } </style> </head> <body> {% load crispy_forms_tags %} <div class="container"> <form action="" method="post"> {% csrf_token %} {% crispy form %} <input type="submit" class="btn btn-primary mx-auto d-block"> </form> </div> </body> </html> and here is my views.py: from django.shortcuts import render from .forms import UserInformationForm # Create your views here. def register(request): form = UserInformationForm() context = {"form": form} print(form) if request.method == "POST": print("Post") form = UserInformationForm(request.POST) if form.is_valid(): form.save() print(form) return render(request, 'index.html', context) The only response i get is: "GET /register/ HTTP/1.1" 200 3542 I already tried things like if request.method == "GET": But then I had on every field in my form a mark with "This fiel is required" -
I am using Django to create and update an Text area I want to save my updated textarea after clicking Insert
I am using Django to create and update an Text area. After putting a text that have variables between {}, I want to change them using button variable. So when I click on variable it will show me all the varaibles between {}, Si I can assign them a value. After I am done, I save my updated Text area after clicking Insert. The problem is when I click Insert, and I open my database, it shows me NULL for my text. I tried to print the variable text in the view, but I have None. Here is my model: class InputText(AbstractModule): text = models.TextField(default='', null=True, blank=True) def __str__(self): return self.text Here is my view: def save_variables_text(request): if request.method == 'POST': print(request.method) text = request.POST.get('input-text') print(text) InputText.objects.create(text=text, user=request.user) return render(request, 'modules/gabarits/previsualise.html') Here is my previsualise.html file: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-dialog modal-md"> </form> <div class="modal-content" hx-target="this" hx-swap="outerHTML" id="this"> {% load crispy_forms_tags %} <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Show gabarit</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <!-- Modal body --> <div class="modal-body"> <pre style="font-size: 12px"><textarea id='input-text' name='input-text' style='height:100px; width: 800px;'>{{commande}}</textarea></pre> {% if formset %} <button class="mb-2 btn btn-outline-secondary mr-2" id="variables-button" type="button" onclick="openModal()">Variables</button> {% endif %} <div id="modal" … -
docker nginx django gunicorn 502 bad gateway
i am a beginner in the docker I want deploy my django project on hostinger.com vps so I am using docker nginx and gunicorn for this I dockrized my django project a test it on the localhost every thing is good and my project is working by when i deploy it on the vps it show me 502 Bad gateway i don't have any idea ? docker-compoe.yml version: "3.7" services: app: build: './app' container_name: 'app' restart: 'always' expose: - '8000' # ports: # - "8000:8000" environment: - "MARIADB_DATABASE=django_app" - "MARIADB_USER=peshgaman" - "MARIADB_PASSWORD=m_nasir5555" - "MARIADB_HOST=mariadb" volumes: - type: 'bind' source: './volumes/app' target: '/app' depends_on: - "mariadb" - "nginx" mariadb: image: 'mariadb:latest' container_name: 'mariadb' restart: 'always' expose: - '3306' # ports: # - "8000:8000" environment: - "MARIADB_DATABASE=django_app" - "MARIADB_USER=peshgaman" - "MARIADB_PASSWORD=m_nasir5555" - "MARIADB_ROOT_PASSWORD=m_nasir5555" volumes: - type: 'bind' source: './volumes/dbdata' target: '/var/lib/mysql' nginx: build: './nginx' container_name: 'nginx' restart: 'always' ports: - "80:80" volumes: - type: 'bind' source: './volumes/media' target: '/app/media' - type: 'bind' source: './volumes/static' target: '/app/static' app Dockerfile FROM python:alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DJANGO_SUPERUSER_PASSWORD=admin RUN mkdir /app COPY requirements.txt /app WORKDIR /app RUN apk update RUN apk add --no-cache gcc python3-dev musl-dev mariadb-dev RUN pip install --upgrade pip … -
Django ORM: How to round down (truncate) a query number?
I'm working with sensitive currency values. In my case, i have to reproduce a sheet with it's formulas. The point is that i need to round down a currency value with 2 decimal places. A practical example is the number: 9809.4069, it should be rounded to 9809.40, with a truncation. Otherwise, normal rounding function returns me 9809.41. Obs. For performance reasons i need to bring all my values in one query. Usual ways, with normal functions as round(), doesen't work inside non-query functions. Well, my Query i'ts working completly FINE and brings everything that i want, the problem are the fields with Round() function, that returns me the "wrong" value. The Query: activetime_qs = activetime_qs.values( 'user', 'user__team__name','user__foreign_id','user__location','user__team__cost_center' ).annotate( full_name=Concat(('user__first_name'),Value(' '),('user__last_name')), project_id=Subquery(UserProject.objects.filter(user_id=OuterRef('user')).values('project')[:1]), item_id=Subquery(Project.objects.filter(id=OuterRef('project_id')).values('item')[:1],), project_name=Subquery(Project.objects.filter(id=OuterRef('project_id')).values('name')[:1]), project_code=Subquery(Project.objects.filter(id=OuterRef('project_id')).values('code')[:1]), item_name=Subquery(Item.objects.filter(id=OuterRef('item_id')).values('name')[:1]), item_value=Subquery(Item.objects.filter(id=OuterRef('item_id')).values('unitary_value')[:1]), available_time=Sum('duration'), completed_tasks_amount=Case( When(user__activity_type=ActivityType.DELIVERABLE, then=Subquery(TaskExecution.objects.filter(members=OuterRef('user'), completed=True, start__date__gte=initial_date, start__date__lte=final_date) .values('pk').annotate(count=Func(F('pk'), function='Count')) .values('count'), output_field=IntegerField() ) ), default=1, ), availability_percentage=Case( When(user__activity_type=ActivityType.SERVICE_STATION, then=Round(F('available_time') / expected_time, 3)), default=0, output_field=FloatField() ), subtotal_value=Case( When(user__activity_type=ActivityType.SERVICE_STATION, then=Round(F('item_value') * F('availability_percentage'),2) ), default=Round(F('item_value') * F('completed_tasks_amount'),3), output_field=FloatField() ), availability_discount=Case( When(user__activity_type=ActivityType.SERVICE_STATION, then=Round(-1 + F('availability_percentage'),3), ), default=0, output_field=FloatField() ), discount_value=Case( When(user__activity_type=ActivityType.SERVICE_STATION, then=Round(F('item_value') - F('subtotal_value'),2), ), default=0, output_field=FloatField() ), ) return activetime_qs Then, i've tried two aprocches to round the annotate values down. Use a DecimalField as output_field with the … -
How to create a new csv from a csv that separated cell
I created a function for convert the csv. The main topic is: get a csv file like: ,features,corr_dropped,var_dropped,uv_dropped 0,AghEnt,False,False,False and I want to conver it to an another csv file: features corr_dropped var_dropped uv_dropped 0 AghEnt False False False I created a function for that but it is not working. The output is same as the input file. function def convert_file(): input_file = "../input.csv" output_file = os.path.splitext(input_file)[0] + "_converted.csv" df = pd.read_table(input_file, delimiter=',') df.to_csv(output_file, index=False, header=True, sep=',') -
How to prevent the page scrolling back to the top after clicking on a button?
I have a small form on django, when the button is clicked it display a django message bellow the form to tell the user that he successfully clicked on the button but it redirect the user in the top of the page. I want the page to stay where it is or redirect where the form is so he can see the message. <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-dark">Soumettre</button> </form> views.py def home(request): if request.method == 'POST': form = LeadForm(request.POST) if form.is_valid(): nom = form.cleaned_data['nom'] messages.success(request, "Merci pour votre message. Nous allons vous contactez le plus vite possible.") else: form = LeadForm() return render(request, 'main/index.html', {'form': form}) I tried to add a href="#!" or href="javascript:void(0);" to the button but it is not working either. -
Django - special query or another field holding Boolean data to get view from multiple models
I have few models, but right now I want to focus on two: class Client(models.Model): first_name last_name car # Client's car to be serviced class Service(models.Model): service_name service_type service_date client = models.OneToOneField(Client, on_delete=models.CASCADE, verbose_name="Client served") def __str__(): return f"Client {self.client} was serviced at {self.service.date}" I want to show all clients data in form of a table... first_name Last_name Car (make/model) Serviced? Service date John Watson Toyota Auris Yes 2023-02-01 Bob Kilicki Toyota Corolla Yes 2023-02-01 Mark Smith Honda Civic No -------- David Bobson VW Polo Yes 2023-02-03 Andrew Hutchinson Renault Clio No -------- (...) But I need additionaly information if Client was served (car was serviced), if so - when (the date)? How can I do that from views.py? Should I make another field in Client model - for example boolean field holding information - client served: True or False? Or better way is to construct - some more advanced - query which will retrieve data from both models, but how? If it is common problem in Django, please point me to the right direction (in Django Docs). Don't know exactly what terms should I use... Of course any example, is welcome, too. -
The ability to like/vote posts from the post list
I have a problem. I made likes to the posts on the video from YouTube. It is possible to like a post only from post_detail view and it's works correctly! How to make it possible to like posts in the post_list (in my case it's 'feed')? Please help! MY CODE: utils.py def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' views.py from .utils import is_ajax def feed(request): comments = Comment.objects.all() posts = Post.objects.all().order_by('-created_at') return render(request, 'main/feed.html', {'posts': posts, 'comments': comments}) def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) comments = Comment.objects.filter(post=post, reply=None).order_by('-created_at') is_voted = False if post.votes.filter(id=request.user.id).exists(): is_voted = True if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = request.POST.get('content') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post = post, author = request.user, content = content, reply = comment_qs ) comment.save() return redirect(post.get_absolute_url()) else: for error in list(comment_form.errors.items()): messages.error(request, error) else: comment_form = CommentForm() return render(request, 'main/post_detail.html', {'post':post, 'comment_form':comment_form, 'comments':comments, 'is_voted':is_voted}) @login_required def post_vote(request, slug): post = get_object_or_404(Post, id=request.POST.get('id'), slug=slug) is_voted = False if post.votes.filter(id=request.user.id).exists(): post.votes.remove(request.user) is_voted = False else: post.votes.add(request.user) is_voted = True context = { 'post': post, 'is_voted': is_voted, } if is_ajax(request): html = render_to_string('main/votes.html', context, request) return JsonResponse({'form':html}) votes.html <form … -
Page not found (404) No Booking matches the given query - Django web application
I am having trouble figuring out where my issue is. I am parsing a slug to the url, via my view pulling from the SlugField in my model. For an object instance that exists in my database, the slug is being parsed successfully into the url. However, I am receiving the above error and cannot work out why. The corresponding model is Booking, and the slug field is as follows: booking_reference = models.SlugField(verbose_name="Slug Field", blank=False, unique=True) (I wanted to use the booking_reference as the slug field). My views.py is as follows: class EditBookingView(UpdateView, NextUrlMixin): model = Booking form_class = BookingForm template_name = 'bookings/edit_booking.html' success_url = '/' default_next = '/' def form_valid(self, form): form.instance.user = self.request.user form.save() next_path = self.get_next_url() return redirect(next_path) def get_context_data(self, **kwargs): context = super(EditBookingView, self).get_context_data(**kwargs) context['slug'] = self.kwargs['booking_reference'] return context def get_object(self): slug = self.kwargs.get('booking_reference') return get_object_or_404(Booking, booking_reference=slug) And my urls.py are: from django.urls import path from .views import ( CreateBookingView, ViewBookingsView, EditBookingView, DeleteBookingView ) app_name = 'bookings' urlpatterns = [ path('createbooking/<str:slug>/', CreateBookingView.as_view(), name='create_booking'), path('viewbookings/<str:slug>/', ViewBookingsView.as_view(), name='view_booking'), path('editbooking/<str:slug>/', EditBookingView.as_view(), name='edit_booking'), path('cancelbooking/<str:slug>/', DeleteBookingView.as_view(), name='delete_booking'), ] Please note, I have a list view for which the booking reference is being displayed under each model instance successfully. It is from … -
Mutation in django graphene for model with foreign key and many to many relationship
I have 2 models in my django app, the first is Tags model and the second is Post model, the problem is when i try to use mutation for the Post model to add a post from the graphql it doesn't work but it works fine in the Tags model, also the Queries works fine when i try to get data from the database. Here's my Code: model.py: from django.db import models from django.utils.translation import gettext as _ from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Tag(models.Model): name = models.CharField(_("Tag Name"), max_length=50, unique=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(_("Title"), max_length=50, unique=True) slug = models.SlugField(_("Post Slug"), unique=True) body = models.TextField(_("Post Content")) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) published = models.BooleanField(_("Published"), default=False) author = models.ForeignKey(User, verbose_name=_("Author"), on_delete=models.CASCADE) tags = models.ManyToManyField("Tag", verbose_name=_("Tags"), blank=True) class Meta: ordering = ['-createdAt'] def __str__(self): return self.title schema.py: import graphene from graphene_django import DjangoObjectType from django.contrib.auth import get_user_model from .models import Post, Tag User = get_user_model() class PostType(DjangoObjectType): class Meta: model = Post class TagType(DjangoObjectType): class Meta: model = Tag fields = ('id', 'name',) class TagInput(graphene.InputObjectType): name = graphene.String(required=True) class CreatePostMutation(graphene.Mutation): class Arguments: title = graphene.String() …