Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django run scheduled jobs hourly
In my project I have to load data in database hourly .I tried celery and cron but found all the stuff very complicated and always createes some issue.I use pycharm in windows. I am new to django and just need a simple solution to run the following command hourly. This loads data in dabase. "python manage.py fetchfiles" management/commands/fetchfiles from django.core.management.base import BaseCommand, CommandError from dashboard.models import airdata as tdata import requests import json class Command(BaseCommand): help = 'Fetches api data' """def add_arguments(self, parser): none""" def handle(self, *args, **options): #for a in range(0,1578,10): a = True offno = 0 lst2=[] dict1={} while a == True: api_key = "579b464db66ec23bdd000001cdd3946e44ce4aad7209ff7b23ac571b" url = "https://api.data.gov.in/resource/3b01bcb8-0b14-4abf-b6f2-c1bfd384ba69?api-key={}&format=json&offset={}&limit=10".format(api_key,offno) response = requests.get(url) data = response.text a1=json.loads(data) for ele in a1['records']: if ele['pollutant_min'] == 'NA': dict1['pol_min'] = 0 else: dict1['pol_min'] = int(ele['pollutant_min']) if ele['pollutant_max'] == 'NA': dict1['pol_max'] = 0 else: dict1['pol_max'] = int(ele['pollutant_max']) if ele['pollutant_avg'] == 'NA': dict1['pol_avg'] = 0 else: dict1['pol_avg'] = int(ele['pollutant_avg']) dict1['state'] = ele['state'] dict1['city'] = ele['city'] dict1['station'] = ele['station'] dict1['time_vector'] = ele['last_update'] lst2.append(dict1.copy()) if a1["count"] < 10: a= False offno += 10 airx = json.dumps(lst2, indent=1) tdata.objects.bulk_create([tdata(**vals) for vals in lst2]) return airx -
How to set the variables from .env file when using Django and Gitlab CI/CD?
I'm trying to run the tests of my Django app in Gitlab CI/CD. The process fails every time with an error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.. I assume this is because I have not my .env file available in the repository and that file contains for example the SECRET_KEY -variable which is then used in the settings.py like this: SECRET_KEY = os.getenv('SECRET_KEY'). So what would be the proper way to set these variables so my tests would pass? -
What to add in permission_classes for allowing to view the api by only specific group - django
To make only admin access the API, used - permission_classes = (IsAdminUser, ) But to access the specific group is there anything needed to add to permission_classes, or such a thing is completely not possible with permission_classes. If so how can I proceed? -
XML http request error on a login request from flutter -
import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:bloc_login/model/api_model.dart'; final _base = "http://localhost:8000/"; final _tokenEndpoint = "rest/v1/pwa/token/login/"; final _tokenURL = _base + _tokenEndpoint; Future<Token> getToken(UserLogin userLogin) async { print(_tokenURL); print(userLogin.toDatabaseJson()); final http.Response response = await http.post( _tokenURL, headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale", "Access-Control-Allow-Methods": "POST, GET, OPTIONS" }, body: jsonEncode(userLogin.toDatabaseJson()), ); if (response.statusCode == 200) { return Token.fromJson(json.decode(response.body)); } else { print(json.decode(response.body).toString()); throw Exception(json.decode(response.body)); } } Seeing XML http request error on a Login request, where as http://localhost:8000/rest/v1/pwa/token/login/ {username: customer1, password: randompass} are obtained but request hit as [18/Jun/2021 12:27:22] "OPTIONS /rest/v1/pwa/token/login/ HTTP/1.1" 200 412 on backend The same API tested from POSTMAN hits as a POST request -
Azure DataLake Query Expression | Error Processing Query
I got some data in blob storage under data lake in CSV, data format is mail,usertype,license Data is huge, so I'm implementing pagination in Django to render it, I don't want my compute unit to fetch all half a mil rows every time which makes the website slow. To improve pagination. Right now when I am querying data based on rows with limit then I'm getting an error Syntax error! RequestId:59f9d9e5-601e-0015-4f0f-64fd1d000000 Time:2021-06-18T06:56:56.9344470Z ErrorCode:ErrorProcessingQueryExpression Error:None Here's my query to pick data of the 5th to 10th row for a test. query_expression = "SELECT * from DataLakeStorage limit 5,10" -
google maps api key for django
hi every one i hope you be okay, so i'm need to display and use google map and places api in my django project and i'm using the django-google-maps package and now i need to get an googld API key i'm got one from https://console.cloud.google.com/ but there is this noise water mark text for developers purposes only after setting the django-google-maps options and google API key on my admin panel. and each time i enter a place namd i'll get the requiest denied error can any one explain to me how to get a correct google API key and or even a better way to display google maps in django project? i'll be so thankful for your help🙇♂️🌷 -
How to make custom decorator with multiple arguments?
Here I am making a custom decorator with some kwargs parameter but the decorator is not working. Error: TypeError: my_decorator() takes 1 positional argument but 2 were given Code def my_decorator(title, **data): def _method_wrapper(view_method): def _arguments_wrapper(request, *args, **kwargs) : obj = Model.objects.get(title=title) if obj.relatedmodel_set.filter(**data).exists(): return view_method(request, *args, **kwargs) raise PermissionDenied return _arguments_wrapper return _method_wrapper #view @my_decorator('title', {'is_manager':True}) def my_view(request, id): -
How to use pre_create_historical_record signal in django-simple-history?
I am using django-simple-history to save history of data. I want to save an extra field value to each history model before it is saved. I found the reference code in documentation mentioned above but cant use it. Please help. from django.dispatch import receiver from simple_history.signals import ( pre_create_historical_record, post_create_historical_record ) @receiver(pre_create_historical_record) def pre_create_historical_record_callback(sender, **kwargs): print("Sent before saving historical record") @receiver(post_create_historical_record) def post_create_historical_record_callback(sender, **kwargs): print("Sent after saving historical record")