Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to trigger a function on user creation with django?
I'm new to django and I would like to know if it is possible to trigger a function after a user has been created? For user creation I use the django administration interface. I want to assign a default theme to a user and to do this I have the following class in my models.py file class Profile(models.Model): user = models.OneToOneField(User, null=False, on_delete=models.CASCADE) selected_theme = models.TextField(max_length=50, default="Clair") This class allows me to store the theme selected by the user I would like to use a function that assigns a theme to a user when creating it. -
Why can't I increment models.IntegerField?
I want to have a counter field in my user profile model to see how many requests each user has made. However I cannot figure out how to increment the count. I am trying to increment an integer field which is a associated with a model which looks like this: class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) request_count = models.IntegerField(default=0) Then in my views I want to increment the request_count every time the user makes a request like so: user = User.objects.get(email=pk) user_profile = Profile.objects.get(user=user) user_profile.request_count += 1 user_profile.save() For some reason every time I run this it sets the request_count to 1. I assume this is because it is defaulting to 0 (the default I set) and then adding 1 to that. But why doesn't the value increment? Help greatly appreciated. -
Is it possible to use "unique together" in Laravel, similarly to Django?
So in Django you can do this: unique_together = ('name', 'username',) so if you try to register people like this: name: John, username: blabla <---- this gets registered name: John, username: haha <---- this gets registered name: John, username: blabla <---- this won't get registered because the combination of John and blabla already exists. Is the something similar is Laravel I could use? The main goal is to check if the name with the username exists together, if it does, throw back a validation error, otherwise register the record to the database. edit #1: if I can get something like "unique together" in laravel, is it possible to modify the validation method based on a hidden field in the form? For example I want the user to write their name and email and submit it, and have a checkbox. The checkbox would enable/disable the 'unique' check of the name, so like if I do this: name: John Doe Corp. email: whatever, checkbox: Ticked then it would check the 'name' column for duplicates. Otherwise: name: Jane Doe. email: whatever, checkbox: Not Ticked then it would not check the name column for duplicates, allowing the record to be saved into the database. -
Django: Get Values from a ListSerializer
I have Serializer like this one: print(SubFoodSerializer(instance.sub_foods,many=True).food_images) Inside each sub_food we have some food_images. I want to get access to all food_images of the sub foods The error I get is: 'ListSerializer' object has no attribute 'title' print(SubFoodSerializer(instance.sub_foods,many=True).food_images) -
Scandics in django admin log
I'm using python 3.7/django 3.2/Mezzanine6.0 and due to use of Mezzanine the entries of django admin log become seen by users in the page history: All page history is ugly (compared what it used to be with python2.7/django 1.8/Mezzanine4.0 as there wasn't seen any unnecessary brackets, but there seem to be no answer in the whole net for that problem ), but it would be nice to have at least the scandics correctly written in the page history, i.e. "Däte of birth instead" of "D\u00e4te of birth". clip from models.py class Author(Page): dob = models.DateField("Däte of birth", null=True) Can anybody help with the scandics ? All program code is available in https://github.com/miettinj/mezzanine/tree/main/mezzanine_app/page_types. -
Django serializer returns enmpty list
I have a class-based view that returns all the data in the table. But while accessing the URL all I get is an empty list. models.py from django.db import models class EmployeeModel(models.Model): EmpID = models.IntegerField(primary_key=True) EmpName = models.CharField(max_length=100) Email = models.CharField(max_length=100) Salary = models.FloatField() class Meta: verbose_name = 'employeetable' views.py from .models import EmployeeModel from .serializers import EmployeeSerialize from rest_framework.views import APIView from rest_framework.response import Response class EmployeeTable(APIView): def get(self,request): emp_obj = EmployeeModel.objects.all() empserializer = EmployeeSerialize(emp_obj,many=True) return Response(empserializer.data) serializers.py from rest_framework import serializers from .models import EmployeeModel class EmployeeSerialize(serializers.ModelSerializer): class Meta: model = EmployeeModel fields = '__all__' The table has 5 rows. It is not empty. I want to serialize all 5 rows -
Django login fails after mail activation
Here's how a signup works: class SignUpView(FormView): template_name = 'center-form.html' form_class = SignUpForm def form_valid(self, form): if form.is_valid(): user = User.objects.create_user( first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password1'], is_active=False, ) activation_code = uuid.uuid4().hex Activation.objects.create(code=activation_code, user=user) activation_url = self.request.build_absolute_uri( reverse('activate', kwargs={'code': activation_code}) ) send_mail( 'Activate account', f'To activate your account, please follow the link below\n{activation_url}', 'Django', [form.cleaned_data['email']], fail_silently=False, ) messages.success( self.request, 'Please check your email for a message with the activation code.', ) return redirect('index') I eventually get a mail which contains some activation code. By clicking the link, I get a message indicating success as a result of: class ActivationView(View): @staticmethod def get(request, code): activation = get_object_or_404(Activation, code=code) activation.user.is_active = True login(request, activation.user) activation.user.save() activation.delete() messages.success(request, 'You have successfully activated your account') return redirect('index') However, when I try to sign in using the email and password used earlier, I get an error in the form: Please enter a correct username and password. Note that both fields may be case-sensitive. The form is AuthenticationForm and here's the view: class SignInView(LoginView): template_name = 'center-form.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data.update({'form_title': 'Sign in'}) return data -
where does user agent stylesheet come from?
basically, i have a html element i want to hide until i make a post request. to hide the element i used display:none; , but this is somehow being overiden by the user agent stylesheet. ive searched by whole html for the word "block" but it doesnt show up anywhere. i also have no external css everything is inline. Im hosting this page with djangos devserver... where is "display: block;" coming from? how do i stop it? below is a minimal reproducable example if what im doing. im trying to make my div element start hidden until a post request is made. <form action="http://localhost:8080" method="post" id = "mi_form"> <input type="submit" name="get prices" value="get prices" /> </form> <div id = "loader" style = "style= display:none; background:#000000; width:200px; height:200px; "> </div> <script type="text/javascript"> $("#mi_form").submit(function (e) { e.preventDefault(); // stops the default action $("#loader").show(); // shows the loading screen $.ajax({ url: test.php, type: "POST" success: function (returnhtml) { $("#loader").hide(); // hides loading sccreen in success call back } }); }); </script> -
Demo version of an existing project
We are currently faced with the task of making a demo of our project for clients with test data. We have the frontend in React and the backend in Django Rest Framework. One of the ideas that came to my mind is to use fixtures and return them in view, but there are a couple of problems such as: filtering, sorting, searching won't work... Another idea is to use a second database and multitenancy architecture to switch between databases in middleware for demo and regular users, but how to keep data up to date in next migrations? -
Generating invoice in django with Shiprocket API
I'm trying to generate invoice of my order in django with shiprocket API. So far I'm getting success Response but the generated URL of PDF is somewhat not understandable. #Response Im getting "{\"is_invoice_created\":true, \"invoice_url\":\"https:\/\/s3-ap-south-1.amazonaws.com\/kr-shipmultichannel-mum\/3116291\/invoices\/Retail000058ba9b309-c4bd-4c06-ba15-2cc76b7c5d1f.pdf\", \"not_created\":[],\"irn_no\":\"\"}" when I try to access above URL get - Access-Denied This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>94ARWRYHGSBEZEH1</RequestId> <HostId>j32LvksmWatylm3TdFGYuJ1qvBwJ39Lj+qIbbQ3CC7AEcrgHnOYGd9fDocMeEwDD4GpzjXQLQhg=</HostId> </Error> This is the way I want the url to be https://s3-ap-south-1.amazonaws.com/kr-shipmultichannel-mum/3116291/invoices/Retail000058ba9b309-c4bd-4c06-ba15-2cc76b7c5d1f.pdf When I remove the slashed I get in Response I'm able to download the PDF and that's done manually. So how do I get working URL. #Views.py class GenerateInvoice(APIView): def post(self, request): order_id = request.query_params.get("ids", None) print(order_id) data = json.dumps({"ids": [order_id]}) headers = { "Content-Type": "application/json", "Authorization": settings.SHIPROCKET_TOKEN, } url = "https://apiv2.shiprocket.in/v1/external/orders/print/invoice" response = requests.post(url=url, data=data, headers=headers) return Response(response) -
TypeError: contactApi() got an unexpected keyword argument 'id' [closed]
views.pyurls.py I need a output for "GET by details by id and enter the details by 'PUT' method -
How to pass kwargs from different view classes without redundancy?
As of now I have 5+ views that are implementing get_context_data to pass a title to the respective template. ex: class SignUpView(FormView): def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data.update({'form_title': 'Sign up'}) return data class SignInView(LoginView): template_name = 'center-form.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data.update({'form_title': 'Sign in'}) return data Each is passing form_title to template which in turn sets the main template title accordingly. <head> <meta charset="utf-8"> <title>{{ form_title }}</title> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> </head> Is there a better way to achieve the same thing without this redundancy? -
Django DeletionMixin and BaseDetailView causes a strange error with Mypy 0.991
So I have a very simple Django view that basically deletes a user account: class UserDeleteView(LoginRequiredMixin, SuccessMessageMixin, DeleteView): success_message = _("Your account has been deleted") success_url = reverse_lazy('account_logout') def get_object(self): return self.request.user After upgrading to Mypy 0.991 I am seeing this error: error: Definition of "object" in base class "DeletionMixin" is incompatible with definition in base class "BaseDetailView" [misc] For the life of me I can't figure out what this means, any help would be much appreciated. Thank you -
Add values from a dictionary to a ManytoMany field
class GuestOrder(models.Model): comment = models.CharField(max_length=400, blank=True, null=True) guest = models.ForeignKey(Guest, on_delete=models.SET_NULL, null=True) dish = models.ManyToManyField(Dish) ingredient = models.ManyToManyField(Ingredient) table = models.ForeignKey(Table, on_delete=models.CASCADE, blank=True, null=True) I have a queryset that returns 3 instances of GuestOrder. guest_orders = GuestOrder.objects.filter(table=table) <QuerySet [<GuestOrder: GuestOrder object (567)>, <GuestOrder: GuestOrder object (568)>, <GuestOrder: GuestOrder object (569)>]> and I have a dictionary where values are dish instances. { "guests":{ "23": [1, 2], "24": [2], "25": [3] } } How to set each of this values to a guestorder instance? -
Unsupported lookup 'unaccent' for CKEditor5 Field or join on the field not permitted
I am using CKEditor5 for my body field and trying to filter using unaccent like so Post.objects.filter(body__unaccent__icontains="text") but I get the error Unsupported lookup 'unaccent' for CKEditor5 Field or join on the field not permitted FYI, I did all the necessary configuration to be sure unaccent works perfectly. How do I know? I successfully executed Post.objects.filter(title__unaccent__icontains="text") where title is defined with CharField. My suggestion is that, unaccent didn't work for the first case because of CKEditor5. Is there a way to get this to work with this package? -
how to handle low capacity, multiple request update in django
In booking system, I have slot with capacity. now lets consider there is only 1 capacity is available and more two users are trying book the slot, at the same time. how I can handle this scenario? looking for any solutions from community. -
why django authenticate() always returns None to MySQL database? [closed]
i have MySQL database that is connected to my Django project, and i want to authenticate user using authenticate(), but the result of it always returning None. this is code of my django project: these forms uses 'User' model and its connected to MySQL 'loginView' handels login request and authenticate user and for password hashing problem, in MySQL database it's showed as plaintext password: password column in user_auth table even if i only authenticate username it still gives me None. -
form tags automatically closing
I am trying to validator with jsquery validator plugin. but it doesn't working. Now I found in chorme dev tools, tag is closed automatically! It seems to be related to the for loop in Django. Why does the form tags closed automatically? what's wrong with my script? In my .html codes, <div class="container-box"> <div> <table class="table table-striped tc"> <div style="float: right; padding: 1%"> <p style="width: 40%; float: left; font-weight: bold">Register for My rate :</p> <input type="text" style="border-radius: 5px; width: 30%; float: left" class="inputgroup form-control form-control-sm tc" placeholder="group" /> <button class="btn btn-outline-primary btn-sm sendgroup" style="float: right; width: 30%">Register</button> </div> <thead class="table"> <tr> <td>Origin</td> <td>Dest</td> <td>Name</td> <td>Cur</td> <td>Rate</td> <td>Unit</td> <td>ChargeAt</td> <td>Group</td> <td>U/D</td> </tr> </thead> <tbody class="tbody"> {% for i in info %} <form id="UpdateForm{{i.id}}"> <tr class="tr{{i.id}}"> <td><input type="text" value="{{i.origin}}" class="origin{{i.id}} tc form-control form-control-sm" disabled name="udtorigin" /></td> <td><input type="text" value="{{i.dest}}" class="dest{{i.id}} tc form-control form-control-sm" disabled name="udtdest" /></td> <td><input type="text" value="{{i.name}}" class="name{{i.id}} tc form-control form-control-sm" disabled name="udtname" /></td> <td> <select id="cur" class="cur{{i.id}} tc form-select form-select-sm" disabled name="udtcur"> <option value="{{i.cur}}">{{i.cur}}</option> <option value="====">====</option> <option value="USD">USD</option> <option value="KRW">KRW</option> </select> </td> <td><input type="text" value="{{i.rate}}" class="rate{{i.id}} tc form-control form-control-sm" disabled name="udtrate" /></td> <td> <select id="unit" class="unit{{i.id}} tc form-select form-select-sm" disabled name="udtunit"> <option value="{{i.unit}}">{{i.unit}}</option> <option value="====">====</option> <option value="R/TON">R/TON</option> <option value="BL">BL</option> … -
Adding to database from another database using button in django
I am creating a web application in which there is a lot of data displayed in tables. I wanted to create a platform where there are various documents, and in order to see them, the user has to send a request for access. Meaning it browses what documents are available and asks for access to see their details. Now I've run into a problem that I can't solve. I want to add data from one table to another without form. Only by clicking a button in a table row (this is the "request for access"). The data in that row would be added to another table. Unfortunately, when I click the button, nothing happens. I know I'm probably going about this the wrong way, but when no problem is displayed, the page reloads normally, I don't have any ideas how to solve it. I created models: class CourtFile(models.Model): court = models.ForeignKey(Court, on_delete=models.CASCADE, null=True) signature = models.CharField(max_length=200, null=True) article = models.CharField(max_length=200, null=True) contents_list = models.FileField(upload_to = "filepath", null=True) def __str__(self): return f'{self.court} - {self.signature}' class AccessRequest(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) status = models.BooleanField(null=True) signature = models.ForeignKey(CourtFile, on_delete=models.CASCADE, null=True) def __str__(self): return f'{self.signature}' I am displaying the table like this: <tbody> … -
How to call multiple API and render the response of all those API in a template in django
I tried rendering the response of multiple API in a single template but since once one view can we passed in the path, i am unable to think of what i can do I tried keeping the two functions to call the API inside a class but i got GET 405 error -
Live Stream text to html tamplets from Django
i have a function at the backend in django that calculate and return frames speed of a video given to OpenCv.videoCapture() .the type of the speed is float . class video_feed(object): def __init__(self, pathVideo): self.cap = cv.VideoCapture(pathVideo) #some code ..... def __del__(self): self.cap.release() def get_frames(self): #some code ... return speed_list this method keep calling the method while the video is working : def gen_speed(video_feed): print('this is spped generation method') while True: speed = video_feed.get_frames() yield(speed) @gzip.gzip_page def speed_frame(request): try: pathVideo = "video_detection/statics/rl4_pb8-7.mp4" cam = model.video_feed(pathVideo) #return StreamingHttpResponse(model.gen_test(cam),content_type="text/csv") return HttpResponse({'speed':cam.get_frames()}) except: print("speed_frame not working !!!!!!!!!!!!!!!!!!!!!!!!") but this code doesn't work . i need a way to make the speed stream to my html page so i can use it in a chartjs. streaming video using openCv is woking just fine but when i change the type to float it doesn't work . -
Django - Accessing extra ModelForm fields in a different template
I have a first view (createview) which calls a ModelForm that has an extra field added to it. The first view leads to a second view (detailview), where i need to access the fields from the previous ModelForm to show them in the template. For the fields belonging to the model, i used {{ object.fieldname }} in the template and it works. The problem that remains is how to access the field i added myself. Thank you for your help -
Upload File in a folder without using submit button in Django
I am on a Django project and the scenario is that I want to save file in a folder without clicking on submit button. I am already saving the file in a folder with the help of submit button but now the scenario has changed and now I want to save file without clicking on submit button. Here are the details of my files: views.py: def compliance_check(request):` if request.method == 'POST':` uploaded_file = request.FILES['doc']` print(uploaded_file.name)` print(uploaded_file.size)` fs = FileSystemStorage()` fs.save(uploaded_file.name, uploaded_file)` messages.info(request, 'your file ' + uploaded_file.name + " has been uploaded successfully") return render(request, 'enroll/abc.html') upload.html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="file" name="doc"> <input type="submit" name = "doc" value="upload file" class="btn btn-warning btn-sm" disabled /> </form> settings.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join('/home/t/Desktop/folder name') MEDIA_URL = '/upload/' urls.py: path('compliance_check/', views.compliance_check, name='compliance check'), Now the situation is that I am already saving file in a folder. But, now, I want to save file without clicking on submit button. -
how to save data from API whenever it updates (django)
there is an API that comes from a device. This device updates its sampling variables every 2 minutes , maybe the results change or may not(because of some conditions). i want to store this API exactly whenever the device updates itself. i have tried using background tasks with 2 minutes intervals but for example the latest result doesn't match the API at the moment , because of the delay which is convincing. I am just curious to know is it possible to store the data as soon as the device updates itself? -
Django - Send email with URL to newly uploaded file
I have a Django app where users can upload PDF files. The PDF files will be saved on my cloud provider. After successfully submitting the PDF, I want to send an email to the user with the URL to the PDF on my cloud. I've been trying to do it by overriding form_valid() but at that point, the URL is not yet generated. The URL also isn't hardcoded, so I can't just point to a hard coded URL in form_valid() Any ideas on how to solve this?