Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way in which I can edit "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css" file?
I tried doing it by creating a css file style.css in the same folder, copied the source code of the bulma link provided and then linked it to my html doc. But then, it shows no css features at all. -
Ajax returning empty string in Django view
I am developing a web application through Django and I want to get information from my javascript to a view of Django in order to access to the database. I am using an ajax call as this post shows. I am calling the js in html by an onclick event : sortedTracks.html ... <form action="{% url 'modelReco:sortVideo' video.id %}"> <input type="submit" value="Validate" onclick="ajaxPost()" /> </form> ... clickDetection.js function ajaxPost(){ $.ajax({ method: 'POST', url: '/modelReco/sortedTracks', data: {'tracksSelected': tracksSelected}, success: function (data) { //this gets called when server returns an OK response alert("it worked! "); }, error: function (data) { alert("it didnt work"); } }); }; So the information I want to transfer is tracksSelected and is an array of int like [21,150,80] views.py def sortedTracks(request): if request.is_ajax(): #do something print(request) request_data = request.POST print(request_data) return HttpResponse("OK") The ajax post works well but the answer I get is only an empty Query Dict like this : <QueryDict: {}> And if I print the request I get : <WSGIRequest: GET '/modelReco/sortedTracks/?tracksSelected%5B%5D=25&tracksSelected%5B%5D=27&tracksSelected%5B%5D=29'> I have also tried to change to request_data=request.GET but I get a weird result where data is now in tracksSelected[] -
how to implement ExpressionWrapper, F and Sum properly in django
I have two models Product and Damaged. Product has quantity of an item and Damaged has the number of damaged quantity of that item. In my template list_product I have listed total quantity of each product. When I add number of damaged_quantity into the Damaged model it should be deducted from the number of total quantity in Product. I have implemented the following code. Everything works fine. The only problem I am having is if the total number of quantity in Product is equal to number of damaged_quantity from Damaged it doesn't show 0 in the template of product_list. How to solve it? models.py class Damaged(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) damaged_quantity = models.IntegerField(default=0) class Product(models.Model): name = models.CharField(max_length=250) quantity = models.IntegerField() views.py def list_product(request): products = Product.objects.annotate(damaged_product_quantity=Sum( 'damagedproducts__damaged_quantity')).annotate( real_quantity=ExpressionWrapper(F('quantity')-F('damaged_product_quantity'), output_field=IntegerField())) damaged_products = Damaged.objects.all() return render(request, 'pos/list_product.html', {'products': products, 'damaged': damaged_products}) list_product template {% if not product.real_quantity %} {{product.quantity}} {% elif product.quantity == product.real_quantity %} 0 {% else %} {{ product.real_quantity }} {% endif %} -
My generic DetailView not showing list of items
I am following a django tutorial series, the music website contains the ListView which contains Albums(this is showing) but the DetailView Containing the list of songs in each Album is not showing. I have tried changing the iteration name in the for loop but it still not working, the list shows when i am not using the generic method i.e using index and detail function instead of the IndexView and DetailView classes. MY music.views Code class IndexView(generic.ListView): template_name='music/index.html' def get_queryset(self): return Albums.objects.all() class DetailView(generic.DetailView): model = Albums template_name = 'music/detail.html' My detail.html code which is supposed to show the list of songs but not working {% extends 'music/base.html' %} {% block title %} Album Details {% endblock %} {% block body %} <img src ="{{ all_album.alb_logo }}"> <h1>{{ all_album.alb_title }}</h1> <ul> {% for song in all_album.song_set.all %} <li>{{ song.song_title }} </li> {% endfor %} </ul> <br> {% endblock %} My index.html which shows the list of albums, this is working {% extends 'music/base.html' %} {% block body %} <h2>List of Current albums available</h2> <div class='container-fluid'> <div class='row'> {% for album in object_list %} <div class='col-lg-4'> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ album.alb_logo }}" > <div class="card-body"> <h5 class="card-title">{{ album.alb_title … -
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) == …