Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get single record from db in Django
VIews.py from .models import Customer as CustomerModel class Balance_Enquiry(TemplateView): template_name = 'balance_enuiry.html' def get(self, request, *args, **kwargs): if "user_id" in request.session: try: customer = CustomerModel.objects.get(user_id=request.session["user_id"]) args = {'form': form, 'posts': customer} return render(request, self.template_name, args) except Exception as e: return HttpResponse('failed: {}'.format(e), 500) Template ` {% extends 'home.html' %} {% load crispy_forms_tags %} {% block title %}Balance Enquiry{% endblock %} {% block content %} <form method="get" > {% csrf_token %} <table border="5"> <tr> <th>Amount</th> <th>Contact</th> {% for get in customer %} <tr> <td>{{ get.amount }}</td> <td>{{ get.contact }}</td> </tr> {% endfor %} i just want to get single person record after login it show the record of that person but it not show anything on screen it show just blank and even not got any error -
MultiValueDictKeyError during form submission
Previously I checked to see that there were some double names but i checked everything and still getting a MultiValueDictKeyError in idcard,I don't know what's causing this error as soon as I submit the form I get this error. <body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-if="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="form-group"> <label for="formGropuNameInput">Aadhaar Number(Enclose copy of Aadhaar Card)*:</label> <input name="adhaarno" class="form-control" id="aadhar" pattern="^\d{4}\s\d{4}\s\d{4}$" placeholder="Enter Aadhar Card number with proper spacing" required> </div> <!--<div class="custom-file"> <input type="file" class="custom-file-input" id="customFile" name="adhaaarcopy"> <label class="custom-file-label" for="customFile">Choose file</label> </div>--> </div> <!--logic for no--> <div ng-if="showHideTest=='false'"> <div class="form-group"> <label for="formGroupDistrict">Please provide any of the following Identity Card*:</label> <select name="idcard" id="formGroupDistrict" required> <option>Bank or Post Office photo passbook</option> <option>Voter ID Card</option> <option>Ration Card</option> <option>Kishan Photo Passbook</option> <option>Passport</option> <option>Driving … -
djangorestframework_simplejwt refresh token
I am trying to implement JWT authentication on a DjangoRestFramework back-end using djangorestframework_simplejwt package. I am following the steps in the following link [https://simpleisbetterthancomplex.com/tutorial/2018/12/19/how-to-use-jwt-authentication-with-django-rest-framework.html][1] The front end will be developed in Angular. My understanding: Now JWT returns an access token(short lived) and a refresh token(lives for long say 24 hrs). The access token expires say after say 5 minutes. Now we need to send the refresh token to the back-end to get a new access token with new expiry. My confusion is, will the refresh token be used to renew the access token implicitly without the knowledge of the user? If yes what kind of action should trigger this action. For e.g, if the user is idle for 5 minutes after logging in, and then clicks on some link that hits a back-end rest API, will I refresh the access token implicitly? If yes, then why not just have one token that has a long expiry duration, when we are allowing access anyway? Another question is what if I just want the token to be sent back from the back-end without any user information embedded for security reasons? Is this possible using this package? Thanks in advance -
Django cache. ManifestStaticFilesStorage
I have just started to use ManifestStaticFilesStorage and I am running into a problem I do not understand. Firstly, if I prepare and run the website without ManifestStaticFilesStorage, then everything displays properly. Within the browser I can for example, see a link to an image and if I follow that it shows the image in a resource box: Next, I add the following line of code into settings STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' and I also have: STATIC_ROOT = os.path.join(BASE_DIR, "static") I then delete the static directory and rebuild everything (migrations, collect static). This produces a website with the following link to an image, but the resource is not visible: However, when I go into the static folder in my project and look at the directory, I can see the file clearly and as far as I can tell, it appears normal: It's like Django is failing to link up correctly when I use ManifestStaticFilesStorage. I have included some other settings that may be relevant: STATIC_URL = '/static/' # STATIC_ROOT = 'static' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = [ './ebdjango/static/', ] I'm new to this, so if you have any suggestions on how to proceed with the cache in Django, please let … -
How to get distinct results when ordering by a related annotated field?
This is a Django (2.2) project using Python (3.7). Given the following models, how would I get distinct results in the query below? class Profile(models.Model): user = models.ForeignKey(User, ...) class Location(models.Model): profile = models.ForeignKey(Profile, ...) point = PointField() class ProfileService(models.Model): profile = models.ForeignKey(Profile, ...) service = models.ForeignKey(Service, ...) Here's the query I have so far which works but I end up with duplicate 'ProfileService' objects: qs = ( ProfileService.objects .annotate(distance=Distance('profile__location__point', self.point)) .order_by('distance') ) If I add .distinct('profile') it obviously fails with SELECT DISTINCT ON expressions must match initial ORDER BY expressions. I have a feeling that the solution lies in using __in but I need to keep the annotated distance field. Thanks in advance. -
Django showing custom URLs to different users
How can I display different URLs to different users based on their user_id? For example, when the user is logged in, in the dashboard user 1 with user_id 1 should have a button with a default URL like https://www.example.com/user_id so that his URL will be https://www.example.com/1 while user 2 with user_id 2 should see the URL https://www.example.com/2. I have no idea how I could achieve that. Do I need to edit the models, views or URLS file and what do I need to add? Your help is highly appreciated. -
How to JSON serialize APIField of StreamField using a ListBlocks of PageChooserBlocks
hi guys my head is spinning trying to figure this out. I cant get a response from a streamfield api using blocks.PageChooserBlock. I need to deserialize the JSON but am out of juice. I get this error Object of type 'TimelineEvent' is not JSON serializable This is the Page class Timeline(Page): content = StreamField([ ('title', blocks.CharBlock(classname="full title")), ('time_period', TimePeriodBlock()) ]) content_panels = Page.content_panels + [ StreamFieldPanel('content') ] api_fields = [ APIField("title"), APIField("content") ] I'm able to get data from TimePeriodBlock and it looks like this class TimePeriodBlock(blocks.StructBlock): def get_api_representation(self, value, context=None): dict_list = [] for item in value: temp_dict = { 'period_name': value.get("period_name"), 'description': value.get("description"), 'duration': value.get("duration"), 'events': value.get('events') } print(value.get('events')) dict_list.append(temp_dict) return dict_list period_name = blocks.CharBlock() description = blocks.CharBlock() duration = blocks.CharBlock() events = blocks.ListBlock(EventBlock()) BUT can't get anywhere near EventBlock class EventBlock(blocks.StructBlock): def get_api_representation(self, value, context=None): dict_list = [] print('here') print(value) for item in value: temp_dict = { # 'event': item.get("event"), 'short_desc': item.get("short_desc"), } dict_list.append(temp_dict) print(dict_list) return dict_list event = blocks.PageChooserBlock(page_type=TimelineEvent) short_desc = blocks.CharBlock(max_length=250) Event looks like this [StructValue([('event', <TimelineEvent: Dance 1700 fandango and jota >), ('short_desc', 'first event')]), StructValue([('event', <TimelineEvent: Dance 1700 contredanse>), ('short_desc', '2nd event')])] [StructValue([('event', <TimelineEvent: Dance 1937 Trudl Dubsky>), ('short_desc', '3rd')])] -
Django toolbar via url?
I am trying to implement debug_toolbar, Can you tell me how to use these kinds of url ^__debug__/ ^render_panel/$ [name='render_panel'] ^__debug__/ ^sql_select/$ [name='sql_select'] ^__debug__/ ^sql_explain/$ [name='sql_explain'] ^__debug__/ ^sql_profile/$ [name='sql_profile'] ^__debug__/ ^template_source/$ [name='template_source'] I tried hitting this url localhost:8000/__debug__/sql_explain/ but am getting either a 404 or or form errors -
Django annotate field not passed to serializer
I'm a little frustrated about why this does not work. Models: class User(models.Model): ... class Group(models.Model): ... class Member(models.Model): user = models.ForeignKey(User, related_name='groups') group = models.ForeignKey(Group, related_name='members') field1 = models.IntergerField() View: def get_queryset(self): Group.objects.filter(members__user=self.request.user).annotate(field1=F('members__field1')) Serializer: field1 = serializers.SerializerMethodField() def get_field1(self, obj): return obj.field1 Getting the error object has no attribute 'field1' However, using the same query in shell window successfully retrieves value for field1 g = Group.objects.filter(members__user=self.request.user).annotate(field1=F('members__field1')) print(g[0].field1) Successfully prints field1 value -
Django template: How to pass formatted string to include tag
I am new to Django and Django template, I know Django Template is kind of restrictive compare to Rails. So I am including a template in email like: {% include "./partials/_info_row.html" with value=f'{request_count} requests' %} but this throws error: TemplateSyntaxError: Could not parse the remainder: ''{request_count} requests'' from 'f'{request_count} requests'' Is there a way to pass formatted string like this to include tag? -
In Django forms, logical validation for the field
I've three fields in my model phone number, email & passworduser model. In forms, I'm using two fields phone_number & passwordforms. I write functionality for user able to login using phone number and email also. login functionalitiesIts working fine. In Front end, I'm using Bootstrap Modal form pop up. it also working fine. Problem is my error message. If wrong password, wrong password for phone number fieldit will pop up show error message in form itself, this is working. When I give doesn't exists, here I'm facing issue. when I give email ID,email field doesn't exists its pop up but when I use phone number its not coming. I don't know, where I made mistake -
why there is like Bunch of backslash in my JSON output
I m trying to send model data as json using below code Views.py def autocomplete(request): model = NewCarModel.objects.only('car_model_new') print('model is',model) # users_list = list(model) posts_serialized = serializers.serialize('json', model) print('post is',posts_serialized) return JsonResponse(posts_serialized,safe=False) models.py class NewCarModel(models.Model): car_model_new = models.CharField(max_length=100, unique=True) def __str__(self): return self.car_model_new output: "[{\"model\": \"core.newcarmodel\", \"pk\": 1, \"fields\": {\"car_model_new\": \"swift\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 2, \"fields\": {\"car_model_new\": \"wagonr\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 3, \"fields\": {\"car_model_new\": \"baleno\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 4, \"fields\": {\"car_model_new\": \"breeza\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 5, \"fields\": {\"car_model_new\": \"spresso\"}}]" why there is bunch of backslash in my JSON output and how i can remove them and Mozilla Firefox default JSON filter is also not working, neither i am able to extract data from it using java script(as i am able to extract data from some public API so there is no problem with extract code) -
Adding objects to users in Django
I am very new to Django and I am trying to build a web app that users can add the books they read and see other users that read the same book. How can I do this in Django? What functions should I add? -
how do i send ajax request by using onclick event without form enclosed tags in django
actually i have a div content,i have apply onclick event on that div when user click on that div the text between these tags should be sent to server and then display in the table as well.i have done something guid me where is the error actually,because $.ajax not working it raising an error e.g: $.ajax is not fnction players.html <div class="selectize-control single"> <div class="selectize-input items has-options not-full"> <input type="text" autocomplete="off" tabindex="" id="select_player" style="width: 146.75px; opacity: 1; position: relative; left: 0px;" placeholder="Adauga jucator la echipa"> </div> <div class="selectize-dropdown single liststyle" id="listitems" style="display: None; width: 987px; top: 29px; left: 0px; visibility: visible;"> <div class="selectize-dropdown-content"> {% block listplayers %} {% if player is not None %} {% for p in player %} <div class="option selected curserstyle sp" id="{{p.id}}" data-selectable="" data-value="{{p.YourName}}">{{p.YourName}}1</div> <div class="option selected curserstyle sp" id="49" data-selectable="" data-value="{{p.YourName}}">{{p.YourName}}2</div> {% endfor %} {% else %} <div class="text-center"> List is Empty </div> {% endif %} {% endblock %} </div> </div> </div> javascript $("#listitems").on('submit',function(e){ // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData = $(this).serialize(); // make POST ajax call $.ajax({ type:'get', url:"/templates/dashboard/players", data:serializedData, success:function(responce){ // on successfull creating object // 1. clear the … -
Django signal not printing message in terminal
I'm trying to understand the signals and use it in my application. However, even though including this signal does not give me any error message, and from Django admin panel, I can actually add a movie successfully, I can NOT see the message 'movie created' printed in my terminal when this happens. Anyone could see why? Thank you so much for any help! models.py ... from django.db.models.signals import post_save class Movie(models.Model): name = models.CharField(max_length=30) description = models.TextField(blank=True) rating = models.IntegerField(default=0, blank=True, null=True) class MovieGenre(models.TextChoices): Action = 'Action' Horror = 'Horror' History = 'History' New = 'New' genre = MultiSelectField( choices=MovieGenre.choices, max_choices=3, min_choices=1 ) def average_rating(self): rating = self.movierate_set.aggregate(Avg('rating'))['rating__avg'] return rating class Meta: ordering = ["-upload_date"] def __str__(self): return self.name def create_movie(sender, instance, created, **kwargs): if created: Movie.objects.create(name=instance) print('movie created') post_save.connect(create_movie, sender=Movie) -
Hide readonly field on form if its value is None
I have typical django model form and I want to hide one readonly field if its value is None and show if it has any value. Also this field is declared in Admin class, not on form. class DjangoAdmin(admin.ModelAdmin): from = DjangoForm readonly_fields = ("my_field",) fieldsets = ( ("Title", { "fields": ("my_field",) } ) ) def get_my_field(): value = None if ...: value = 1 return value -
Django: Problem with ContentFile: String content is not downloaded completely
I'm quite new to using Django. As first project I wrote a little tool to create M3U8-Playlists. My problem is, that long playlists are not transferred completely. This is the stripped-down code: def create(request): # just a dummy filelist playlist = ["#EXTM3U"] + 5 * ["/home/pi/music/" + 5 * "äöü0123456789á/" + "xyz.mp3"] file_to_send = ContentFile("") for item in playlist: file_to_send.write("{}\n".format(item.replace("/home/pi/Music", r"\\raspberry\music").replace("/", "\\"))) response = HttpResponse(file_to_send, "audio/x-mpegurl") response["Content-Length"] = file_to_send.size response["Content-Disposition"] = f"attachment; filename=\"playlist.m3u8\"" # print some debug info print("lines:", len(playlist), "chars (no linebreaks)", sum([len(entry) for entry in playlist]), "filesize:", file_to_send.size) return response The problem seems to lie in the non-ascii chars in playlist entries (äöüá). When there are no such characters, the file is transferred intact. I assume that these are characters that use two bytes in UTF-8, but writing strings to the ContentFile like I do is probably not correct. -
One-to-one relationship with two models (fields) in Django to the current model
How to have one-to-one relationship with two models (fields) in Django (User and Product to be one-to-one together to Review)? So one user should have one review per product. Is there a built-in solution in Django models? Obviously having them both foreignkeys would be wrong as given here. from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): title = models.CharField(max_length=255) class Product(models.Model): title = models.CharField(max_length=255) class Review(models.Model): title = models.CharField(max_length=255) user = ForeignKey(User, on_delete=models.CASCADE) product = ForeignKey(Product, on_delete=models.CASCADE) -
How to limit prefetch record in django
In this, I deal with 2 tables: brand & product. so I've used prefetch_related to get related products for a particular brand with only minimum brand price. but the problem is when I have 2 products at the same price it selects both records so how to limit this? alternatives_data = Brand.objects.filter(category__category_slug = category_slug).prefetch_related( Prefetch('products', queryset=Product.objects.annotate( min_brand_price=Min('brand__products__product_price') ).filter( product_price=F('min_brand_price') ).order_by('product_id'))) -
Django & Celery: calling a Class function as a Celery task
I'm having a little conceptual trouble with setting a class based Celery task (Just a quick note, this is different as I am not inheriting from the celery.Task class). The bound app task is merely a class method. I have the following in my celery.py file: import os import celery from celery.schedules import crontab from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Wave.settings') app = celery.Celery('DjangoProject', include=['amq.v1.TaskRunner.demand', 'amq.v1.TaskRunner.periodic']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(minute='1,11,21,31,41,51', hour='*', day_of_week='*', day_of_month='*'), APIMiddelwareTasks().dispatch_bookings_fetch.s(), ) class APIMiddelwareTasks(): def get_middleware_class(self, *args, **kwargs): from django.conf import settings return MiddlewareAPIClass( headers={'Content-Type': 'application/soap+xml; charset=UTF-8'}, config=settings.middleware_config, debug=False ) @app.task(bind=True) def dispatch_bookings_fetch(self, *args, **kwargs): # This is the main call for the MiddlewareAPI wrapper class. The config in settings.py contains the parameters from both the sandbox and production workstations. # Setting sandbox to True will query the sandbox workstation, and setting debug to True will query known session dates and times. middleware = self.get_middleware_class() ... However, the above seems to throw the following error: AttributeError: 'dispatch_surfers_bookings' object has no attribute 'get_middleware_class' Would anyone know the best way to create a class based of multiple app tasks, with the ability to reference various self.methods() within that task? Should I just class this … -
Django many-to-many query matching all related fields
I have two models connected by a many-to-many relationship in django. class BuildingMapping(models.Model): name = models.CharField(max_length=1000, null=False) buildings = models.ManyToManyField( Building, related_name="mapping" ) class Building(models.Model): function = models.CharField( max_length=1000, blank=True, null=True ) Function is a string containing one or more identifier divieded by a "/" e. g. "1300", "1300/2200", "1300/2230/7500", ... I now want to perform a query that gets only BuildingMapping instances where the function for all Buildings is identical. I tried the following, but this will also return BuildingMapping instances where only one Building has "1300" as function. BuildingMapping.objects.filter(buildings__function="1300") Thanks! -
Django staticfiles files problems
i have problem with Django staticfiles. anyway everything works good but when i want change something in Css or in image or Js nothing is happening. in settings.py i have this # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') i have 2 folder of statics first is static and seccond one i get after manage.py collecstatic i get another folder (staticfiles) so even when i'm deleting both folder my website files not Brokening i need to restart my mac. plus i cannot change elements in css because i'm woking on both folder but nothing happend enter image description here P.S sorry guys for my english . i'm learning it :( <3 -
Jquery Elements in a webpage not loading on webpage on clicking browser back button
I have a html form page(page 1) from where I go to page 2 html page. In page 1 I have fields such as Resolution, on selecting particular resolution populates fields such as frame-width and height(with value) which is loaded using Jquery and is disabled (just to show) Similarly I have cascaded drop-downs. On submission of this form I get the results on the same page. Also I have given option to display the output on new page. But when I get back to the previous page from new page. Jquery Elements are not loaded. Only static elements in form are loaded. Resolution stays but frame width and frame-height is not loaded. Also output on same page is also gone. How can I get to previous page as per my submission made. I am using Django in Back-end. Index.html <p><label>Resolution:</label> <select id="resol" name="resol" class="ip" autocomplete="off"> <option disabled selected value> -- select an option -- </option> <option value="2K">2K</option> <option value="4KDCI">4KDCI</option> <option value="4KUHD">4KUHD</option> <option value="480p">480p</option> <option value="576p">576p</option> <option value="720p">720p</option> <option value="1080p">1080p</option> <option value="CIF">CIF</option> <option value="FWVGA">FWVGA</option> <option value="HVGA">HVGA</option> <option value="QCIF">QCIF</option> <option value="QVGA">QVGA</option> <option value="VGA">VGA</option> <option value="WVGA">WVGA</option> <option value="other">other</option> <option value="all">All</option> </select> </p> Jquery to display $('#resol').change(function () { var value = $(this).val(); //history.pushState(null,null,"#resolution"); … -
Django user group == another model's group
I just lost myself a little, and I'm stuck on this one. I have a model which has a group field : class CalendarGroups(models.Model): GRP_CALS = ( ('Grp1', 'Grp1'), ('Grp2', 'Grp2'), ('Test', 'Test'), ) name = models.CharField(max_length=155, choices=GRP_CALS, blank=True, null=True) def __str__(self): return self.name class Meta: ... class CalendarMaster(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) group = models.ForeignKey(CalendarGroups, on_delete=models.CASCADE) date_valid = models.DateTimeField(null=True, blank=True) I just want to check, if the User's group matches the Calendar group - some context will be rendered. I tried with: user_groups = request.user.groups.values_list('name', flat=True) calendar_groups = CalendarMaster.objects.all() {% if user_groups in calendar_groups %} But somehow, I cant manage it -.- PS.User groups are the same as CalendarMaster's -
Highlight word and send GET request
I've created a text field in a Django model. I want to highlight words when word is clicked. I've found this answer How can I adjust it to send a GET request to Django when a word is selected to receive JSON from other website API? Thanks in advance! $(function() { editTxt('#myTxt'); editTxt('#myTxtDiv'); $('span').live('mouseover', function() { $(this).addClass('hlight'); }); $('span').live('mouseout', function() { $(this).removeClass('hlight'); }); }); function editTxt(selector) { $(function() { var newHtml = ''; var words = $(selector).html().split(' '); for (i = 0; i < words.length; i++) { newHtml += '<span>' + words[i] + '</span> '; } $(selector).html(newHtml); }); }