Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send date to Template of django
in my project, user after register can complete his information in another form. after completed this form and submitted it every time he visits this page, he sees the completed form. but i have a problem in this form, calender of user's birthday field works well at the first time when field is empty, but after the form is completed and submitting when the user wants to change it the calendar looks like this: models.py: from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): ED_CHOICES = [ ('hs', 'High school'), ('bc', 'Bachelor'), ('ms', 'Master'), ('do', 'Doctor'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=13) birthday = models.DateField() education = models.CharField(max_length=20, choices=ED_CHOICES) gender = models.CharField(max_length=15) forms.py: class ProfileForm(forms.ModelForm): ED_CHOICES = [ ('hs', 'High school'), ('bc', 'Bachelor'), ('ms', 'Master'), ('do', 'Doctor'), ] phone = forms.CharField( widget=forms.TextInput(attrs={'class': 'input--style-4'}), label='' ) birthday = forms.DateField( widget=forms.DateInput(attrs={'class': 'input--style-4 js-datepicker'}), label='' ) education = forms.CharField( widget=forms.Select(choices=ED_CHOICES, attrs={'class': 'select-dropdown'}), label='' ) gender = forms.CharField( widget=forms.TextInput(attrs={'class': 'radio-container m-r-45'}), label='' ) class Meta: model = models.UserProfile fields = ['phone', 'birthday', 'education', 'gender'] views.py: from django.shortcuts import render, redirect from . import forms, models from django.contrib.auth import get_user_model my_user = get_user_model() my_profile = models.UserProfile first = True def profile(request, slug): … -
One Form for Two Models in Django and get thread ID after it's created
Okay, so I'm creating a function that creates a new thread for a forum software. I pass in the category that the new thread is going into, through the URL. Currently, for the new thread, I have title, body, author which are passed through a hidden input, and the category which is also passed in through hidden input. Now what I want to do is, whenever I create the thread, I want the same details to be posted into a different model. So the Thread model has name (title), body (content), author, and forum_id. The Post model which I want it to go into has post_body (content), (author), and post_thread. Now the important part is post_thread is the current thread that we are about to create that we haven't created yet. How can I get the ID of this thread AFTER it's created and then pass into that Post model? Basically, when you create a new thread, it creates the first post in that thread and attaches itself to it. I know this is kinda confusing but anybody who has experience with forum software should have an easier time getting what I'm trying to do here. Models.py class Thread(models.Model): name … -
django count rows by column
I have a model like this class tbl_invoice(models.Model): invoice_id = models.IntegerField(blank=True, null=True) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) invoice_number = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) total_tax = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) discount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) balance = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) a client can obviously have multiple invoices and I want to show all the invoices according to clients in a table like Customer Total Invoices Total Amount Total Tax Client1 10 50000 200 Client2 8 10000 500 I tried this tbl_invoice.objects.values('client_id').order_by().annotate(Count('client_id')) but this gives <QuerySet [{'client_id': 19, 'client_id__count': 5}, {'client_id': 21, 'client_id__count': 10}, {'client_id': 24, 'client_id__count': 15}]> this does give the count of rows but how can I get other data?? sorry if this is a duplicate, but I just can't figure out this simple query. -
How to execute redis-server.exe in Heroku?
I'm following this tutorial and faced the problem how to execute redis-server.exe in heroku. https://www.youtube.com/watch?v=Wv5jlmJs2sU&list=PLLRM7ROnmA9EnQmnfTgUzCfzbbnc-oEbZ&index=1 Procfile web: gunicorn mysite.wsgi --log-file - Should I add something on setting.py or Procfile? I am a newbie btw. any suggestion and advice is welcome! thank you! -
create directory function is not working in django production server
create directory function not working in django production server (using nginx ) and also not show any error in nginx logs but when we run django prebuild server manually (python3 manage.py runserver 0.0.0.0:8000) then all functions work properly. if request.method == 'POST': prefix = request.POST.get('prefix', '') log_usr = request.user subprocess.call('mkdir -p '+'/home/django/usr/'+str(log_usr)+'/'+str(prefix), shell=True) I am using above code for create directory -
Django modelling a rules based engine
Hi I am building a calculator and a rules engine. I am struggling how to model this table in the database. where it will be easier if parameters change to be adjusted in the django admin rather than redeploy code The lower and upper are income based and depending if they have children (dependents) you can add to the expenses if > 2 and then you add a fixed amount (Single add dep) and (couple add dep) for each child above 2. If someone can assist it would be greatly appreciated -
Trouble getting Salesforce login working with dj-rest-auth + django-allauth
My app has a Django 3.1 backend with django-allauth and dj-rest-auth (actively supported fork of django-rest-auth). My mobile and web frontends can already sign in using Facebook and Google via REST. I'm now trying to add Salesforce as a 3rd REST social login method, but am running into issues. I've followed the django-allauth instructions for Salesforce: Created a Salesforce Connected App with id and openid scopes (along with some others), and set the callback URL to https://www.mywebdomain.com/accounts/salesforce/login/callback/ Created a SocialApplication in Django with client ID, secret, and login URL in the "Key" field (https://login.salesforce.com/) Included allauth.socialaccount.providers.salesforce in INSTALLED_APPS I've been using client-side JSforce to kick off the Salesforce auth request in the frontend, but I'm open to other methods if they are simpler/better/etc. Running jsforce.browser.login() in my clients' JS code opens a Salesforce login popup. After entering Salesforce login credentials, the Salesforce system redirected to my defined callback URL, resulting in a page that shows the following text: Social Network Login Failure An error occurred while attempting to login via your social network account. The URL in the address bar on that page looks something like this: https://www.mywebdomain.com/accounts/salesforce/login/callback/#access_token=00D3t000004QWRm%21ARwAQPfHWiM6jdB43dlyW6qjEw._34mjzGi_Jv6YCXp0QssT.9F9lCge5_YaH8gqTy3Od6SywCs8X9zOGv145SyviBVeGdn0&instance_url=https%3A%2F%2Fna123.salesforce.com&id=https%3A%2F%2Flogin.salesforce.com%2Fid%2F00D3t000004QWRmEAO%2F0053t000008QBetAAG&issued_at=1606802917608&signature=KvxAX0WBCFQYY%2BO25id9%2FXxpbh2q2d2vWdQ%2FFV5FCBw%3D&state=jsforce0.popup.c0ockgct29g&scope=id+api+web+refresh_token+openid&token_type=Bearer I tried to debug and print the error in my backend, but … -
Changing the inner Element of HTML using Javascript to present Django For Loop
I am currently in the process of the basics of Javascript and I know Django. So I am trying to use javascript to show elements in HTML for a Django For Loop. The purpose of doing this is that I understood that presenting data using Javascript doesn't require the page to be refreshed, so I decided to give it a try. To explain more my question here is an example of what I did. I have a list of name of users who likes a posts and there are presented in the following format in the template: <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> {% for user in post_likes %} <span class="dropdown-item" >{{ user.username }}</span> {% endfor %} So I added an id to the span and added the following script related to javascript: <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> {% for user in post_likes %} <span id="id01" class="dropdown-item" >{{ user.username }}</span> {% endfor %} </div> <script> var element = document.getElementById("id01"); element.innerHTML = "{{ user.username }}"; </script> When a new user likes the post his name should appear directly in this loop without the page refreshing but it is not happening and the name of the logged-in user is the one and appearing. I am not sure … -
Django Comment on Blog System
So I am trying to build up comment system in my instagram-like app. My main problem is that i can't get access to comment(s) of each post in my PostListView which inherits from ListView of Django Model of Comment: class Comment(models.Model): post = models.ForeignKey(Post, on_delete = models.CASCADE, related_name ='comments') user = models.ForeignKey(User, on_delete = models.CASCADE) content = models.TextField() View of PostList: class PostListView(LoginRequiredMixin,ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-created_on'] urls.py path('',PostListView.as_view(), name='blog-home'), all the imports have been coded properly. The problem is that within my PostListView I also want to display comment(s) of each post. Pretty much like instagram where we can find posts and comments in the same page(we should not necessarily click on post and go to detail of a particular post) -
TypeError: 'QuerySet' object does not support item assignment when creating an object in Django
I get a " TypeError: 'QuerySet' object does not support item assignment " error message when trying to create an object in Django. Here is my code: for ing in ingredient_list: print(ing['name']) target = Ingredient.objects.filter(name=ing['name'], brand=ing['brand'],price=ing['price'],igd_type=ing['igd_type']) # If there are no ingredient, create ingredient. if len(target) == 0: temp = 0 print(ing['quantity']) tempPicture = "carrot.png" price = ing['price_normalized'] if ing['price_normalized'] != 0 else ing['price'] normPrice = 0 if (ing['price_normalized'] or ing['quantity']==0) else ing['price']/ing['quantity'] quantity = float(ing['quantity']) target[0] = Ingredient.objects.create(name=ing['name'], brand=ing['brand'], price=price, igd_type=ing['igd_type'], quantity=quantity, price_normalized=normPrice, picture=tempPicture ) target[0].save() print(target[0]) I get the error at picture. Why can't I assign?? I would really appreciate the help! -
Keep django pagination and search filters when submitting form on same page
I have a view which has a list of all customers on one side, which also has working pagination and search/ filter functionality. Where I am stuck is, if I have a form & button on my list to select a customer to view on the other side of the page, and it clears my current pagination page and any filters applied to the customer list when I run the function to pick up the selected customer. How can I have a form action = "{% url 'some_function' %}" and keep the pagination and search. http://localhost:8000/clients/clean?page=8&search_term=nsw Current view: def customer_list_clean(request, selected = None): if selected != None: selected = Client_Customer.objects.get(id = selected) try: msg = request.GET['search_term'] except: msg = "" clients = Client_Customer.objects.distinct().filter(Q(customer_name__contains = msg) | Q(physical_address__street_address__contains = msg) | Q(physical_address__suburb__suburb__contains = msg) | Q(physical_address__suburb__post_code__contains = msg) | Q(physical_address__suburb__region__state_abb__contains = msg) ).order_by('customer_name') if msg: messages.success(request, (f"Customer records filtered by: {msg}")) found = clients.count() if clients.filter(confirmed= False).count()>0: messages.info(request, (f"Some customers records have not been validated!")) #Pagination page = request.GET.get('page', 1) paginator = Paginator(clients, 25) try: clients = paginator.page(page) except PageNotAnInteger: clients = paginator.page(1) except EmptyPage: clients = paginator.page(paginator.num_pages) if selected != None: context ={'clients':clients, 'found':found, 'msg':msg, 'selected':selected} else: context ={'clients':clients, 'found':found, … -
Uncaught TypeError: Cannot read property 'style' of undefined using datatable pipeline
I am using Datatable pipeline for generating table. My table has dynamic column means it has no fixed column. The column column number changes with the change of a month. Suppose, during current month the table has 4 column but for november it has 32 columns. When I changes month to november,it gives me Cannot read property 'style' of undefined this error. My datatable initilization function: function monthlyAttendanceStatusDatatableInit(tableIdOrCss, url, columns, sortArr, pageLength, year, month) { console.log(columns); var param = { "responsive": false, // "columnDefs": [ // {responsivePriority: 1, targets: -1}, // {responsivePriority: 2, targets: 0} // ], "aLengthMenu": [[10, 20, 50, -1], [10, 20, 50, 'All']], "pageLength": pageLength || 10, "iDisplayLength": pageLength || 10, //"language": { search: "" }, "sPaginationType": "simple_numbers", // you can also give here 'simple','simple_numbers','full','full_numbers' "oLanguage": { "sSearch": "Search:", "sProcessing": "Loading..." }, "ajax": $.fn.dataTable.pipeline( { url: url, data: { 'month': month, 'year': year }, pages: 2 // number of pages to cache }), "processing": true, "serverSide": true, "searching": true, // "bPaginate": true, // "fnDrawCallback":function(){ // if(typeof callBack == 'function'){ // callBack(); // } // }, "destroy": true, "paging": true, "retrieve": false, "aoColumns": columns, "aaSorting": sortArr, //[[ 0, "asc" ],[ 1, "desc" ]] // Sort by first column … -
how do I assign api keys to unique users in django rest framework
so I'm working on a rest framework project that requires to have a |get-key/ endpoint that returns the current users api-key I've read alot of articles and even tried to use the diangorestframework-api-key,but still no success for me. please any idea on how to do this would be greatly appreciated.🥺 -
How can get list of field value from all objects list in django python?
I have Client class, and i am trying to get all objects email in one list. class Client(models.Model): client_name = models.Char Field(max_length=100, null=True, blank=True) client_email = models.Email Field() From all objects list i need all emails which are in Client list. How can i do this ? -
read html file inside zip file python djnago
I am reading a zip file using django python and uploading that to aws s3. I want to read html file inside zip file and upload that html fle to s3 but not zip file. *NOTE : I am always recieving zip file in_memory_uploaded_file = request.FILES['file'] files = in_memory_uploaded_file.open("rb") boto3.setup_default_session(profile_name='test') s3 = boto3.resource('s3') base_url = 'https://s3-ap-southeast-1.amazonaws.com/atest.poptest.com/creatives_preview/' s3_file_path = "creatives_preview" + "/" + "indgdex.zip" s3.meta.client.upload_fileobj(files, 'adunits.popmunch.com', s3_file_path) -
Trying to grab a random pic through JS but dosen't work properly
Hi guys I am a django developer and trying to grab a random img through JS in html like below img works and it would randomly pick one from the ImageArray. However, the path will be <img src= '/static/%22%20%2B%20img%20%2B%22'>. Rather than something I want like <img src= "{% static 'img/indexBg_1.png' %}" > And the error msg is : GET http://192.168.7.64:8000/static/img/%22%20%2B%20pic%20%2B%20%22%20 404 (Not Found) Could anyone enlighten me to resolve this problem? Thx! <script type="text/javascript"> window.onload=function(){ ImageArray = new Array(); ImageArray[0] = 'img/indexBg_1.png'; ImageArray[1] = 'img/indexBg_2.png'; ImageArray[2] = 'img/indexBg_3.png'; var num = Math.floor( Math.random() * 3); var img = ImageArray[num]; var path = " <img src= '{% static '" + img +"'%}'>" console.log(img) console.log(path) } </script> -
How to test if an object is a django UploadedFile?
I am using django3.1 and python 3.7. I have a dictionary as follow: {'text2': 'text2', 'file2': <UploadedFile: img5.jpg (image/jpeg)>, 'file22': <UploadedFile: img8.jpg (image/jpeg)>} I want to print out the image names: img5.jpg img8.jpg When I check type of <UploadedFile: img5.jpg (image/jpeg)>, it says: <class 'django.core.files.uploadedfile.UploadedFile'> I tried following: data1 = {'text2': 'text2', 'file2': <UploadedFile: img5.jpg (image/jpeg)>, 'file22': <UploadedFile: img8.jpg (image/jpeg)>} for key in data1: if isinstance(data1[key], io.IOBase): print(data1[key].name) else: print('not a file') It always shows not a file. Any idea? Thanks! -
Using Vue.js inside Django template
What I would like to accomplish is to set a django block content inside a vue app. I used vue cli to create a vue app but I am not able to do the following. views.py def login(request): template_name = 'login.html' return render(request, template_name) base.html {% load static %} <html> <body> <div id="app"> {% block component %}{% endblock %} </div> </body> </html> <script src="{% static 'assets/js/app.js' %}"></script> login.html {% extends 'base.html' %} {% block component %} <myComponent /> {% endblock %} What kind of setup do I need to build app.js in way that I can put whatever component I want in the templates? below is the NOT working vue files main.js import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app') App.vue <template> <div id="app"> </div> </template> <script> import HelloWorld from './components/HelloWorld.vue' export default { name: 'App', components: { HelloWorld } } </script> <style> </style> Currently if I add tags within the component block in login.html nothing changes. If I add a tag inside App.vue it will show up in login.html but I want to be able to choose which components will be displayed. -
Hi can anyone help me I'm trying to show some categories but the problem is I can't paginate or using this "paginate_by = 10" in Generic Views
This is the views.py HomeView This is the Main Page That I want to make it paginate The problem is the categories its not detected I try to refresh or restart but nothing happen. But the category is ok no error just only the pagination guys please help me. class HomeView(ListView): model = Food paginate_by = 10 context_object_name = "index.html" def get(self,request): categories = Category.getAllCategory() food = Food.getAllProduct().order_by('-id') if request.GET.get('id'): filterProductById = Food.objects.get(id=int(request.GET.get('id'))) return render(request, 'productDetail.html',{"food":filterProductById,"categories":categories}) if request.GET.get('category_id'): filterProduct = Food.getProductByFilter(request.GET['category_id']) return render(request, 'index.html',{"food":filterProduct,"categories":categories}) return render(request, 'index.html',{"food":food,"categories":categories}) def query_set(self): return Category.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories_list'] = Category.objects.all() return context CategoryView This is also in Main Page class CategoryView(ListView): model = Category paginate_by = 4 template_name = "index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories_list'] = Category.objects.all() return context This is models.py class Category(models.Model): category = models.CharField(max_length=100) def __str__(self): return self.category @staticmethod def getAllCategory(): return Category.objects.all() And this is the Homepage for HTML, if you think this is wrong can you help me {% if is_paginated %} <nav class="d-flex justify-content-center wow fadeIn"> <ul class="pagination pg-blue"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} <li class="page-item … -
passing two files as -d parameters in curl command
how do I pass two files with the -d parameter in a curl command and then accept them in django? If I pass them like: curl -X POST -d '1='/Users/User/desktop/test.json -d '2=/Users/User/desktop/test.json' http://127.0.0.1:8000 It accepts it as a string because that's how i'm passing it. but if I want to add the @ symbol before both of them then I can't assign them the 1= and 2= identifiers? How do I get around this so I can pass two files with identifiers so I can get each of them seperately from the request? -
How to get optional parameters from a url and use them to parse objects from a model?
For example, from the url: https://localhost:8000/parameters=param1&param2&param3 How can I parse out the parameters as a list and pass it into a class-based view? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('parameters=...', MyListView.as_view()), ] views.py class MyListView(generics.ListAPIView): queryset = MyObject.objects.all() # Use the parameters to filter out objects serializer_class = MyObjectSerializer models.py class MyObject(models.Model): object_id = models.CharField(max_length=10) content = models.CharField(max_length=120) # Each object can have an unlimited number of parameters class ObjectParameters(models.Model): my_object = models.ForeignKey(MyObject, on_delete=models.CASCADE) param = models.CharField(max_length=120) I would like to query a list of objects that contain all given parameters. Also, is this a logical structure for my models? -
Why cant my Django app read the environment variables set?
Problem My django app cannot read the env vars that I set. Im sure it is something stupid simple that I am missing. The env vars exists as I expect them to. When I go into the python shell I am able to access them. Using the os.environ["DB_PASSWORD_DJANGO"]command. Code The variables exist as I expect them ~/.profile # Set Environment Vars export DB_NAME_DJANGO="<name>" export DB_USER_DJANGO="<user>" export DB_PASSWORD_DJANGO="<pw>" export CLOUD_SQL_INSTANCE_IP="<IP>" user@localhost:~$ env ANG=en_US.UTF-8 ... CLOUD_SQL_INSTANCE_IP=<ip> DB_PASSWORD_DJANGO=<pw> DB_USER_DJANGO=<user> ... DB_NAME_DJANGO=<db> Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['DB_NAME_DJANGO'], 'USER': os.environ['DB_USER_DJANGO'], 'PASSWORD': os.environ['DB_PASSWORD_DJANGO'], 'HOST': os.environ['CLOUD_SQL_INSTANCE_IP'], 'PORT': 5432, } } Error Dec 3 02:16:52 localhost gunicorn[36212]: File "/usr/lib/python3.6/os.py", line 669, in __getitem__ Dec 3 02:16:52 localhost gunicorn[36212]: raise KeyError(key) from None Dec 3 02:16:52 localhost gunicorn[36212]: KeyError: 'DB_NAME_DJANGO' Dec 3 02:16:52 localhost gunicorn[36212]: [2020-12-03 02:16:52 +0000] [36218] [INFO] Worker exiting (pid: 36218) Dec 3 02:16:52 localhost gunicorn[36212]: Traceback (most recent call last): Dec 3 02:16:52 localhost gunicorn[36212]: File "/home/user/django_app/venv/lib/python3.6/site-packages/gunicorn/arbiter.py", line 209, in run Dec 3 02:16:52 localhost gunicorn[36212]: self.sleep() Dec 3 02:16:52 localhost gunicorn[36212]: File "/home/user/django_app/venv/lib/python3.6/site-packages/gunicorn/arbiter.py", line 357, in sleep Dec 3 02:16:52 localhost gunicorn[36212]: ready = select.select([self.PIPE[0]], [], [], 1.0) Dec 3 02:16:52 localhost gunicorn[36212]: File "/home/user/django_app/venv/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld … -
How can i display ListCharField's verbose_name in HTML (Django)
I have a model looks like this class Program(models.Model): name = models.CharField(max_length=20, default='program_1') pazartesi = ListCharField( verbose_name = 'Pazartesi', base_field=models.CharField(max_length=15), size=10, max_length=(10 * 16) ) and this is my views.py file: def program(request): context = { 'dp' : Program.objects.all() } return render(request, 'dash/program.html', context) and i want to display the ListCharField's verbose name which is 'Pazartesi' on my template. {% for i in dp %} <th scope="col">{{ i.pazartesi.XXX }}</th> {% endfor %} i tried creating a custom tag like return object._meta.verbose_name but i get 'str' object has no attribute 'verbose_name' error. Is there any functon where i can put on 'XXX' or another simple way? -
Django Rest Framework Serializer : get fields of two models
Hello all been working on Rest API for couple of weeks I have learned about serializers and nested serializer. I am stucked on grabbing fields from Two models is it possible to do in serializer. Here is my code. class Slider(BaseModel): page = models.ForeignKey(Page, on_delete=models.CASCADE) section = models.CharField( max_length=20, validators=[validators.validate_section_name], ) tag = models.CharField( max_length=20, validators=[validators.validate_tag_name], ) class Meta: default_permissions = () verbose_name = 'Slider' verbose_name_plural = 'Sliders' def __str__(self): return self.section next model I want to combine in serializer is class SliderImage(BaseModel): image = models.ImageField( upload_to=upload_slider_image_to, validators=[], null=True, blank=True ) slider = models.ForeignKey(Slider, on_delete=models.CASCADE, related_name='slider_image', ) class Meta: default_permissions = () verbose_name = 'Slider Image' verbose_name_plural = 'Slider Images' now is there any way out so that i can get serializers in this way? {page:home-banner, section:home-banner, image:?-- I want this from slider_Image?} I am newbie hope I clarified my question. -
Django - Cannot run "py manage.py runserver"
I have tried python manage.py runserver, same result. It says the following in the terminal: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases When I run py --version, it works fine. I want to know why it says python was not found, when it works just fine. I haven't found anything online.