Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django deployment on aws lightsail with apache
i'm trying to deploy my django project in amazon lightsail with apache. i now get the 500 internal server error, the log files says that i'm missing django. this is the error log: [Fri Jun 18 09:17:21.185206 2021] [mpm_event:notice] [pid 18855:tid 139805003744384] AH00491: caught SIGTERM, shutting down [Fri Jun 18 09:17:21.234245 2021] [mpm_event:notice] [pid 32187:tid 139822253159552] AH00489: Apache/2.4.38 (Debian) mod_wsgi/4.6.5 Python/3.7 configured -- resuming norma l operations [Fri Jun 18 09:17:21.234333 2021] [core:notice] [pid 32187:tid 139822253159552] AH00094: Command line: '/usr/sbin/apache2' [Fri Jun 18 09:17:58.402513 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] mod_wsgi (pid=32188): Failed to exec Python script file '/var/ww w/sito_fotografo/sito_fotografo/sito/wsgi.py'. [Fri Jun 18 09:17:58.402562 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] mod_wsgi (pid=32188): Exception occurred processing WSGI script '/var/www/sito_fotografo/sito_fotografo/sito/wsgi.py'. [Fri Jun 18 09:17:58.402710 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] Traceback (most recent call last): [Fri Jun 18 09:17:58.402734 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] File "/var/www/sito_fotografo/sito_fotografo/sito/wsgi.py", li ne 12, in <module> [Fri Jun 18 09:17:58.402777 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] from django.core.wsgi import get_wsgi_application [Fri Jun 18 09:17:58.402796 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] ModuleNotFoundError: No module named 'django' [Fri Jun 18 09:23:28.841563 2021] [wsgi:error] [pid 32188:tid 139822105474816] [remote 93.43.210.55:49231] mod_wsgi (pid=32188): Failed to … -
Django Rest Framework group fields
I'm exposing an REST api for legacy application. I have a Company model class that defines the following fields: address_street (required) address_street_number (required) shipping_address_street (optional) shipping_address_street_number (optional) billing_address_street (optional) ... you got the point I would like to group all address fields into an Adress serializer in order to have a cleaner structure. Some thing like: { "adress": {"street": "foo", "street_number": "bar"}, "shipping_address": {"street": "ham", "street_number": "spam"}, "billing_address": null, } So far, I can create a CompanySerializer from a rest_framework.serializers.Serializer and manually build my Company objects from this. It is tedious, but it will work. But how can I build a rest_framework.serializers.ModelSerializer for my Company model, changing the way fields are structured to have my model fields automatically populated by rest framework ? DRF nested model serializers seems to only work for relations, not groups of fields. Am I to build my models instances by hands or is there a way to decouple the representation of a model serializer to my object ? -
Not getting output from api after hosting in Django
Hi I making a page where user can enter pincode for their respective state and can get availability of vaccine in their area. It's run perfectly on local server but when I hosted it show no output neither any error. (https://doctorz.pythonanywhere.com/vaccine) my views.py def vaccine(request): try: today = date.today() d1 = today.strftime("%d-%m-%Y") pincode = request.GET.get('pincode') pincode = str(pincode) # # pincode = '110065' baseurl = 'https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByPin?pincode={}&date={}'.format(pincode,d1) # baseurl = 'https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByPin?pincode=110025&date=15-06-2021' vaccine = requests.get(baseurl) data = vaccine.json() vaccinedate = data["sessions"] return render(request, 'vaccine_data.html', {'vaccinedate':vaccinedate}) except: return render(request, 'vaccine_data.html') vaccine_data.html {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block body %} <div> <div class="form-control formy"> <form method="GET"> <label for="pincode" style="margin: 5px 0px 5px 0px;">Enter Pincode: </label> <input class="" type="text" name="pincode"> <button class="btn btn-primary" type="submit">Submit</button> </form> <br><br> <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Center ID</th> <th scope="col">Name</th> <th scope="col">Address</th> <th scope="col">Fee Type</th> <th scope="col">Vaccine</th> <th scope="col">Age limit</th> </tr> </thead> <tbody> {% for i in vaccinedate %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{i.center_id}}</td> <td>{{i.name}}</td> <td>{{i.address}}</td> <td>{{i.fee_type}}</td> <td>{{i.vaccine}}</td> <td>{{i.min_age_limit}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> {% endblock body %} urls.py from django.urls import path from home import views from django.conf.urls import * urlpatterns = [ path('',views.index, name="home"), path('home',views.index, name="home"), … -
Celery data import leads to MultipleObjectsReturned
I'm running a Celery Data import Job but I'm running into the following issue Task Import Descriptor[ef5cad5c-26aa-40de-89a0-e85fb0d580a2] raised unexpected: MultipleObjectsReturned('get() returned more than one MusicAlbums -- it returned 2!' This happens because I call the task like this: for clean_obj in keys: .... if not Files.objects.filter(descriptor=strip_descriptor_url_scheme(url)).exists(): task = import_descriptor.delay(descriptor=url) task.get(timeout=120, interval=3) which basically puts all descriptors I try to import directly onto the message queue... I don't have issues if I call the task like that, because every descriptor gets imported one after another: task = import_descriptor.apply_async(kwargs={"descriptor": str(url)}) task.get(timeout=120, interval=1) Inside the task this happens: if not MusicArtists.objects.filter(title=artist_value).exists(): new_music_artist_object = MusicArtists.objects.create(title=artist_value) new_music_artist_object.save() new_music_artist_object.refresh_from_db() else: new_music_artist_object = MusicArtists.objects.get(title=artist_value) if not MusicAlbums.objects.filter(artist=new_music_artist_object, title=album_value).exists(): new_music_album_object = MusicAlbums.objects.create(title=album_value, artist=new_music_artist_object, cover=cover_value, total_discs=total_discs_value, total_tracks=total_tracks_value, copyright=copyright_value, release_date=release_date_value, genre=genre_value) new_music_album_object.save() new_music_album_object.refresh_from_db() else: new_music_album_object = MusicAlbums.objects.get(artist=new_music_artist_object, title=album_value) new_music_track_object = MusicTracks.objects.create(file=new_file_object, album=new_music_album_object, artist=new_music_artist_object, bitrate=bitrate_value, duration=duration_value, size=size_value, nb_streams=nb_streams_value, media_type=0, title=title_value, release_date=release_date_value, disc=disc_value, track=track_value ) new_music_track_object.save() new_music_track_object.refresh_from_db() The problem with this is that if multiple celery processes are working on the task queue I sometimes have the same Artist, Album or Track saved at the Database twice with two different primary keys ... So my question is how could I possibly bypass this behavior without creating my whole database sequential as this … -
I'm trying to change password using the django built in functionality but it's not working
Problem I'm trying to change the password using the Django in-built authentication functionality but it doesn't change the password and doesn't even redirect to the next page. I have pasted all the code below which I have written for this, please can anyone can check it and tell me what am I doing wrong. form.py class MyPasswordChangeForm(PasswordChangeForm): old_password = forms.CharField(label=_("Old Password"),strip=False,widget=forms.PasswordInput(attrs={'autocomplete':'current-password', 'autofocus':True,'class':'form-control'})) new_password1 = forms.CharField(label=_("New Password"),strip=False,widget=forms.PasswordInput(attrs={'autocomplete':'new-password','class':'form-control'}),help_text=password_validation.password_validators_help_text_html()) new_password2 = forms.CharField(label=_("Confirm New Password"),strip=False,widget=forms.PasswordInput(attrs={'autocomplete':'new-password','class':'form-control'})) urls.py path('passwordchange/',auth_views.PasswordChangeView.as_view(template_name='main/passwordchange.html',form_class=MyPasswordChangeForm, success_url='/passwordchangedone/'),name='passwordchange'), passwordchange.html {% extends 'main/base.html' %} {% load static %} {% block title %}Buy Now{% endblock title %} {% block main-content %} <div class="container my-5"> <div class="row"> <h3>Welcome {{request.user.username.title}}</h3> <div class="col-sm-2 border-end"> <ul class="list-unstyled"> <li class="d-grid"><a href="{% url 'main:profile' %}" class="btn btn-primary">Change Password</a></li> </ul> </div> <div class="col-sm-9 offset-sm-1"> <h3>Change Password</h3> <hr> <form action="" method=" post" novalidate class="shadow-sm p-5"> {% csrf_token %} <!-- {{form.as_p}} --> {% for fm in form %} <div class="form-group"> {{fm.label_tag}}{{fm}} <small class="text-danger">{{fm.errors|striptags}}</small><br> </div> {% endfor %} <input type="submit" class="btn btn-primary mt-4" value="Save"> {% if form.non_field_errors %} {% for error in form.non_field_errors %} <p class="alert alert-danger my-3">{{error}}</p> {% endfor %} {% endif %} </form> </div> </div> </div> {% endblock main-content %} -
Init.py goes for local settings.py rather than production settings.py DJANGO
I created a setting folder with init.py, base.py, local. py and production.py but the Heroku address (host) is always trying to use local settings. The app works fine when I access it from '127.0.0.1' but displays a 'disallowed host' error message when I try to access it from Heroku generated web address "XXX.herokuapp.com". "XXX.herokuapp.com" is only an allowed host when running production.py settings. Also, DEBUG = False in that particular setting file, so I suppose I shouldn't an error message detailed Thanks for any help! Here's my init.py file : from .base import * from .production import * try: from .local import * except: pass Here's my local.py file : from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['0.0.0.0', '127.0.0.1', ] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'XXX@gmail.com' #my gmail username EMAIL_HOST_PASSWORD = 'XXX' #my gmail password EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "Lucas <XXXX>" ADMINS = [('Lucas', … -
Getting error when trying to use Django ORM
I have a script which pull out every record from database, but I can't run it because I'm getting error. I have googled it, tried to change settings but probably I do something wrong. Eror: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. script def test(self): enter = Enter.objects.all() print(enter) test() -
Extracting data from the payload in Djnago Rest framework
I have a payload of data sent from the frontend. It is a post api call to create a product object and a variant object at the same time. But I am having difficulties in extracting the ids from the validated_data. The data sent is like this: name: Soap category[0]: 7 category[1]: 23 brand: 7 collection: 11 availability: in_stock warranty: no_warranty service: cash_on_delivery rating: 3 best_seller: true top_rated: true featured: true main_product_image: (binary) merchant: 2 variants[0][product_id]: fgfdg variants[0][price]: 127 variants[0][quantity]: 1 variants[0][color]: red variants[0][size]: M variants[0][variant_availability]: not_available variants[0][variant_image]: (binary) variants[1][product_id]: fgfdg variants[1][price]: 127 variants[1][quantity]: 1 variants[1][color]: red variants[1][size]: M variants[1][variant_availability]: not_available variants[1][variant_image]: (binary My view: class ProductAddAPIView(CreateAPIView): permission_classes = [IsAuthenticated] parser_classes = [MultipartJsonParser] serializer_class = AddProductSerializer My serializer: class AddProductSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(read_only=True) variants = VariantSerializer(many=True) slug = serializers.SlugField(read_only=True) class Meta: model = Product fields = ['id','merchant','featured', 'top_rated','category','brand','collection','sub_category', 'name','slug','description', 'main_product_image','best_seller','picture', 'rating','availability','warranty','services','variants'] #depth = 1 def create(self, validated_data): #user = self.context['request'].user picture_data = validated_data.get('picture') merchant = validated_data.get('merchant') featured = validated_data.get('featured') top_rated = validated_data.get('top_rated') brand = validated_data.get('brand') collection = validated_data.get('collection') sub_category = validated_data.get('sub_category') name = validated_data.get('name') description = validated_data.get('description') main_product_image = validated_data.get('main_product_image') best_seller = validated_data.get('best_seller') rating = validated_data.get('rating') availability = validated_data.get('availability') warranty = validated_data.get('warranty') services = validated_data.get('services') #variants_logic variants_data = validated_data.get('variants') #breakpoint() … -
How to fix this no attribute error in Django backend
Same technique I used in Product model and views and it's working fine Code for product serializer and views is #Serializers.py class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = '__all__' class ProductSerializer(serializers.ModelSerializer): reviews = serializers.SerializerMethodField(read_only=True) class Meta: model = Product fields = '__all__' def get_reviews(self, obj): reviews = obj.review_set.all() serializer = ReviewSerializer(reviews, many=True) return serializer.data #views.py @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) serializer = ProductSerializer(product, many=False) return Response(serializer.data) #and review sections is @api_view(['POST']) @permission_classes([IsAuthenticated]) def createProductReview(request, pk): user = request.user product = Product.objects.get(_id=pk) data = request.data # 1 - Review already exists alreadyExists = product.review_set.filter(user=user).exists() if alreadyExists: content = {'detail': 'Product already reviewed'} return Response(content, status=status.HTTP_400_BAD_REQUEST) # 2 - No Rating or 0 elif data['rating'] == 0: content = {'detail': 'Please select a rating'} return Response(content, status=status.HTTP_400_BAD_REQUEST) # 3 - Create review else: review = Review.objects.create( user=user, product=product, name=user.first_name, rating=data['rating'], comment=data['comment'], ) reviews = product.review_set.all() product.numReviews = len(reviews) total = 0 for i in reviews: total += i.rating product.rating = total / len(reviews) product.save() return Response('Review Added') And this is working fine . But When I use same in OurPanel Serializers and Reviews its throwing this erro \base\serializers.py", line 114, in get_reviews reviews = obj.review_set.all() AttributeError: 'OurPanel' object … -
Django version <= 1.6 metrics exporter for prometheus
I am looking for Django metric exporters, however, found ones below only support Django version >= 1.8 https://github.com/korfuri/django-prometheus https://github.com/prezi/django-exporter Any suggestions to find an exporter fix django 1.6? Or any workaround, for example, install exporter in prometheus server? -
DRF serializer: IntegrityError: FOREIGN KEY constraint failed
I want to create a simple CRUD application with DRF GenericViewSet using it's mixins for create, update, list ... and I run into the following error: IntegrityError: FOREIGN KEY constraint failed model: class Link(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE, null = True, blank = True) page = models.PositiveIntegerField("page", default = 2, choices = PAGE = [(1, 1), (2, 2)]) device = models.ForeignKey(Device, on_delete = models.CASCADE) ltype = models.ForeignKey(LinkType, on_delete = models.CASCADE, null = True, blank = True) class Device(models.Model): device_id = models.PositiveIntegerField(unique = True) serializer: class LinkSerializer(serializers.ModelSerializer): device_id = serializers.SerializerMethodField("get_device_id") def get_device_id(self, link): return link.device.device_id class Meta: model = Link fields = ["device", "page", "product", "device_id", "ltype"] and the ViewSet: class TestViewSet(RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, ListModelMixin, GenericViewSet): serializer_class = LinkSerializer def get_queryset(self): store = Store.objects.get(user = self.request.user) devices = Device.objects.filter(store = store) return Link.objects.filter(device__in = devices) def perform_create(self, serializer): dev = Device.objects.get(pk = self.request.POST["device"]) serializer.save(device_id = dev.device_id) -
Django: Extract time from datetime and convert into minutes
This is a quiz app where a quiz has a scheduled date and time as well as duration in minutes. The duration is to the nearest minute like 1, 2,10, 20. However, someone might be late to take the quiz and I want to extract the amount of time by which he is late. Like give him the right amount of time to complete based on his lateness I have the following code snippet which does not work: present_time = timezone.now().minute # the time he is taking the test in minutes scheduled_time = test.scheduled_date_time.strftime("%H:%M:%S") lateness = present_time - scheduled_time lateness_in_min = lateness.minute allocated_time = test.time - lateness_in_min //test.time is the duration of the quiz -
Django Rest Framework pass file path in URL
urlpatterns = [ path('file/<path>', files) ] Able to pass normal variables in url Eg. http://127.0.0.1:8000/file/logo.png But if i pass path Eg. http://127.0.0.1:8000/file/a/b/logo.png It's showing 404 error. How to do this. Thank you. -
Please suggest the best platform to learn the mommy model in Django
I am trying to learn Model Mommy in Django If anyone has thoughts or resources please share them with me. Thanks in advance -
How to use environment variables in views.py in Django?
I am using python-decouple 3.4 for setting up environment variables for my django application. My .env file is in the same directory as that of manage.py. Except for SECRET_KEY (in settings.py), loading other environment variables in either settings.py or views.py fails stating that they have not been defined. The other environment variables which give error will be used in views.py. If I try to define them in settings.py like:- from decouple import config FILE_PATH = config('file_path') and then use them in views.py, from django.conf.settings import FILE_PATH print(FILE_PATH) then also I get the same error. How can I define environment variable for my views.py specifically? -
Django saveing logged in logged in user as ForeignKey
I have model with a ForeignKey "log_written_by" and I want that to be the logged in user. How should i state that in my forms.py as a hiddenfield? class AssetLog(models.Model): # Relationships log_written_by = models.ForeignKey("auth.User", on_delete=models.SET_NULL, blank=True, null=True) asset_case = models.ForeignKey("asset_app.AssetCase", on_delete=models.CASCADE) # Fields date_time_log = models.DateTimeField() notes = models.TextField(max_length=1024) created = models.DateTimeField(auto_now_add=True, editable=False) class Meta: pass def __str__(self): return str(self.pk) def get_absolute_url(self): return reverse("asset_app_AssetLog_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_AssetLog_update", args=(self.pk,)) -
can django have react.js like behavior?
I am wondering whether in Django could be done for example a list and if you add something to the list on the ui side, the ui will update the list fast. Because in Django I have to reload the page every time I make a single change so this seems very slow from the user's experience. I am blindly trying to make it work using with tag and then change the variables declared. Or maybe changing the context will help to achieve this? If it works by changing context, how do I append something to a list? -
Translations troncated
I am working on Django and I saw my translations are troncated. I don't know why. For instance I have that code : {% blocktrans %}the water{% endblocktrans %} And when I look at the django.po I wrote : msgid "the water" msgstr "el agua" And I did that then : compilemessages And when I open my browser I just see "el" instead of "el agua". Do you know why I get that result ? Thank you very much ! -
How to convert python function to sql function to query data [closed]
I've stuck with a situation I don't want to union of all tables, Below functions queries multiple table one by one if exists return the record enter code here def detectContentType(contentId): qobject = Question.get_obj(contentId) if qobject == None: qobject = MultipleChoiceQuestion.get_obj(contentId) if qobject == None: qobject = MultipartQuestion.get_obj(contentId) if qobject == None: qobject = PointsToRemember.get_obj(contentId) if qobject == None: qobject = FlowChart.get_obj(contentId) return qobject -
get auth token using dj-rest-auth when user logged in
Previously I was using django-rest-auth package and I was getting the auth token when user log in in response response.data.key and this auth token or key was working fine with the api calls as authentication auth Previously for django-rest-auth: "/rest-auth/login/" was getting the response.data.key as auth token and that was working I have stored in the cookie for later use .get("/rest-auth/user/", { headers: { "Content-Type": "application/json", Authorization: "Token " + response.data.key + "", }, }) It was working to get info on user and also was working when used in other api calls by setting it in Authorization: "Token " + response.data.key + "" But now, I'm using dj-rest-auth package instead of django-rest-auth and shifted my urls to /dj-rest-auth/login and I'm not getting any key or auth token that I can use for authorization in header. .get("/dj-rest-auth/user/", { headers: { "Content-Type": "application/json", Authorization: "Token " + response.data.? + "", }, }) It's not working because now I'm getting access_token , refresh_token and user info. I tried to use access_token and refresh_token for authorization in header but it's not working because I'm not getting key or auth token in response when user log in Note: django-rest-auth is no more maintained and … -
Django got an unexpected keyword argument 'repearpass' [closed]
I am trying to create a registration page which had name, email, password and repeatpassword what is wrong Exception Type: 'TypeError; Exception Value: Register() got an unexpected keyword argument 'repeatpass' Exception Location: C:\Users\ANT-PC\anaconda3\lib\site-packages\django\db\models\base.py, line 503, in init veiws.py def index(request): if request.method=="POST": name=request.POST.get("name") email=request.POST.get("email") password=request.POST.get("password") repeatpass=request.POST.get("repeatpass") Register.objects.create(name=name,email=email,password=password,repeatpass=repeatpass) return redirect('login') else: return render(request,"index.html") def login(request): if request.method == "POST": userid = request.POST.get("userid") pwd = request.POST.get("pwd") Register.objects.filter(userid=userid, pwd=pwd) return redirect('home') else: return render(request, 'login.html') def logout(request): return redirect('login') Models.py class Register(models.Model): name = models.CharField(db_column='Name', max_length=20, blank=True, null=True) # Field name made lowercase. email = models.CharField(db_column='Email', max_length=250, blank=True, null=True) # Field name made lowercase. password = models.CharField(db_column='Password', max_length=30, blank=True, null=True) # Field name made lowercase. repeatpaas = models.CharField(db_column='RepeatPaas', max_length=30, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'register' my url.py urlpatterns = [ path('login/',views.login,name='login'), path('logout/',views.logout,name='logout'), path('register/',views.index,name='register'), path('admin/', admin.site.urls), ] my registration page {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Sign Up </title> <!-- Font Icon --> <link rel="stylesheet" href="fonts/material-icon/css/material-design-iconic-font.min.css"> <!-- Main css --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <form method="POST"> {% csrf_token %} <div class="main"> <!-- Sign up form --> <section class="signup"> <div … -
Annotate in django object using function
I have two models Parent, Child class Parent(models.Model): id = models.IntegerField(...) class Child(models.Model) id = models.IntegerField(...) parent = models.ForeignKey(Parent, ...) wanted = models.CharField(default="yes") I have a queryset parents = Parent.objects.all() I want to annotate a char field to parents queryset which is based on Child model get_status(obj): # complex function which returns string based on child onjects children = Child.objects.filter(parent_id = obj.id) if children.count() == 1: return 'some' if children.count() == 2: return 'thing' I want something like this, How to send object to get_status() function. queryset.annotate(status = Value(get_status(), output_field=CharField())) -
Django: Bootstrap 3 modal darkens when being clicked
This is a quiz app where several quiz can be added to a particular topic. However, when I click on the button to start the quiz, the modal asking for confirmation pops up but in a darkened way. It does not allow me to select any of the option. What is the issue here? Here is my code snippet: {% if test %} {% for test, validity in test %} //validity is the duration for which the test remains valid <div class="modal fade" id="testStartModal" tabindex="-1" role="dialog" aria- labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="exampleModalLabel"><strong>Start?</strong</h4> <button type="button" class="close" data-dismiss="modal" aria label="Close"><span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" id="modal-body-confirm"></div> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-lg" data dismiss="modal">No</button> <button type="button" id="start_button" class="btn btn-success btn-lg" {% if test.scheduled_date_time > time %} disabled {% endif %}>Yes</button> </div> </div> </div> </div> <div style="padding:10px;"> <!-- Button trigger modal --> <button type="button" class="btn btn-info modal-button" data-pk="{{test.pk}}" data-test="{{test.name}}" data-questions="{{test.number_of_questions}}" data-difficulty="{{test.difficulty}}" data-time="{{test.time}}" data-schedule-datetime="{{test.scheduled_date_time}}" data-pass="{{test.threshold}}" data-toggle="modal" data-target="#testStartModal" {% if validity < time %} disabled>{{ test.name }} Expired </button> {% else %}> Take {{ test.name }}</button> {% endif %} </div> {% endfor %} {% endif %} -
django How to get kwargs in decorator from view
This is my view class SectorCreateView(GenericAPIView): permission_classes = [IsAuthenticated] serializer_class = SectorSerializer @method_decorator(permission_required('view_sector')) def get(self, request, *args, **kwargs): print('kwargs in view',kwargs) sector = Sector.objects.all() serializer = self.serializer_class(sector, many=True) return Response(serializer.data, status=status.HTTP_200_OK) I am using permission required decorator to check permissions of user. in **kwargs there is slug with name of company. On basis of which i am checking permissions of that specific company. I can see kwargs in my view but not in my decorator here is the code of my decorator def permission_required(perm, login_url=None, raise_exception=False): def check_perms(user, **kwargs): print('kwargs in decorator',kwargs) partof_objs = PartOf.objects.filter(user=user) for i in partof_objs: role = Role.objects.filter(pk = i.role.pk) for permission in role: li = permission.permissions.values_list('code', flat=True) has_perm = perm in li if has_perm: print('Granted') return True else: print('Denied') raise PermissionDenied return False return user_passes_test(check_perms, login_url=login_url) -
How can I show rating in product comments
My models: class Comment(models.Model): product = models.ForeignKey(Product ,on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User ,on_delete=models.CASCADE, max_length=80, related_name='comments_user') body = models.TextField() created_on = jmodels.jDateField(auto_now_add=True) created_on_time = models.TimeField(auto_now_add=True,null=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.user) class Rating(models.Model): product = models.ForeignKey(Product ,on_delete=models.CASCADE) user = models.ForeignKey(User ,on_delete=models.CASCADE) score = models.IntegerField(default=0, validators=[ MaxValueValidator(5), MinValueValidator(0), ] ) def __str__(self): return 'rate {} by {} for {}'.format(self.score, self.user, self.product) In product single page, I have comments part that I want show user rating if that user put comment in next of username and comment date.