Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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") -
Wagtail RoutablePageMixin fail to route page when DEBUG=True
I am using Wagtail/CodeRedCMS to set the website. RoutablePageMixin is inherited in my model (named WriteLandingPage). And "route" is used to redirect request to certain custom view. my code is below. model.py class WriteLandingPage(RoutablePageMixin, CoderedArticlePage): class Meta: verbose_name = 'Write Landing Page' template = 'coderedcms/pages/write_landing_page.html' @route('') def submit(self, request): article_index = ArticleIndexPage.objects.all()[0] from .views import submit_topic return submit_topic(request, article_index) views.py def submit_topic(request, article_index): print(request.user.is_authenticated) form = EditForm(data=request.POST or None, label_suffix='') if request.method == 'POST' and form.is_valid(): submit_page = form.save(commit=False) submit_page.slug = slugify(submit_page.title) topic = article_index.add_child(instance=submit_page) if topic: topic.unpublish() topic.save_revision(submitted_for_moderation=True) return render(request, 'coderedcms/pages/submit_topic_success.html', {"user": request.user}) context = { 'form': form, 'edit_index': article_index, } return render(request, 'coderedcms/pages/submit_topic.html', context) forms.py class EditForm(ModelForm): class Meta: model = ArticlePage fields = ['draft', 'title'] Everything works just prefect when DEBUG=True. But It fails to read page when I turns DEBUG to False. The following messages shows on backend console. [18/Jun/2021 01:41:04] "GET /write-landing-page/ HTTP/1.1" 500 940 Am I missing any setting? -
docker cmd: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
I have a Django project and I want to create a docker image for it. FROM python:3 # copy source and install dependencies ENV PYTHONUNBUFFERED=1 WORKDIR DockerHome COPY requirements.txt /DockerHome/ RUN pip install -r requirements.txt RUN pip install psycopg2 COPY . /DockerHome/ RUN python manage.py makemigrations RUN python manage.py makemigrations bill RUN python manage.py migrate CMD python manage.py grpcrunserver 0.0.0.0:5051 The RUN commands use psycopg2 successfully. for example python manage.py makemigrations bill uses psycopg2 too, but when I run a container from this image, I get this error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' what is the problem with the CMD function that cannot import psycopg2? -
Uncaught RangeError: Maximum call stack size exceeded at Dt on posting
I am using Django and trying to post a form through ajax. $(document).on('submit', '#create-assignment', function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '/teacher/exam/create/', data:{ title: $('#assignment-form-title-input').val(), time: $('#assignment-form-time-input'), description: $('#assignment-form-description-input'), date: today, file: files[0], csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() } }); $('#create-assignment').trigger("reset"); }); On trying to post it I get an error - Uncaught RangeError: Maximum call stack size exceeded at Dt I tried to search for it but couldn't understand anything. For the array files, $('#assignment-form-file').change(function(event) { files = event.target.files; reader = new FileReader(); reader.onload = function(){ reader.readAsDataURL(files[0]); }; }); and var today = new Date().toISOString().slice(0, 10) And the html is like this - : <form id="create-assignment"> {% csrf_token %} <div class="title-time-wrapper"> <input type="text" placeholder="Enter Title" class="assignment-form-input" id="assignment-form-title-input" name="assignment-title"> <input type="text" placeholder="Enter Time in minutes" class="assignment-form-input" id="assignment-form-time-input" name="assignment-time"> </div> <textarea placeholder="Enter Description" class="assignment-form-input" id="assignment-form-description-input" name="assignment-description" rows="5"></textarea> <div class="input-file-wrapper"> <input type="file" name="assignment-file" id="assignment-form-file"> </div> <input type="submit" value="Save" id="assignment-form-submit"> </form> If anyone can tell the mistake and explain a bit about the same it will be really helpful. -
About (sender, instance, created, **kwargs) parametert. How it's assigned
from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) I'm new to python in general and while I was going thru a tutorial it teaches about signals. I've been trying to figured how this function works, as in how (sender, instance, created, **kwargs) is assigned to? I can't seem to wrap my head around it. So if a post is saved it triggers this vvv receiver(post_save, sender=User) in this case User gets assigned to sender. since sender=User . easy. Now, as for the second parameter, instance , it shows in the very last line of the function. user= instance. from my understanding of function, and parameter, should it all be assigned WHEN the function is CALLED? in this case when the receiver signal is triggered and create_profile is called, instance and created has no value yet.... correct? As for 'created', why does it have to be a parameter? since it's checking if CREATED. Does (instance, created) have an in built....functionality in it? since from what i get those three are placeholders and it needds to be assigned a value in order to do … -
Disable field in Django forms do not fetch the original value
I am trying to disable the field input for update from my view def get_update_form(self, obj): form = super().get_update_form(obj) form.fields["is_active"].disabled = True return form But when I update, it doesn't retain the original value of the active status of the object to be updated. I also tried form.fields["is_active"].widget.attrs['disabled'] = 'disabled' but it still doesn't retain the value. Is there any way I can disable it but upon update, it will retain the original value of this specific field? Thanks! -
Declare Model Value in Django [duplicate]
I am pretty new to Django. I would like to know how to declare the value of a models field. For example, if was making a model for pictures frames, I could choose from the selection of small, medium, or large. Then, it would automatically populate the values for length and width to be 5 and 7 for small, 8 and 10 for medium and so on. I’m assuming you still have to make the field length and width be integer fields. But I don’t know how to set the value after that. -
How can I undeploy a heroku app with Django?
I'm having issues with parts of my website (made with Django) that I create after deploying disappearing because Heroku is very unhelpful with storage. Is there a way to undeploy and redeploy a site on Heroku? I think this would fix my issue. -
pytest django load database data from yaml file
I have dumped data from my development environment using dumpdata django command into a yaml file. I am using pytest framework and need to achieve the following scenario: During start of a pytest session -> that is when I run pytest from command line, the data from yaml file should be loaded into my test database Is there any plugin or hook which I can use to achieve the above ? I am using python 3.8, pytest 6.2.4, pytest-django 4.40, Django 3.0.5 -
Django url dynamic link
im using vuejs in django and i have this code <form method="POST" :action="edit ? '{% url 'productoEdit' pk=request.path|slice:'19:21' %}' : '{% url 'productoCrud' %}'" enctype="multipart/form-data"> if the variabble edit is true action will be {% url 'productoEdit' pk=request.path|slice:'19:21' %} if is false {% url 'productoCrud' %} the problem is that django gives me an error: Reverse for 'productoEdit' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['user/productoEdit$', 'user/productoEdit/(?P<pk>[^/]+)$'] this is my urls.py path('productoEdit/<str:pk>', views.productoEdit, name="productoEdit"), path('productoEdit', views.productoEdit, name="productoEdit") as you can see the path productoEdit has 2 views, one with parameters and other without parameters. this is my productoEdit in views.py def productoEdit(request, pk=''): producto = Producto.objects.get(id=pk) form = CreateProductForm(instance=producto) if request.method == 'POST': form = CreateProductForm(request.POST, instance=producto) if form.is_valid(): form.save() redirect('productoCrud') return render(request, 'productoCrud.html', {'form': form}) the problem ocurred when request.path is an empty string pk=''. i tried using a ternay operator like this: pk=request.path|slice:'19:21' ? request.path|slice:'19:21' : None or pk=request.path|slice:'19:21'|yesno:'request.path|slice:'19:21',None' Django doesnt like my solutions xD, how can i resolve this problem?? thx so much for your help -
Confusion about migration files on Official Django document
On Migration Files part of Django Official Document, it reads: Paragraph 1: The operations are the key; they are a set of declarative instructions which tell Django what schema changes need to be made. Django scans them and builds an in-memory representation of all of the schema changes to all apps, and uses this to generate the SQL which makes the schema changes. Paragraph 2: That in-memory structure is also used to work out what the differences are between your models and the current state of your migrations; Django runs through all the changes, in order, on an in-memory set of models to come up with the state of your models last time you ran makemigrations. It then uses these models to compare against the ones in your models.py files to work out what you have changed Q1: In differences are between your models and the current state of your migrations, what exactly your models and current states of your migrations refer to? which one refers to the Database Version before this new migration file is applied and which one refers to the Database Version after new migration file is applied? Q2: That in-memory structure is also used to work …