Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Tablesorter for Select?
I'm trying to use tablesorter.js to sort a column by a select box. I can't seem to make it work and I've tried most of the stuff written either here or in the docs. Was wondering if someone could help me out with this. I'm using Django which shouldn't matter I think, but here is the HTML and JS: HTML: <tr> <th></th> <th></th> <th></th> {% if perms.directors.director %} <th></th> {% endif %} <td class=""> <select class="" > <option value=""></option> <option value="Incomplete">Incomplete</option> <option value="Submitted">Submitted</option> <option value="OnHold">OnHold</option> <option value="Qualified">Qualified</option> <option value="Denied">Denied</option> </select> </td> </tr> </thead> <tbody> {% for org in object_list %} <tr class="{{ forloop.counter|divisibleby:2|yesno:"even,odd" }}"> <td><a href="{{ org.get_absolute_url }}">{{ org.name }}</a></td> <td>{{ org.submission_date | date:"Y/m/d" }}</td> <td>{{ org.updated_date | date:"Y/m/d" }}</td> {% if perms.directors.director %} <td>{{ org.review_note_date | date:"Y/m/d" }}</td> {% endif %} <td> <span class="label {{ org.bootstrap_color_state }}"> {{ org.pretty_state }}</span> </td> <td> </td> </tr> {% endfor %} </tbody> JS: $('.table').each(function () { var $table; $table = $(this); $table.find('a').not('.btn').closest('td, th').css({ 'padding': 0 }); $table.find('.amount').addClass('text-right'); // Adds tablesorter plugin to .table, so to sort on <th>s $table.tablesorter().addClass('tablesorter'); // Add up/down arrows to indicate which order column data is displayed $table.bind('sortEnd', function (event, table) { $(table).find('.glyphicon').remove(); $(table).find('.tablesorter-headerAsc > div').append('<span class="glyphicon glyphicon-chevron-up" />'); … -
Django models ManyToManyField always adding item to list
I'implemented two models, Card and Dish. I used many-to-many relationship because Dish can be in many cards. Not sure if I did that right because any Dish that I add is automatically added to every Card. Here is the code: class Dish(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1000) price = models.DecimalField(max_digits=5, decimal_places=2) preparation_time = models.IntegerField() date_added = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) vegan = models.BooleanField(default=False) def __str__(self): return self.name class Card(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1000) date_added = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) dishes = models.ManyToManyField(Dish, blank=True) def __str__(self): return self.name An the problem in admin panel looks like this: When I create a dish it is alway added to every card. Any help please I'm just begining to learn sql and django ORM -
Djnago rest framework html/url to docx
I am creating a Django API that converts any URL or HTML file into pdf and Docx. The implemented code below already renders in pdf format using pdfkit package. I'm using python-docx to generate in Docx, but I don't know how to handle it. I would like to have any support, please. I don't have deep knowledge and any help will be appreciated. Here is my convert.py file: import io from pydoc import doc from tempfile import NamedTemporaryFile from typing import IO from urllib.parse import urlparse import pdfkit from docx import Document class ConvertingError(Exception): """ This exception represents an error during converting. In example, when Host of a url is unreachable. In other words, this is a wrapper for wkhtmltopdf errors. """ pass def url_to_pdf(url: str) -> IO: """Fetch HTML from url and convert the page to pdf,""" with NamedTemporaryFile('w+b') as tmpf: try: pdfkit.from_url(url, tmpf.name) except OSError as e: raise ConvertingError from e pdf = io.BytesIO(tmpf.read()) return pdf def html_to_pdf(html: str) -> IO: """Convert HTML string to pdf.""" with NamedTemporaryFile('w+b') as tmpf: try: pdfkit.from_string(html, tmpf.name) except OSError as e: raise ConvertingError from e pdf = io.BytesIO(tmpf.read()) return pdf def filename_from_url(url: str) -> str: """ Generate pdf filename using a hostname … -
Update function creating new object instead of updating existing in django?
i am creating a comment update function using django and ajax, and i am trying to update the comment without refreshing the page, now when i click on the edit button, the exisiting comment get filled in the input box ready for edit, when i edit the text (comment) instead of saving the new edit to the old one; it goes ahead an create a new comment all together, how do i prevent that. view.py ## edit comment @csrf_exempt def edit_comment(request): if request.method == "POST": id = request.POST.get("cid") comment = Comment.objects.get(pk=id) comment_data = {"id": comment.id, "comment": comment.comment, "video": comment.video.id} return JsonResponse(comment_data) ## Create comment def ajaxComment(request): if request.method == "POST": pk = request.POST.get("id") video = Video.objects.get(id=pk) user = request.user comment = request.POST.get("comment") new_comment = Comment(user=user, video=video, comment=comment) new_comment.save() print(id) print(user) print(comment) print(video) response = "Comment Posted" return HttpResponse(response) ajax code // Edit $('.comment-wrapper').on("click", ".btn-edit", function(){ console.log("Edit Button Cliked"); let id = $(this).attr("data-cid"); console.log(id); mydata = {cid:id} $.ajax({ url: "{% url 'edit-comment' %}", method:"POST", data:mydata, success: function(data){ console.log(data); $("#id").val(data.id) $("#id").val(data.video) $("#comment").val(data.comment) // $(".new_comment").val(data.video) console.log(data.id); }, }) }) $(document).on("submit", "#comment_form", function(e){ e.preventDefault(); let _comment = $("#comment").val() console.log("send button clicked") $.ajax({ type: "POST", url: "{% url 'save-comment' %}", data:{ id: $("#id").val(), comment: _comment, … -
In Django, I have added my app to INSTALLED_APPS but still can't use makemigrations command
I have added my app to INSTALLED_APPS This is my class created for the app And here, I have registered my app to the admin panel -
uploaded video not showing up
So I have uploaded videos for a class model for an educational website but that video is not being rendered. What can I do to render it? My models.py: class Class(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='class/class_videos',null=True, validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])]) def __str__(self): return self.title class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) students = models.ManyToManyField(User, related_name='courses_joined', blank=True) classes = models.ForeignKey(Class, on_delete=models.CASCADE, null=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title My views.py: class CourseDetailView(LoginRequiredMixin, DetailView): model = Course template_name = 'class/course.html' My html file : {% extends "class/base.html" %} {% load crispy_forms_tags %} {% block content %} <h1>{{ object.title }}</h1> {{ object.classes.video }} {% endblock content %} The output is the title of the class and the <name>.mp4 filename where name is the name of the video file I uploaded. But I want the video to be rendered. Can anyone help me ? Thanks in advance! -
How to know what serializer_class is used
I define a serializer class in the get_serializer_class function. In my update function, how can I know which serializer class is selected? What is the best practice for this? Simple code: class SomeViewSet(ModelViewSet): model = SomeModel def get_serializer_class(self): # here I define my serializer class, let's say between FirstSerializerClass and SecondSerializerClass def update(): if serializer_class == FirstSerializerClass: # I checked this way, but it didn't work for me -
django rest framwork filter by year or month
How can i filter date by year or by month in django rest framework my model class DailyJues(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.IntegerField() date = models.DateField(default=timezone.now) my views class DailyJuesViews(APIView): def get(self, request): daily_jues = DailyJues.objects.all() serializer = DailyJuesSerializers(daily_jues, many=True) return Response(serializer.data) def post(self, request): serializer = DailyJuesSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django-admin startproject foo : Access denied
I am trying to install django and create a project I am not able to get any success I have looked on internet but could not find solution for this. I am also running my cmd with admin. I have also check permission of folder. I also tried running in virtual env but same error. -
How to use group by, max of a column and also getting other columns of the model from a Django queryset?
I have a model that looks like this class Documents(models.Model): id = models.AutoField(primary_key=True, editable=False) uid = models.CharField(max_length=64) version = models.IntegerField() reviewed_dtm = models.DateTimeField(null=True) timestamp = models.DateTimeField(auto_add_now=True) document = models.FileField() I want the average time difference between the timestamps for the maximum version and the minimum number for every uid. I basically want to know the average time it takes for a document to be reviewed by a user since its creation. Being reviewed is optional, if a user finds the document to be good then marks it as reviewed, or else sends it for the new version. Then another record is made for the uid with an updated version. -
Return many to many field queryset as json
I am trying to return all the results of a many to many query (all the customers linked to a store i.e. a customer can be linked to many stores). I have the following models and serializers class Customer(models.Model): stores = models.ManyToManyField(Store) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) ... class Store(models.Model): store_name = models.CharField(max_length=30, unique=True, null=True) ... class CustomerSerializer(serializers.ModelSerializer): stores = serializers.PrimaryKeyRelatedField(queryset=Store.objects.all(), write_only=True, many=True) class Meta: model = Customer fields = ['stores', 'first_name', 'last_name', ...] In my views, I want to get all the customers in a store and return them like this: def return_customers(request, *args): ... store = Store.objects.get(account__email=user) customers = Customer.objects.filter(stores__id=store['id']) print(customers) json_customers = CustomerSerializer(customers).data print(json_customers) context = { 'customers': json_customers, } return Response(context, status=HTTP_200_OK) This returns an empty object {} print(customers) gives: <QuerySet [<Customer: Michael>, <Customer: Naomi>, <Customer: Blessing>, <Customer: John>, <Customer: Cena>]> print(json_customers) gives: {} If I try to return customers instead of json_customers, I get error message (Type Error): Object of type Customer is not JSON serializable If I try json_customers = CustomerSerializer(customers[0]).data I get only the first customer (I want all of them): "customers": { "id": 7, "first_name": "Michael", "last_name": "", ... }, I have tried this with other models that don't … -
Should I use Many-to-one relationship or a Many-to-many?
Basically I am creating a website using django where I have created a class called courses and a separate class Class. I'm now confused which relationship I should use. My code: class Class(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='class/class_videos',null=True, validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])]) def __str__(self): return self.name class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) students = models.ManyToManyField(User, related_name='courses_joined', blank=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title Thanks in advance! -
How to hide an HTML generated link that should only be called by javascript addeventListener?
I have a Django app, and want to have an image appear on a webpage only when someone clicks a specific element/image 30 times as such: var count = 0; document.addEventListener('DOMContentLoaded', function(){ document.querySelector("#PDDO").onclick = function(){ if(count > 30){ document.querySelector("#PDDO").src = document.querySelector("#PDDO").dataset.over }else{ count++; } }}) When this code is executed, the original image is replaced with the hidden image, which is hardcoded in the URL as such: <img src="{% static 'database/images/original_image.png' %}" width="200", height="200", class="revolve" id="PDDO" data-over="{% static 'database/images/new_image.png' %}"> </div> However, people can easily find the source of this image simply by inspecting the page source code, and I can't seem to hide it: #Page source: <img src="/static/database/images/original_image.png" ,="" class="revolve" id="PDDO" data-over="/static/database/images/new_image.png" width="200" height="200"> I tried to implement js solutions such as below, but to no avail. $("a[data-label='document.querySelector("#PDDO").dataset.over']").hide() What is the best way to hide the image url from the page source? -
Is this way to reset password fine?
I wrote a code to resetting user password. I just want to ask if it is a good and secure way to do this? Can I make any improvements here? I use send_password_resetting_message function to send an email with a link to reset password and when I go on this page I use there set_new_password to set new password using uidb64, token and new password. I am using DRF. views.py from .utils import password_reset_token @api_view(['POST']) def send_password_resetting_message(request): try: email = request.data['email'] if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) email_subject = "..." email_body = render_to_string('password_resetting/index.html', { 'user': user, 'domain': settings.FRONTEND_APP_ADDRESS, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': password_reset_token.make_token(user) }) email=EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[email]) email.content_subtype='html' email.send() return Response(status=status.HTTP_200_OK) except: return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['POST']) def set_new_password(request, uidb64, token): try: uid = force_text(urlsafe_b64decode(uidb64)) user = User.object.get(pk=uid) except Exception as e: user=None if user and password_reset_token.check_token(user, token): user.set_password(request.data['password']) user.save() return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_403_FORBIDDEN) utils.py class PasswordResetTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.password)) password_reset_token = PasswordResetTokenGenerator() -
Django - doesn`t make the migrations
In Django, after I created a model, in cmd I runned: "python manage.py makemigrations" and returned that: Migrations for 'hello': hello\migrations\0001_initial.py - Create model Article hello is the name of app. And after I runned: "python manage.py migrate" returned: Operations to perform: Apply all migrations: admin, auth, contenttypes, hello, sessions Running migrations: No migrations to apply. And when I try to introduce a field in that model appear: OperationalError at /admin/hello/article/add/ no such table: hello_article I tried to delete all migrations and I created again the model and the result was the same. How fix this? -
count all objects within a values_list Django
This is a follow up question to this Django object has no attribute in a _set.filter @property def mathe2(self): return self.lehrertabelle_set.count() @property def mathe3(self): return self.lehrertabelle_set.values_list('Stundenanteil_bei_WE', flat=True)[0] + self.mathe2 I got so far that I can calculate that but I need everything within values_list counted together, pls tell me how, I have no clue -
Oauth2-proxy - 404 error when redirecting to upstream url (Django application web page)
I'm trying to protect a Django application with oauth2-proxy In the oauth2-proxy configuration: (version 7.2.1 or 7.3.0) When the upstream url is set to something like this: --upstream="http://127.0.0.1:8000" the redirection works fine. (and it returns a home page I have defined in the application ) But, if I use an upstream like this: --upstream="http://127.0.0.1:8000/hello" it returns 404 error instead of the hello page that is also defined in the application The page http://127.0.0.1:8000/hello is working fine when invoked directly and it returns "GET /hello HTTP/1.1" 200 136 So I would say it is not a problem with the page. This is the command line I'm using: oauth2-proxy.exe ^ --http-address=127.0.0.1:4180 ^ --email-domain=* ^ --cookie-secure=false ^ --cookie-secret=adqeqpioqr809718 ^ --upstream="http://127.0.0.1:8000/hello" ^ --redirect-url=http://127.0.0.1:4180/oauth2/callback ^ --oidc-issuer-url=http://127.0.0.1:28081/auth/realms/testrealm ^ --insecure-oidc-allow-unverified-email=true ^ --provider=keycloak-oidc ^ --client-id=oauth2_proxy ^ --ssl-insecure-skip-verify=true ^ --client-secret=L2znXLhGX4N0j3nsZYxDKfdYpXHMGDkX ^ --skip-provider-button=true When the oauth2-proxy succeeds to redirect (--upstream="http://127.0.0.1:8000"), I get the page and the following output: This is the output for the oauth2-proxy: [2022/09/08 10:52:06] [proxy.go:89] mapping path "/" => upstream "http://127.0.0.1:8000" [2022/09/08 10:52:06] [oauthproxy.go:148] OAuthProxy configured for Keycloak OIDC Client ID: oauth2_proxy [2022/09/08 10:52:06] [oauthproxy.go:154] Cookie settings: name:_oauth2_proxy secure(https):false httponly:true expiry:168h0m0s domains: path:/ samesite: refresh:disabled [2022/09/08 10:57:01] [oauthproxy.go:866] No valid authentication in request. Initiating login. 127.0.0.1:54337 - … -
Dynamically setting max_value and min_value in a Django/DRF serializer field
I am trying to validate some query params in a Django request handler. I am expecting to receive a number n that's bounded by a range. I'd like to validate n using rest_framework.serializer. Something like this: class NumberSerializer(serializers.Serializer): number = serializers.FloatField(min_value=1, max_value=10) However, I'd like to set min_value and max_value inside FloatField dynamically. Is that possible? I can roll my own validator, but I am trying to learn DRF serializers. So far I feel like DRF serializers have a very specific purpose (validating incoming data against a model), but I want to get into the habit of using serializers for more generic validations like the example above. -
(elasticbeanstalk, Django, postgresql) Unable to migrate existing data to elasticbeanstalk
I have deployed my django api to the AWS elasticbeanstalk, after numerous trying, I successfully deployed the django app without any error => Environment update completed successfully. The log file also seems fine to me, I can access my django website. However, there is no data inside the elasticbeanstalk database. After looking into the log file. The django was successfully migrated. I have no idea what is going on here. log file: 2022-09-08 16:20:37,014 P3694 [INFO] Command 01_makemigrations 2022-09-08 16:20:37,520 P3694 [INFO] -----------------------Command Output----------------------- 2022-09-08 16:20:37,521 P3694 [INFO] No changes detected 2022-09-08 16:20:37,521 P3694 [INFO] ------------------------------------------------------------ 2022-09-08 16:20:37,521 P3694 [INFO] Completed successfully. 2022-09-08 16:20:37,528 P3694 [INFO] ============================================================ 2022-09-08 16:20:37,528 P3694 [INFO] Test for Command 02_migrate 2022-09-08 16:20:37,531 P3694 [INFO] Completed successfully. 2022-09-08 16:20:37,531 P3694 [INFO] ============================================================ 2022-09-08 16:20:37,531 P3694 [INFO] Command 02_migrate 2022-09-08 16:20:38,080 P3694 [INFO] -----------------------Command Output----------------------- 2022-09-08 16:20:38,080 P3694 [INFO] Operations to perform: 2022-09-08 16:20:38,081 P3694 [INFO] Apply all migrations: admin, api, auth, contenttypes, sessions 2022-09-08 16:20:38,081 P3694 [INFO] Running migrations: 2022-09-08 16:20:38,081 P3694 [INFO] No migrations to apply. 2022-09-08 16:20:38,081 P3694 [INFO] ------------------------------------------------------------ 2022-09-08 16:20:38,081 P3694 [INFO] Completed successfully. env config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: backend.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "backend.settings" package config: packages: yum: postgresql-devel: [] django config: option_settings: … -
Display data from a Django model as a Tree view
I have a Django model as shown below class operationTemplates(models. Model): templateID = models.IntegerField(primary_key = True) templateCategory = models.CharField(max_length=255, blank=True, null=True) templateName = models.CharField(max_length=400, blank=True, null=True) templatePreopBundle = models.CharField(max_length=255, blank=True, null=True) templatePosition = models.CharField(max_length=20, blank=True, null=True) I want to display the data as a tree view using either CSS or Javascript. Tree view should order the data by "templateCategory" as follows - Category1 |__Name1 |__Name2 |__Name3 + Category2 - Category3 |__Name6 |__Name7 |__Name9 |__Name10 I am using Django2 and Python3.7 Thanks in advance. -
How to increment a django value_list
I'm trying to find a way to add one more element to the list, but with my first attempt using append it didn't work, as it's a queryset. Any tips on how to add an element to generos after the value_list query? generos = Specie.objects.values_list('Genus', flat=True) generos.append('NA') -
How to dinamically access to a field in django form to change instance
Using a generic CreateView in Django I'm trying to save only the fields that have been changed by user. I'm trying to do this in my view: def form_valid(self, form): if form.has_changed(): for field in form: if field.name in form.changed_data: continue else: form.instance.field=None In the last line I got this error: object has no attribute 'field' Is there a way to dynamically access to each field in the form? so I could change it? -
How to get the latest (distinct) records filtered by a non unique field in Django
I'll demonstrate by using an example. This is the model (the primary key is implicit): class Item(models.Model): sku = models.CharField(null=False) description = models.CharField(null=True) I have a list of skus, I need to get the latest descriptions that are written in the table for the model Item. Latest item == greatest id. I need a way to annotate the latest description: Item.objects.values("sku").filter(sku__in=list_of_skus).annotate(latest_descr=Latest('description').order_by("-id") but this won't work for various reasons (excluding the missing aggregate function). -
Can I tell PyCharm that a function argument is a Django template path to enable autocomplete?
In Pycharm, values from built-in Django functionality which will eventually be used as the argument to resolve_template (such as the template_name property on TemplateView) are subject to autocomplete using the Django template lookup syntax. I have a custom function whose signature includes a template name. Is there a way to annotate this function such that PyCharm will provide the same template directory autocomplete for uses of this custom function as it provides for built-in functionality? -
Subclassing TemplateView with Mixins - a bad idea?
I have several "Listing" views which are very similar and I feel like I'm unecessarily repeating myself. Subclassing seems like the answer, but I've run into problems down the line before when subclassing things in Django so I'd like to ask before doing so. If I have 2 views, like this, which use the same template, a variable message and different querysets: class MyGiverView(LoginRequiredMixin, TemplateView): template_name = "generic_listings.html" message = "" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["list_of_stuff"] = MyModel.objects.filter( giver=self.request.user, status=1, ) context["message"] = self.message return context class MyTakerView(LoginRequiredMixin, TemplateView): template_name = "generic_listings.html" # this hasn't changed message = "" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["list_of_stuff"] = MyModel.objects.filter( taker=self.request.user, # this has changed status__in=(1,2,3), # this has changed ) context["message"] = self.message # this hasn't changed return context Am I going to screw it up by creating a base class like: class MyBaseView(LoginRequiredMixin, TemplateView): template_name = "generic_listings.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["list_of_stuff"] = self.qs context["message"] = self.message return context And using it in my views as such: class MyGiverView(MyBaseView): qs = MyModel.objects.filter( giver=self.request.user, status=1, ) message = "" class MyTakerView(MyBaseView): qs = MyModel.objects.filter( taker=self.request.user, status__in=(1,2,3), ) message = "" It's DRYer, but I'm unsure of the …