Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Slice Django Queryset field value
My object has content field which is actually content of the article. I am passing it to template by using XHR. I don't want to slice content in front end. How can I slice it by giving a maximum character limit? It is very long content so doing it in backend will help me to reduce my JSON size. This is how my JSON looks like. I deleted content because it is very long. It will be in results list. -
NodeJS Grant - Oauth with Django Oauth Toolkit app
I'm working with two servers, one a NodeJS app (FeathersJS and Grant for authentication), and the other is a Django app, using django-oauth-toolkit for authentication. https://github.com/simov/grant https://pypi.org/project/django-oauth-toolkit/ I am trying to get the NodeJS app to oauth with the python django app, so here is what I have done so far: Registered Feathers with Django Oauth toolkit - Configured Feathers/Grant with the following options: "key": "xxx", "authorize_url": "https://www.com/o/authorize", "access_url": "https://www.com/o/token" But I'm running into an issue where the grant workflow is not receiving the access token, and am stuck at this point. Has anyone tried integrating two apps as such and been successful in this process? I'd appreciate any pointers, suggestions. Thanks! -
How to hide 0 notification count in django-notifications-hq
I ham trying to hide the notification count when it's 0 in django-notifications-hq I have tried the below method but it is not updating regularly and displaying the number correctly. {% live_notify_badge as nc %} {% if nc > 0|add:0 %} <span class="badge-notifications badge badge-pill badge-danger" style="float:right;margin-bottom:-3px;margin-top: -2px !important; margin-left: 10px !important; font-size: 0.6rem;"> {% live_notify_badge %}</span> {% endif %} -
Is it possible to make option tag a link or button
I'm trying to trigger modal form using a selection from the dropdown list. In using django. The idea is that use is filling a form. He can make a selection from the dropdown list but if he will not find a required item on the list he can add this item. He would be able to do this filling modal form. Now it is triiger with button. The ideal situation would be if there is a button or link on the dropdown list. Something like bootstrap offers, what is called separated link: html - the dropdown list content <option value="">---------</option> {% for salesPersonDistributor in salesPersonsDistributor %} <option value="{{ salesPersonDistributor.pk }}">{{ salesPersonDistributor.name }}</option> {% endfor %} html - from template <form method="post" id="subsidiaryForm" name="text" data-subsidiaries-url="{% url 'ajax_load_subsiriaies' %}" data-salesPersonsDistributor-url="{% url 'ajax_load_salesPersonsDistributor' %}" data-salesPersonsDistributorContact-url="{% url 'ajax_load_salesPersonsDistributorContact' %}" novalidate> <table class="table table-borderless table-condensed"> {% csrf_token %} {{ form.as_table }} </table> <input type="hidden" name="build" value="{{ VCIUpdate }}">, <input id="submit" type="submit" value="save" /> </form> <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"></div> </div> </div> <button id="new_sales_person_distibutor" class="btn btn-primary" type="button" name="button">Dodaj przedstawiciela</button> </div> jquery $(document).ready(function() { $("#new_sales_person_distibutor").modalForm({ formURL: "{% url 'new_sales_person_distibutor' %}" }); }); I have tried to trigger jquery usung vale if … -
Invalid API Key provided in creating token (Stripe)
How to fix Invalid API Key provided: cus_**** card = stripe.Token.create(customer_id, method) charge = stripe.Charge.create( amount=price, currency='usd', description=desc, receipt_email=request.user.email, source=card ) I've tried adding the account id to Token.create like this: card = stripe.Token.create(stripe_account_id, customer_id, method) but that gives the error Invalid API Key provided: acct_**** and I think that's what I'm supposed to be using so I'm not sure what I'm doing wrong. -
Debugging graphql queries in Django
How can I get my GraphQL API to show more query/post data in the console? I'm running a Django app that is powered by GraphQL and served via a react frontend. With regular Django paths I would see something like this in the development server: [04/Sep/2020 11:53:08] "GET /my_app/2020/09/01/5cc4e7cc-7.png HTTP/1.1" 200 11330 But with GraphQL all I see is this: [04/Sep/2020 11:53:18] "POST /graphql HTTP/1.1" 200 32 [04/Sep/2020 11:53:18] "POST /graphql HTTP/1.1" 200 2993 [04/Sep/2020 11:53:29] "POST /graphql HTTP/1.1" 200 11635 Any ideas? -
What happens if I rename the 'manage.py' in django?
I have changed the 'manage.py' to 'server.py' and it worked. But what I want to know is whether it will work if I host the Django App somewhere ? -
I am geeting error in unit testing of django app
I am geting error "ValueError: Cannot assign "'12A20'": "Attendance.rollno" must be a "Student" instance." how to solve it ?? Is another way for testing when foreign key is present in Django? model.py class Student(models.Model): classId=models.ForeignKey(Class,on_delete=models.CASCADE) name=models.CharField(max_length=20) fatherName=models.CharField(max_length=20) motherName=models.CharField(max_length=20) address=models.TextField(max_length=100) section = models.CharField(max_length=2) prevClass=models.IntegerField() prevClassMark=models.IntegerField() prevResult=models.ImageField(upload_to='images/') gender=models.CharField(max_length=6) image=models.ImageField(upload_to='images/') stream=models.CharField(max_length=10,)#choices=Stream) department=models.CharField(max_length=15) dob=models.CharField(max_length=12) rollno = models.CharField(max_length=10) password=models.CharField(max_length=30) class Attendance(models.Model): rollno=models.ForeignKey(Student,on_delete=models.CASCADE) class_id=models.ForeignKey(Class,on_delete=models.CASCADE) date=models.CharField(max_length=11) status=models.CharField(max_length=7) tests.py class AttendanceTest(TestCase): def setUp(self): Attendance.objects.create( rollno='12A20', class_id=121, date='2020-09-03', status='Present' ) Attendance.objects.create( rollno='13A20', class_id=121, date='2020-09-03', status='Present' ) def test_Attendance(self): qs=Attendance.objects.all() self.assertEqual(qs.count(),2) -
How to pass query sets from html to views.py in django using AJAX
I am new to Django.So here, I am trying to pass a two query sets from Django html template to Django views.py. This has to happen on the click of a button and hence, I am using onClick function to pass the parameters to Ajax and from there, I am sending it to views.Here, along with the two query sets, I am passing two other values called rid and category and it is working fine,but the query sets are getting converted to string and hence I am not able to iterate through the query sets after passing it to the views.py page. This is my views.py code: if request.is_ajax(): rid = request.POST.get('rid') category = request.POST.get('category') extracted_records=request.POST.get('extracted_records') show_cards_records=request.POST.get('show_cards_records') return render(request,'cards_update.html',{'extracted_records':extracted_records,'show_cards_records':show_cards_records,'rid':rid}) return render(request,'cardpage.html',{'extracted_records':extracted_records,'show_cards_records':show_cards_records,'rid':'1234'}) This is my main html code: <!-- templates/base.html --> {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head > <meta charset="utf-8"> <title>CardGame</title> <link rel="stylesheet" href="/static/css/cardpage.css"}> </head> <body> <center> <h1>{{rid}}</h1> <div id='update_cards'> {% include 'cards_update.html' %} </div> </center> </form> </body> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type = "text/javascript" charset = "utf-8"></script> <script> function func(rid,category,extracted_records,show_cards_records) { $.ajax({ type: 'POST', url: '/Cardpage', data:{ 'rid':rid, 'category':category, 'extracted_records':extracted_records, 'show_cards_records':show_cards_records, }, success: function (response) { $("#update_cards").replaceWith(response); alert("card casted."); } }); } </script> </html> This is … -
How do I displaya list of dictionary of dictionaries in django template?
Here the dictionary employee contains the list of the dictionary. "Emp": [ { "info": [ { "name": john Patrik, "emp_id": "20021", "salary": 3000 "interest":[{"fav_song":"happy_song"}, {"fav_city":"newyork","fav_place":"centralPark"}] }] }] -
Python django threading and dictionary
Hello I'm running django server that fetch some large chunks of data from database and printing it on view as json but this is rather slow, so I thought about using threading to speed up this code and it somewhat worked but still it is quite slow. This my first attempt to use concurrent.futures module so some of my solution are probably ugly. def chartData(request): fixm = datetime.min.time() fixd = datetime.max.time() datee = datetime.date(datetime.now()) dateo = datee - timedelta(days=1) dateo = datetime.combine(dateo, fixm) datee = datetime.combine(datee, fixd) resultproc = {} s1 = S280000020E3120.objects.filter().values('date', 'temprature') s2 = S280119514568Ff.objects.filter().values('date', 'temprature') s3 = S2801195146F4Ff.objects.filter().values('date', 'temprature') s4 = S28011951743Bff.objects.filter().values('date', 'temprature') s5 = S285A1993D983Ff.objects.filter().values('date', 'temprature') s6 = S285A1993Ed66Ff.objects.filter().values('date', 'temprature') s7 = S285A1993F99Fff.objects.filter().values('date', 'temprature') s8 = S280119514D1Eff.objects.filter().values('date', 'temprature') s9 = max31856.objects.filter().values('date', 'temprature') s = [s1, s2, s3, s4, s5, s6, s7, s8, s9] nr = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] resultpr = [resultproc, resultproc, resultproc, resultproc, resultproc, resultproc, resultproc, resultproc, resultproc] # I know this is ugly but I don't know how to properly use it with .map start_time = time.time() with concurrent.futures.ThreadPoolExecutor() as executor: resultproc = executor.map(constructChartData,resultpr, s, nr) print("Thread: ", (time.time() - start_time)) result = { 'ds1':[ list(s1), S280000020E3120.objects.last().sensor.description, ], … -
JavaScript from static is not functioning in my templates while working in django(jinja)
base.html file This is where jinja is used and all js is linked, i have created a partial file of navigation and footer and the problem is in navigation part {% load static %} {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Home</title> <!-- Favicon--> <link rel="icon" type="image/x-icon" href="{% static 'assets/img/favicon.ico'%}" /> <!-- Font Awesome icons (free version)--> <script src="https://use.fontawesome.com/releases/v5.13.0/js/all.js" crossorigin="anonymous"></script> <!-- Google fonts--> <link href="{% static 'https://fonts.googleapis.com/css?family=Merriweather+Sans:400,700'%}" rel="stylesheet" /> <link href="{% static 'https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic'%}" rel="stylesheet" type="text/css" /> <!-- Third party plugin CSS--> <link href="{% static 'https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css'%}" rel="stylesheet" /> <!-- Core theme CSS (includes Bootstrap)--> <link href="{% static 'css/styles.css'%}" rel="stylesheet" /> </head> <body id="page-top"> <!-- Navigation--> {% include 'partials/_navigation.html' %} <!-- Navigation--> <!--content--> {% block content %} {% endblock %} <!--content--> <!-- Footer--> {% include 'partials/_footer.html' %} <!-- Footer--> <!-- Bootstrap core JS--> <script src="{% static 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'%}"></script> <script src="{% static 'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.bundle.min.js'%}"></script> <!-- Third party plugin JS--> <script src="{% static 'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js'%}"></script> <script src="{% static 'https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js'%}"></script> <!-- Core theme JS--> <script src="{% static 'js/scripts.js'%}"></script> </body> </html> Settings: This is the settings part giving static a path STATIC_URL = '/static/' #Manually Done STATICFILES_LOCATION = 'static' STATIC_URL='/static/' … -
I am repeatedly getting [NameError: name '_mysql' is not defined in] in pythonanywhere where i deployed my django web app?
I have installed requirements.txt[mysql, django etc].created the database . Migrated and viewed the mysql(with the same credentials as in the settings) on the pythonanywhere shell. all is fine. All the tables are present but i cant find what is wrong. Please help with this error. these are the related files:- (django 3.1.1 python3 3.8.0 mysql Ver 14.14 Distrib 5.7.27, for Linux (x86_64) using EditLine wrapper) auto generated wsgi.py import os import sys # # assuming your django settings file is at '/home/proj/mysite/mysite/settings.py' # # and your manage.py is is at '/home/proj/mysite/manage.py' path = '/home/proj/proj' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'project3.settings' # # then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() database settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'proj$proj', 'USER': 'proj', 'PASSWORD': '*****', 'HOST': 'proj.mysql.pythonanywhere-services.com', } } errors log 2020-09-04 17:07:32,532: NameError: name '_mysql' is not defined 2020-09-04 17:07:32,532: File "/var/www/proj_pythonanywhere_com_wsgi.py", line 39, in <module> 2020-09-04 17:07:32,532: application = get_wsgi_application() 2020-09-04 17:07:32,532: 2020-09-04 17:07:32,532: File "/home/proj/proj/vad_env/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-09-04 17:07:32,532: django.setup(set_prefix=False) 2020-09-04 17:07:32,533: 2020-09-04 17:07:32,533: File "/home/proj/proj/vad_env/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2020-09-04 17:07:32,533: apps.populate(settings.INSTALLED_APPS) 2020-09-04 17:07:32,533: 2020-09-04 17:07:32,533: File "/home/proj/proj/vad_env/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate 2020-09-04 17:07:32,533: app_config.import_models() 2020-09-04 17:07:32,533: 2020-09-04 17:07:32,533: File "/home/proj/proj/vad_env/lib/python3.8/site-packages/django/apps/config.py", … -
How to save json data that i got from api call in the database while working in django?
[{'year': '2014', 'petroleum_product': 'Diesel', 'sale': 901393}, {'year': '2018', 'petroleum_product': 'Diesel', 'sale': 813399}] If I have JSON data as above how do I save it in the database using Django? I want the year, petroleum_product, and sale to be in the same table. Do I have to first create a model and loop through the data and store it? (If so how can it be achieved?) Or is there a shortcut way of doing it? -
How to handle user data (via browser) that was entered into the webapp
I am new to django, however I wrote my first project and am having trouble getting it started. I transferred the project to another computer for testing. My web application is built for an intranet. So, the project is up and running, I can log in from another computer and everything also works, but when I enter to web app, the user on whose pc where project is running is authorized (one of the authorization conditions is to get a Windows username for verification), I use request.META['USERNAME'] for this. So, it's an essence of the problem: after transferring, i become META data of the PC on which the project is running, from the client I only receive their IP. Please tell me how to be, and forgive my English. Thaks and have a nice day! -
Django bulk_create for many2many field on MySQL
I have the model: class Content(models.Model): can_see = m.ManyToManyField('users.User',blank=True,related_name='can_see') can_edit = m.ManyToManyField('users.User',blank=True,related_name='can_edit') can_delete = m.ManyToManyField('users.User',blank=True,related_name='can_delete') text = m.CharField(max_length=160, blank=True) name = m.CharField(max_length=160, blank=True) I am trying to create many "Contents" by using bulk_create and making a user choose which users can manage contents by filling the fields as this: def handle_csv(request): if request.method == 'POST': form = UploadCSVForm(request.POST, request.FILES) if form.is_valid(): data_can_see = form.cleaned_data['can_see'] data_can_edit = form.cleaned_data['can_edit'] data_can_delete = form.cleaned_data['can_delete'] csvfile = TextIOWrapper(request.FILES['csvfile'].file, encoding='utf-8') table = csv.reader(csvfile) created = Content.objects.bulk_create([Content(text=data[0],name=data[1]) for data in table]) ... return render(request, 'importing/success.html') I now wish to add the manytomany relation to give to the selected users the permissions I want on the Content objects, but I can't set m2m relations in a bulk_create. I tried this: for content in created: content.can_see.set(data_can_see) content.can_edit.set(data_can_edit) content.can_delete.set(data_can_delete) But it's not working since it says the object needs to have an ID before the m2m relation can be set, and I can't understand why the objects list I have have no ID. I think I am not understanding how to create multiple objects with bulk_create. I also tried to add a content.save() in the above mentioned loop, but that is resulting in a double set of objects being created, … -
how to convert Django object into json?
Hi I'm trying to convert a Django queryset object into JSON but every time I try do it with the python JSON module I get this error: "TypeError: Object of type QuerySet is not JSON serializable". Here is the Django object: titles = Queries.objects.values('Topic').distinct(). and here is what it returns `<QuerySet [{'Topic': 'Phone or Web'}, {'Topic': 'Time or Money'}, {'Topic': 'Power or Wisdom'}, {'Topic': 'Luxure or Camp!'}]>. Now even when I try to use the django serilizers to try to solve this problem I get this error: "AttributeError: 'dict' object has no attribute '_meta'." Can anyone help me solve this? Here is my code for both situation. code of the django serializers situation: from django.shortcuts import render from django.http import HttpResponse from .models import Queries import json from django.core.serializers import json from django.core import serializers def data_json(): titles = Queries.objects.values('Topic').distinct() titles_json = serializers.serialize('json', titles) with open('topic.json', 'w') as file: data = json.dumps(titles_json) print(data, file=file) print(titles) def index(request, query_title): queries = Queries.objects.all() page = Queries.objects.filter(Topic=str(query_title)) # print(page) data_json() return render(request, 'Querie/index.html', {'queries': page}) and here how my code looked like when I was using the regular json module so the data_json funtion was like this: import json def data_json(): titles = … -
How to get rid of label generated with django forms
aim: to just have 2 input boxes without a label ontop problem: using django form app a label appears ontop of input boxes: see image. my models.py code is: # Create your models here. class Customer(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) def __str__(self): return self.first_name + ', ' + self.last_name and my 0001_inital.py is # Generated by Django 2.1.7 on 2019-11-01 19:21 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=200)), ('last_name', models.CharField(max_length=200)), ], ), ] -
Django - Save audio file
I'm using this for images: newimage = ContentFile(base64.b64decode(b64image), name='{}.{}'.format(image_name, 'jpg')) But when I try to do the same with audio: newaudio = ContentFile(base64.b64decode(b64audio), name='{}.{}'.format(audio_name, 'mp3')) I get this error: Media resource .../media/audio/1471985664.mp3 could not be decoded, error: Error Code: NS_ERROR_DOM_MEDIA_METADATA_ERR (0x806e0006) Thank you for any suggestions -
Although it works in css on other pages, it doesn't work on category page Django
I built blog site. Although it works in css on other pages, it doesn't work on category page. What can i do? Codes here STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') def category_detail(request, cats): category_posts=Blog.objects.filter(category_id=cats) context = { 'cats': cats, 'category_posts': category_posts, } return render(request, 'post/category.html',context) from django.conf.urls.static import static from django.urls import include, path from blog.views import blog_detail, category_detail from home.views import home_view, about_view urlpatterns = [ url(r'^adminerdo/', admin.site.urls), url(r'^$', home_view), url(r'^about/$', about_view), url(r'^(?P<slug>[\w-]+)/$', blog_detail , name= 'detay'), url(r'^category/(?P<cats>[\w-]+)/$', category_detail, name='category'), ] urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) -
Topics arent being added
Im pretty new to both python and django , currently reading the Python Crash Course by Eric Matthes . Im trying to code a simple learning log , but im having some issues adding new topics using the django form . Heres the code: urls.py: from django.urls import path , re_path from . import views urlpatterns = [ #Home page path('', views.index, name='index'), path('topics/', views.topics , name='topics'), re_path(r'^topics/(?P<topic_id>\d+)/$' , views.topic , name = 'topic'), re_path(r'^new_topic/$' , views.new_topic , name = 'new_topic') ] app_name = 'learning_logs' part of view.py: def new_topic(request): if request.method != 'POST': form = TopicForm else: form = TopicForm(request.POST) if form.is_valid(): form.save return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form' : form} return render(request , 'learning_logs/new_topic.html' , context) new_topic.html: {% extends 'learning_logs/base.html' %} {% block content %} <p>Added a new topic:</p> <form action="{% url 'learning_logs:new_topic' %}" method="post"> {% csrf_token %} {{form.as_p}} <button name='submit'>add topic</button> </form> {% endblock content %} topics.html: {% extends 'learning_logs/base.html' %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <li><a href="{% url 'learning_logs:topic' topic.id %}">{{topic}}</a></li> {% empty %} <li>No topics have been added yet.</li> {% endfor %} </ul> <a href="{% url 'learning_logs:new_topic' %}">Add a new topic:</a> {% endblock content %} -
how to send Django view response to modal?
Im trying to create note detail in modal popup window. Here is the modal invoke anchor tag <a class="fa fa-pencil" data-toggle="modal" href="{% url 'post_detail_view' %}" data-id="{{ todo_item.content }}" data-target="#modal" title="edit item" data-tooltip></a> here is the view function in views.py: def post_detail_view(request, content): all_items1 = TodoItem.objects.get(content=content) return render(request, 'todo.html', {'all_items1': all_items1}) here is my urls.py : path('post_detail_view/<str:content>/', views.post_detail_view, name='post_detail_view'), This is my modal code in todo.html <div class="modal-dialog" role="document"> <div class="modal-content"> <form action="/addTodo/" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabe2">Edit Info</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% if all_items1 %} <label for="content">Title :</label><br> <p>{{ all_items1.content }}</p> <p>{{ all_items1.data }}</p> <input type="text" id='c' name="content" value="{{ all_items1.content }}"/><br> <label for="data">Description :</label><br> <textarea id="data" rows="4" cols="50" value="">{{ all_items1.data }}</textarea> <br> <label for="tags">Tags :</label><br> <input type="tags" name="tags" value="{{ all_items1.tags }}"/><br> <a href="{{ all_items1.file.url }}"> {% load static %} <img src="{% static 'ico.png' %}" style="width:30px;height:30px" alt="download"> </a> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> {% endif %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save changes</button> </div> </form> </div> </form> </div> This code is not working. I can see modal is popping up but no data is displayed. I'm still learning Django. Can someone please … -
Populate a Django form field with data from a model
I'm have been struggling on this for 2 days, really. I want to populate Timesheet form field from Employees model as a select field / dropdown list. Here are my files and I tried so far. MODEL.PY class Employees(models.Model): # MONTHLY = 'MONTHLY' # SEMIMONTHLY = 'SEMIMONTHLY' # BIWKEEKLY = 'BIWKEEKLY' # WEEKLY = 'WEEKLY' # DAILY = 'DAILY' PAY_PERIODS = [ ('Monthly', 'Monthly'), ('Bi-weekly', 'Bi-weekly'), ('Weekly', 'Weekly'), ('Daily', 'Daily'), ] user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) is_active = models.BooleanField(default=True, verbose_name='Employee is actives') first_name = models.CharField(max_length=50, verbose_name='First Name.', null=True, blank=False) middle_name = models.CharField(max_length=50, verbose_name='Middle Name or Initials.', null=True, blank=True) last_name = models.CharField(max_length=50, verbose_name='Last Name.', null=True, blank=False) full_name = models.CharField(max_length=50, null=True, blank=True) phone = PhoneField(blank=True, null=True) email = models.EmailField(max_length=150, blank=True, null=True) state = USStateField(null=True, blank=True) street_address = models.CharField(max_length=150, blank=True, null=True, verbose_name='Street Address.') zip_code = models.CharField(max_length=50, blank=True, null=True, verbose_name='Zip Code.') hourly_rate = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) pay_frequency = models.CharField(max_length=100, choices=PAY_PERIODS, blank=True) hire_date = models.TimeField(auto_now_add=True) def __str__(self): return self.full_name def save( self, *args, **kwargs ): self.full_name = f'{self.first_name} {self.middle_name} {self.last_name}' super().save( *args, **kwargs ) class Timesheet(models.Model): """A timesheet is used to collet the clock-ins/outs for a particular day """ employer = models.ForeignKey(User, on_delete=models.CASCADE, null=True) full_name = models.CharField(max_length=100, null=True, blank=False, verbose_name='Select YOUR Name') start_date = … -
Why does Django perform UPDATE before INSERT when PK is None?
I've got a model with a UUID primary key: id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False, null = False, blank = False, help_text = 'The unique identifier of the Node.' ) The issue I'm trying to solve is that Django always seems to try an Update before an Insert. The Django Docs seem to be explicit on what the behavior should be: If pk is None then it will try an INSERT first, otherwise an UPDATE. When I create a ModelInstance, it autopopulates id with a UUID, so it's not none. Is there a way I can make it not do this? Regardless, even if I set id and pk to None on create, it still does an UPDATE first: my_totally_new_node = Node(data = data, id = None, pk = None) my_totally_new_node.id > None my_totally_new_node.pk > None reset_queries() my_totally_new_node.save() connection.queries > [{'sql': 'UPDATE "connection_p...::uuid", 'time': '0.002'}, {'sql': 'INSERT INTO "connect...::bytea)", 'time': '0.001'}] To summarize: Is there a way I can cause default behavior for the ID field to be not to populate on create, but to still populate on Save? Any ideas why Django isn't following the documented behavior when pk is None and is … -
HTML order list mess up with un-order list in django template
I have some data about users such as first name, last name, and email. Now I am trying to view it on the browser. But its ordering number is totally odd. My Template Code <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>User List</title> <link rel="stylesheet" href="{% static "css/mystyle.css" %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <div class="container"> <h1> Here is yours users: </h1> {% if user_info %} <ol> {% for user in user_info %} <li>{{ user.first_name }}</li> <ul> <li>First Name: {{ user.first_name }}</li> <li>Last Name: {{ user.last_name }}</li> <li>Email: {{ user.email }}</li> </ul> {% endfor %} </ol> {% endif %} </div> </body> </html> My View Code def userlist(request): user_info = UserInfo.objects.all() content = { "user_info":user_info, } print("User List") return render(request, "practiceApp/user-list.html", context=content) And My Browser enter image description here