Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django polymorphic and GenericRelation field. How get all filtered objects?
models.py class File(models.Model):--> content_type_id=4 is_recorded = models.BooleanField(verbose_name=_('is recorded'), default=False) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') class Parent(PolymorphicModel): --> content_type_id=1 files = GenericRelation(File) field0 = models.CharField(verbose_name=_('field0'), max_length=255, blank=True, null=True) class Child1(Parent): --> content_type_id=2 field1 = models.CharField(verbose_name=_('field1'), max_length=255, blank=True, null=True) class Child2(Parent): --> content_type_id=3 field2 = models.CharField(verbose_name=_('field2'), max_length=255, blank=True, null=True) Run query 1 Parent.object.all() [ <Child1: id 1>, <Child2: id 2>] SQL 2 SELECT `parent`.`id`, `parent`.`polymorphic_ctype_id`, `parent`.`content_type_id`, `parent`.`object_id`, `parent`.`fiedl0`, FROM `events_event` It's good; Run query 2 Child2.object.filter(files__is_recorded=True) [<Child2: id 1>] SQL 2 SELECT DISTINCT `parent`.`id`, `parent`.`polymorphic_ctype_id`, `parent`.`content_type_id`, `parent`.`object_id`, `child2`.`parent_ptr_id`, `child2`.`field1`, FROM `child2` INNER JOIN `parent` ON (`child2`.`parent_ptr_id` = `parent`.`id`) INNER JOIN `parent` T3 ON (`child2`.`parent_ptr_id` = T3.`object_id` AND (T3.`content_type_id` = 2)) INNER JOIN `file` ON (T3.`id` = `file`.`id`) It's good; Run query 3 Parent.object.filter(files__is_recorded=True) [] SQL 3 SELECT DISTINCT `parent`.`id`, `parent`.`polymorphic_ctype_id`, `parent`.`content_type_id`, `parent`.`object_id`, FROM `parent` INNER JOIN `file` ON (`parent`.`id` = `file`.`object_id` AND (`file`.`content_type_id` = 12)) It's bad. How do i get all the subobjects (Child1, Child2), who have files__is_recorded=True (Without adding one more GenericForeignKey in File model with link to parent model)? -
How to display certain fields in a modelform according to roles?
I created a modelform corresponding to a certain model. What do I need to do if I want to hide certain fields when user logs in but display them when a superuser sees the form. -
How to add an extra field in Django model form only when the object exists?
Lets say I have a model form like this: class PersonForm(forms.ModelForm): full_name = forms.CharField(max_length=255) class Meta: model = Person fields = '__all__' The full_name field is not a database field. I want to have the field full_name appear only if the object exists, ie, not on add, and the set the initial value to instance.first_name + ' ' + instance.last_name. On add, because the first_name and last_name don't exist yet, the field full_name is simply not shown. How can I do this? Moreover, will this extra field affect my save process? -
Instance of a new object still uses the value which was in the previously used object
I am developing a web application using Python and Django. I got a problem while creating a new object. I created the object and stores the data in db and returned the response to the client, but the next request when i try to create a object i found some of the variables are already defined with the values which were in the last request. Here is the code: cart_object = json.loads(request.POST.get("cart")) cart: CartModel = CartModel() cart.cart_id = IntHelper.string_to_int(cart_object.get("cart_id"), None) cart.entity_id = IntHelper.string_to_int(cart_object.get("entity_id"), None) cart.user_id = IntHelper.string_to_int(cart_object.get("user_id"), None) # cart.cart_item = [] list_items = cart_object.get("cart_item") for i in range(len(list_items)): cart_item: CartItemModel = CartItemModel() cart_item.cart_id = IntHelper.string_to_int(cart.cart_id, None) cart_item.user_id = IntHelper.string_to_int(cart.user_id, None) cart_item.category_id = IntHelper.string_to_int(list_items[i].get("category_id"), None) cart_item.quantity = FloatHelper.string_to_float(list_items[i].get("quantity"), None) cart_item.seller_bid_price = FloatHelper.string_to_float(list_items[i].get("seller_bid_price"), None) cart_item.seller_gst_percentage = FloatHelper.string_to_float(list_items[i].get("seller_gst_percentage"), None) cart_item.files = list_items[i].get("files") cart.cart_item.append(cart_item) cart_service: CartService = CartService() cart_object = cart_service.add(cart) return self.send_response(cart_object) Here everytime i create CartModel object, it has list of CartItemModel. In the 2nd call to this method, after i create the CartModel object. All other fields are empty and the list of CartItemModel has the value as the in the previoulsly created object class CartModel: def init(self, cart_id=None, entity_id=None, user_id=None, cart_date=None, status=None, cart_item=[]): self.cart_id = cart_id self.entity_id = entity_id … -
Pagination: Filtering Filters
We have an E-Commerce Platform that has a "product catalog" page with 1000's of results. This catalog is paginated (offset pagination). There are filters which, when activated, filter the results. Our problem is that our filters are not limited to the result set, and are therefore nonsensical. Example: Result Set: Blue Car Red Car Blue Book Yellow Book Filters: Colors: [Blue, Red] Items: [Car, Book] Companies like Amazon, etc. limit the filters shown, so when someone filters on "Book", the only colors available are [Blue, Yellow]. My question is: how is it possible to filter the filters unless the entire queryset is evaluated? And, if the entire queryset is evaluated, why do companies like Amazon use pagination? Note: My team is using Django with DRF and GraphQl backends, but this should not make a difference. -
images does not appear in html, it is apearing like it is broken
Notice: when i go to [http://127.0.0.1:8000/media/images/download.jpeg] it takes me to the home page while the url is [http://127.0.0.1:8000/media/images/download.jpeg]. images not apearing in html, se the code down there, please tell me what is the problem. models.py from django.db import models class jop(models.Model): image = models.ImageField(upload_to='images/') summary = models.CharField(max_length=200) views.py from django.shortcuts import render from .models import jop Create your views here. def home(request): jops = jop.objects return render(request, 'jops/home.html', {'jops':jops},) home.html <div class="album py-5 bg-light"> <div class="container"> <div class="row"> {% for jop in jops.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img src="{{jop.image.url}}"/> <p class="card-text">{{ jop.summary }}</p> </div> </div> </div> {% endfor %} </div> </div> urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static import jops.views urlpatterns = [ url(r'^admin/', admin.site.urls), url('', jops.views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
How do I fix these errors?
I have an sqlite3 databased django app. I was trying to use djongo to switch to MongoDB Atlas. But I don't know how to fix these errors I installed djongo DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'test', 'HOST': 'mongodb+srv://<username>:<password>@cluster0-bs91f.mongodb.net/test?ssl=true&ssl_cert_reqs=CERT_NONE&retryWrites=true&w=majority', 'USERNAME': '<username>', 'PASSWORD': '<password>', } } Thats the only thing I changed in settings.py File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymongo/network.py", line 158, in command parse_write_concern_error=parse_write_concern_error) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pymongo/helpers.py", line 155, in _check_command_response raise OperationFailure(msg % errmsg, code, response) I keep getting these errors. I don't know how to fix them -
how to use mod_wsgi for hosting multiple django projects under single domain?
I have multiple django projects and i want to host them under same domain eg: example.com/one example.com/two I have searched for various solutions and found the below given link which helped me alot. Is it possible to host multiple django projects under the same domain? From the above reading , I get to know that I need mod_wsgi for this but I am confused that where to install this mod_wsgi - Do i need to install under every project folder (seperate for every myenv) or it should be installed only once . Please help me in how and where to install this mod_wsgi and finally how to host multiple projects under same domain name. -
Django - how i get instance from another function
I have two functions in views.py and I want when I submit first function another function to get instance from previous submitted function. How can I do that? -
Django: How to add input elements to form as per input value
I have a Django form coming from the below model: class Ledger1(models.Model): ledger_name = models.CharField(max_length=32) group1_name = models.ForeignKey(Group1,on_delete=models.CASCADE,null=True,related_name='ledgergroups') taxes = ( ('GST','GST'), ('Others','Others'), ) tax_type = models.CharField(max_length=100,choices=taxes,default='GST',blank=True) I want to create a form in such a way that the tax_type field will be hidden in the front-end and will only be visible if the User choses tax from the ForeignKey field group1_name. The tax object is auto-created through a signal. Not a pro in ajax,So facing some difficulties in solving the issue.. Any solution will be helpful in my learning process. Thank you -
Django Running Particular Test
In My Project more than one test file and if i run python manage.py tests It takes huge time to complete the test and i don't want this way. I want only run particular file of test like i have test project/todo/tests/test_todo.py project/accounts/tests/test_signup.py project/todo/tests/test_archive.py and lots more like above these: Now i want to run only project/todo/tests/test_todo.py How can i do it? -
Django admin : How to call an action on a click of custom button?
I have a django admin view displaying a list of orders. I have added a custom button, which when clicked should perform a certain action. So I have a function defined in my services.py file as : def penalty(order): #Do something So, how should I call this function when Penalty is clicked. I can create a view, but how to call it? -
Migrating to Django rest framework
Currently I am using node as backend and looking forward to shift my project to django-rest-framework. In node I used firebase-auth and MySQL and have a table called FIREBASE_USERS with email and firebase_uid fields. I was thinking of building my own custom auth for drf but can't figure out on using my FIREBASE_USERS table instead of django Users model. I read that django provides settings.AUTH_USER_MODEL to set your own custom model but the documentation uses AbstractUser class to create that and I don't want to mess with my tables since the tables are used in other projects too. Any suggestions would be appreciated. -
Django annotate add interval to date
I am using postgres database with Django 2.2. I need to combine date and time field in model and add an interval of one day in it. I have done first part like this. Model.objects.annotate( end_dt=models.ExpressionWrapper( models.F('date') + models.F('end'), output_field=models.DateTimeField() ) ) Now I have to add 1 day to end_dt. I have done this with plain sql like this. SELECT "db_shift"."id", (("db_shift"."date" + "db_shift"."end") + INTERVAL '1 day') AS "end_dt" FROM "db_shift"; How can I achieve this using django ORM? -
how to solve string indices must be integers in django while receiving data from some other application
I am sending data from one application to other application and I would like to receive the data and I need to save in database This is i am receiving data data recived from api {'locations': [<City: Banglore>], 'send_application_email_to': [<Employee: thirumala reddy>], 'category': <JobCategory: Sales>, 'role': <Role: Sales Manager>, 'job_description': '<p>hello hellow hellow dude</p>', 'min_experience_in_year': 1, 'max_experience_in_year': 2, 'min_salary': Decimal('3.00'), 'max_salary': Decimal('3.00'), 'number_of_open_positions': 3, 'jobcode': 381969, 'posted_by': <SimpleLazyObject: <User: thiru@gmail.com>>} type of data recived from api <class 'str'> Internal Server Error: /jobposting_api/Traceback (most recent call last): File "/home/.virtualenvs/source/venv/career_new/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/.virtualenvs/source/venv/career_new/lib/python3.7/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/.virtualenvs/source/venv/career_new/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)File "/home/.virtualenvs/source/venv/career_new/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/source/career_new/resume/views.py", line 276, in jobpostingapi jobcode = data_recieved['jobcode'] @csrf_exempt def job(request): data_recieved = request.POST.get('validated_data') print("data recived from api",data_recieved) print("type of data recived from api",type(data_recieved)) jobcode = data_recieved['jobcode'] print("jobcode",jobcode) max_salary = float(data_recieved['max_salary']) min_salary = float(data_recieved['min_salary']) job_description = data_recieved['job_description'] role = data_recieved['role'] TypeError: string indices must be integers -
Fields for password1, password2 show up(at registration page) even after using "exclude" variable in Meta class of UserRegistrationForm in forms.py
At the registration page of a Django web app, I want to just ask for desired username and the email address and the system will email a randomly generated password to the user's given id. What should I do with this? I am using django 2.2.2 & python 3.7.3. I am using crispy_forms to render the forms. Relevant django forms documentation here. I have already used the "exclude" variable in the Meta class of my UserRegisterForm class. See code for exactly what I have done In forms.py file: class UserRegisterForm(UserCreationForm): """ Inheriting the UserCreationForm class to add some additional fields in the registration form because the #s of fields in the UserCreationForm class has less fields than required. We add email field in this extended class. """ email = forms.EmailField() class Meta: model = User fields = ("username", "email") exclude = ("password1", "password2") My register.html template file: {% extends "blog/base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend> Join here! </legend> {{ form|crispy }} </fieldset> <div> <button>Sign up!</button> </div> </form> <small class="text-muted"> Already have an account? Sign in <a href="{% url "login" %}" class="ml-2">here</a>. </small> … -
Convert file located in relative path into a Django File object
I have a file located at below relative path in my source code: docs/Shootsta_Videographer_critical_info.pdf I want to convert this file into a Django File object. Please help. -
Restricting whole django app to only superuser
I am not using django built-in admin panel for the admin page but i am trying to add functionality like django-admin.I want to restrict normal users to the admin page for this i tried if not request.user.is_superuser and which is fine.It does the job pretty well but in the app there can be hundreds of functions and i have to add this line to every function and i think this is not best idea to do.So is there any idea or solution so that i can give access the whole admin page to only superuser without adding if not request.user.is_superuser in every function? views.py def a(request): if not request.user.is_superuser: return redirect('login') .......... def b(request): if not request.user.is_superuser: return redirect('login') ............. def c(request): if not request.user.is_superuser: return redirect('login') ........... def d(request): if not request.user.is_superuser: return redirect('login') .... -
How to make sure an extra field shows up in my Django admin form?
I have the following code: class MyModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args, **kwargs) self.fields['extra_field'] = forms.CharField( label=_('Extra field'), max_length=255 ) class Meta: model = MyModel fields = '__all__' class MyModelInline(admin.StackedInline): extra = 0 model = MyModel form = MyModelForm The extra field I added does not show up in my form. Please note, the extra field is not a field present in the database. It is just something specifically for this form. How can I make sure that the extra field shows up in my form, along with all the other database fields automatically? I don't want a way where I have to manually mention every field in the self.fields attribute. Thanks for any help. -
How to fix this Django error. I couldn't reslove this error and literally worked for more than 4 hours on this issue
Error showing here please help me to resolve this error. -
Uncaught ReferenceError: jQuery is not defined at getCookie function for django csrf get token code
I got the error "Uncaught ReferenceError: jQuery is not defined at getCookie " for function getcookie defined in js. I have used this function for getting csrf token to pass to django views. Here is my html script declaration code:- <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <link rel="icon" href="../../static/images/logo.png" type="image/gif" sizes="16x16"> <!-- CSS --> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" href="../static/stylesheets/jquery-ui.css"> <link rel="stylesheet" media="screen" href="../static/stylesheets/spectrum.css" /> <link rel="stylesheet" href="../../static/stylesheets/bootstrap-select.min.css"> <link rel="stylesheet" media="screen" href="../../static/stylesheets/reconvert.mini.css" /> <link rel="stylesheet" href="../../static/stylesheets/main.css"> <!-- Js --> <script type="text/javascript" src="../../static/admin/js/jquery-2.1.1.min.js"></script> <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> --> <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <script src="../../static/admin/js/bootstrap.js"></script> <script src="../../static/admin/js/spectrum.js"></script> <script src="../../static/admin/js/bootstrap-select.min.js"></script> <script src="../../static/admin/js/nprogress.js"></script> <script src="https://unpkg.com/tippy.js@4"></script> </head> <body> <form action="/client/" method="post" id="post-form" class="container tab-pane"> {% csrf_token %} <div class="form-group"> <label for="phone_number">Whatsapp Phone Number</label> <input type="text" class="form-control" name="phone_number" id="phone_number" /> <br> <label for="chat_butn_text">Chat Button Text</label> <input type="text" class="form-control" name="chat_butn_text" id="chat_butn_text"/><br> </div> <br> <button type="submit" class="btn btn-primary btn-block">Submit</button> </form> </body> Here is my js code:- function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == … -
Django Cryptographic "signing.loads(value)" giving None with same SECRET_KEY
I have 2 Django Project with same SECRET_KEY. Using First project we are encrypting some important data using 'signing.dumps(value)' and sending via rest to another django project. Now I am trying to decrypt using signing.loads(value) its giving None why? -
java.io.FileNotFoundException: C:\Program Files x86\Python37-32\lib\multiprocessing\spawn.py
On a windows machine, working on a web app using DJango framework, and I'm completely new to Python as well. Through eclipse, I had setup DJango environment, and trying to get inside the method of certain class by pressing F3, as I used to do in case of Java. But Eclipse is showing following error after pressing F3 on some methods or sometimes on some classes also... Just asking whether I have missed some plug-in or dependency! Or what's wrong happening here, If it would not work properly then It would really become difficult for me to navigate between classes and methods. If more details are required about those classes and methods, please let me know. Thank you -
How to provide data from one input field to two input field of Django generated form?
I am trying get similar look on date range picker like below (figure 1). Figure 1 : Predefined Date Ranges HTML of current form <form method="POST" enctype="multipart/form-data"> <input type="hidden" name="csrfmiddlewaretoken" value=""> <div id="div_id_start_date" class="form-group"> <label for="id_start_date" class="col-form-label "> Start date </label> <div class=""> <input type="text" name="start_date" value="2019-04-25" class="datetimeinput form-control" id="id_start_date"> </div> </div> <div id="div_id_end_date" class="form-group"> <label for="id_end_date" class="col-form-label "> End date </label> <div class=""> <input type="text" name="end_date" value="2019-04-26" class="datetimeinput form-control" id="id_end_date"> </div> </div> <input type="submit" id="btnsubmit" value="Submit"> HTML and JS of Figure 1 look < div id = "reportrange" style = "background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%" >< i class = "fa fa-calendar" > < /i>&nbsp; < span > < /span > < i class = "fa fa-caret-down" > < /i > < /div > < script type = "text/javascript" > $(function() { var start = moment().subtract(29, 'days'); var end = moment(); function cb(start, end) { $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } $('#reportrange').daterangepicker({ startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, … -
Django ModelForm not saving data to Model
I created a model and respective ModelForm, view and Template for it, but ModelForm does not save data to the model even though .save() function is used. I have tried reviewing forms and views but I do not know what is wrong.I have posted the respective models, forms, views and templates in the question. models.py: class Centre(models.Model): Location = ( ('rashmi_heights', 'Rashmi Heights Centre'), ('Levana', 'Levana Centre') ) name= models.CharField(max_length=50, blank=False, choices=Location, unique=True) address = models.CharField(max_length =250) contact = models.CharField(max_length=100, blank=False) phone = PhoneField(blank=True, help_text='Contact phone number') def __str__(self): return self.name forms.py: class CentreForm(forms.ModelForm): class Meta(): model = Centre fields = '__all__' views.py: def centre(request): forms = CentreForm() if request.method == 'POST': forms = CentreForm(request.POST) if forms.is_valid(): centre = forms.save(request.POST) centre.save() else: forms = CentreForm() return render(request,'NewApp/centreinfo.html',{'forms':forms}) template: <!DOCTYPE html> {% extends 'NewApp/base.html' %} {% load staticfiles %} {% block body_block %} <div class="jumbotron"> <h2>Fill details about your centre.</h2><br> <h3> </h3> <form method="post" enctype="multipart/form-data"> {{forms.as_p}} {% csrf_token %} <a class="btn btn-primary" href="{% url 'NewApp:centreinfo' %}">Submit</a> </form> </div> {% endblock %}