Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple sub-fields attached to a field, and how to give the user the possibility of adding many of these fields
I am building a form in which users (composers) can add a composition. Within this form, alongside title, year, etc, they also add instrumentation. Each instrument can have a couple of properties, for example 'doubling', and the number of players. So, for instance: title: New composition instrumentation: violin doubled: no players: 1 viola doubled: yes players: 2 cello doubled: no players: 4 I have created three different models: one for instrumentation, one for the composition, and then one with a ManyToMany relation via a 'through'. models.py: class Composition(models.Model): title = models.CharField(max_length=120) # max_length = required INSTRUMENT_CHOICES = [('pno', 'piano'), ('vio1', 'violin_1(orchestral section)'), ('vio2', 'violin_2(orchestral section)'),] instrumentation = models.ManyToManyField('Instrumentation', through='DoublingAmount', related_name='compositions', max_length=10, choices=INSTRUMENT_CHOICES,) class Instrumentation(models.Model): instrumentation = models.CharField(max_length=10) class DoublingAmount(models.Model): DOUBLING_CHOICES =[(1, '1'),(2, '2'), (3, '3')] composition = models.ForeignKey(Composition, related_name='doubling_amount', on_delete=models.SET_NULL, null=True) instrumentation = models.ForeignKey(Instrumentation, related_name='doubling_amount', on_delete=models.SET_NULL, null=True) amount = models.IntegerField(choices=DOUBLING_CHOICES, default=1) forms.py: from django import forms from .models import Composition, Instrumentation class CompositionForm(forms.ModelForm): title = forms.CharField(label='Title', widget=forms.TextInput() description = forms.CharField() class Meta: model = Composition fields = [ 'title', 'instrumentation', ] views.py: def composition_create_view(request): form = CompositionForm(request.POST or None) if form.is_valid(): form.save() form = CompositionForm() context = { 'form': form } return render(request, "template.html", context) template.html: {{ form }} I … -
Django Upgrade Taking Forever
I am attempting to upgrade my Django version. I am currently on 1.10 and would like to get current with the version. I am following the recommendation in the docs to move one version at a time - so I have run pip install --upgrade django==1.11 and it currently says it is uninstalling Django 1.10. It has been doing this for nearly 2 hours now...this seems like an abnormal amount of time to me, but I've never done this before. Does it normally take this long? If not, might I have done anything wrong? It seems like a straightforward process to me. -
Django Template : Escape <script> tag only when showing RichText
I am currently developing a blog site with Django from scratch where people can write the description in a RichText Field where they can use HTML features like Bold, Italic. Heading, Add Image, Add URL etc. When rendering it from template I want to show all the tags as HTML. The only thing I want to escape is the script tag i.e. render something as something but alert("Hello world"); as <script> alert("Hello world"); </script> How can I do that? -
Serializer Method Field
I try to do hall booking app. I Have set up every things. the model and Serializer view set and urls. Now I want to return from this API 1. All halls with their booking table 2. All user Booking with hall name I try to SerializerMethodField to get all this data and it is working one side. for example, when I put SerializerMethodField in booking table ti give me the result as will as hall table. But when I try to put in both classes it give Error maximum recursion depth exceeded Model classes class HallModel(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hall_owner') name = models.CharField(max_length=100) price = models.FloatField() phone = models.CharField(max_length=9, blank=True) size = models.CharField(max_length=50) region = models.CharField(max_length=100) state = models.CharField(max_length=100) image_1 = models.ImageField(upload_to='halls_image') image_2 = models.ImageField(upload_to='halls_image') image_3 = models.ImageField(upload_to='halls_image') created_at = models.DateTimeField(auto_now_add=True) class BookingModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_booking') hall = models.ForeignKey(HallModel, on_delete=models.CASCADE, related_name='hall_owner') time_date = models.DateTimeField(auto_now_add=True) booking_method = models.IntegerField() Serializer class HallSerializer(serializers.ModelSerializer): booking = serializers.SerializerMethodField() class Meta: model = HallModel fields = '__all__' def get_booking(self, obj): booking = BookingSerializer(obj.hall_owner.all(),many=True).data return booking def perform_create(self, serializer): serializer.save() class BookingSerializer(serializers.ModelSerializer): hall = serializers.SerializerMethodField() class Meta: model = BookingModel fields = '__all__' def get_hall(self, obj): serializer_data = HallSerializer(obj.hall).data return serializer_data View Sets … -
IntegrityError at /admin/first_app/post/add/
I have four models in my models.py on django app 'first_app' which UserProfile Category Post Comment When I logon to the django admin to create a post I run into this error IntegrityError at /admin/first_app/post/add/ NOT NULL constraint failed: first_app_post.status Below is the Post model class Post(models.Model): post_title = models.CharField(verbose_name='Post Title', max_length=150) category = models.ManyToManyField(Category, verbose_name='Categories of Post') author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Author') post_img = models.ImageField(blank=True, null=True, upload_to='uploads/post_img', verbose_name='Post Image') create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) content = models.TextField() def publish(self): self.published_date = timezone.now() self.save() def approve_comment(self): return self.comments.filter(approve_comment=True) def __str__(self): return self.title On the error above 'NOT NULL constraint failed: first_app_post.status' I remember I created status field which I later deleted I did my python manage.py makemigrations first_app python manage.py migrate I also run this command to verify that the status field is successfully deleted but I still see it in the shell when I run the following commands python manage.py dbshell .schema --indent first_app_post CREATE TABLE IF NOT EXISTS "first_app_post"( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "post_title" varchar(150) NOT NULL, "status" varchar(50) NOT NULL, "post_img" varchar(100) NULL, "create_date" datetime NOT NULL, "published_date" datetime NULL, "content" text NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user"("id") DEFERRABLE INITIALLY … -
How to run my Django project on Apache server on exampp server?
I'm in localhost after running Apache and MySQL ; Xampp give me a Server Erorr(500) . in apache erorr.log there is a error . it is : ModuleNotFoundError: No module named 'digionline'\r, referer: http://localhost/ my code in httpd.conf: LoadModule wsgi_module "c:/users/hameds510/appdata/local/programs/python/python37/lib/sitepackages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIScriptAlias / "C:/Users/Hamed-S510/Desktop/hamed/digionline/wsgi.py" WSGIPythonHome "c:/users/hamed-s510/appdata/local/programs/python/python37" -
Vue code not updating in my Django/Vue Project
I added VueJS to my Django project using this guide. I am now trying to change the example to some code made by me, but nothing changes: assets/js/components/Demo.vue <template> <div> <p>This is just a Demo.</p> </div> </template> <script> </script> <style> </style> If i change this code, for example, to: <template> <div> <h1> test </h1> <p>TEST.</p> </div> </template> <script> </script> <style> </style> I will keep seeing the first snippet of code, in my frontend. Here is my index.js window.$ = window.jQuery = require('jquery'); require('bootstrap-sass'); import Vue from 'vue'; import Demo from "./components/Demo.vue"; window.Vue = Vue; const app = new Vue({ el: '#app', components: { Demo } }); And here is my Django template, from where Vue is called: {% load render_bundle from webpack_loader %} <html lang="en"> <head> <meta charset="UTF-8"> <title>My Django Vue</title> </head> <body> <h1>test</h1> <div id="app"> <demo></demo> </div> {% render_bundle 'main' %} </body> </html> The other parts of my Vue/JS code are basically the same of this repository, since i followed the guide https://github.com/michaelbukachi/django-vuejs-tutorial Am i missing something in my console, maybe? Should i update in some way my JS/Vue code? Any help is appreciated, thanks in advance! -
Web Scraping in Django: running scraper every day to update database or running a specific scraper for every user?
I have a project idea: a website where a user could enter search details (city, keywords, etc.) and then receive periodical job offer emails. I would like to hear your opinion on how the scraper part should work: Should I run a scraper every day? It would go through the pages of the website, building a database. Then filter the database specifically for the user and send an email with the result. Or should I build a specific scraper for every user? Every scraper would only take the information that is needed for a particular user from the website. As far as I understand django-dynamic-scraper package would fit, but it does not support the newest django version. What are your thoughts on this? Maybe there are simpler ways to implement this project? -
Unable to content Django form with extended user model
Trying to connect Django form and extended user model, but struggling to get the form to save. Basically, I'm able to authenticate user, but not save information to the CustomUser model or "profile" model for the user. I feel like I fundamentally don't understand how to extend the user model, so if you have some advice to that affect that would be very helpful. #views.py def registration(request): if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): custom = form.save(commit=False) user = request.user custom = user.profile() custom.key = "".join(random.choice(string.digits) for i in range(20)) custom.save() username = form.cleaned_data['username'] password = form.cleaned_data['password2'] user = authenticate(request, username=username, password=password) messages.success(request, f'Your account has been created! Please proceed to agreements and payment.') return redirect('other_page') else: form = CustomUserCreationForm(request.POST) return render(request, 'registration.html', {'form': form}) Here is my models.py class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) key = models.CharField(max_length=25, null=True, blank=True) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) username = models.CharField(max_length=25) password1 = models.CharField(max_length=25) password2 = models.CharField(max_length=25) @receiver(post_save, sender=User) def create_custom_user(sender, omstamce, created, **kwargs): if created: CustomUser.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): if instance.CustomUser.save() def __str__(self): return f'{self.first_name} ({self.last_name})' In settings.py I added "AUTH_PROFILE_MODULE = 'app.CustomUser'". However, I'm getting this error: AttributeError: 'User' object has no attribute 'profile' -
Django datatable error - DataTables warning: table id=datatable - Ajax error
I am using datatables in Django. But when i include related data in my datatable, search function display a pop error "DataTables warning: table id=datatable - Ajax error." At the same time i also receive this error in terminal "File "C:\Dev\virenvmt\lib\site-packages\django\db\models\sql\query.py", line 1107, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) " My model is class Location(models.Model): name = models.CharField (max_length=50, null=False, blank=False, unique= True) status = models.IntegerField(blank=False, default='1') created_date = models.DateTimeField(default=datetime.now, blank=False) created_by = models.IntegerField(blank=False) updated_date = models.DateTimeField(blank=True) update_by = models.IntegerField(blank=True) def __str__(self): return self.name class Devices(models.Model): name = models.CharField (max_length=50, null=False, blank=False, unique= True) phone_number = models.CharField (max_length=20, blank=True, unique=True) location = models.ForeignKey(Location, on_delete=models.DO_NOTHING, null=False, blank=False) status = models.IntegerField(blank=False, default='1') ip_address = models.CharField(max_length=15, null=False, blank=False, unique=True) power_status = models.IntegerField(blank=True, default='0') created_date = models.DateTimeField(default=datetime.now, blank=False) created_by = models.IntegerField(blank=False) updated_date = models.DateTimeField(blank=True) update_by = models.IntegerField(blank=True) My Javascript file is $(document).ready(function() { var dt_table = $('#datatable').dataTable({ columns: [ {"dt_table": "name"}, {"dt_table": "location"}, {"dt_table": "phone_number"}, {"dt_table": "ip_address"}, {"dt_table": "power_status", "render": function (data, type, row) { return (data === '1') ? '<span class= "badge badge-success icon-flash_on r-20">&nbsp;On</span>' : '<span class="badge badge-danger icon-flash_off blink r-20">&nbsp;Off</span>';} }, { "dt_table": "id", "orderable": false, // "defaultContent": "<a class=\"btn-fab btn-fab-sm btn-primary shadow text-white\"><i class=\"icon-pencil\"></i></a>", "targets": -1, 'render': … -
DJANGO - Static files are being collected, but they don't want to work on local server
as a newbie in Django I'm struggling with the staticfiles within my project. Whenever I take some prepared bootstrap template something is not working, same when I try to add some javascript - and have no idea why. I tried to find the answer before, but in theory, everything should work - would be awesome if someone could guide me, cuz I feel completely lost now. Everything works fine until I want to use some advanced js/css animations. It looks like in the image - the main background doesn't load, the navibar is shattered as well... My settings I think look fine - Django collect all the static files, but they don't want to work on the local server. Everything is rooted in views.py/urls.py (settings.py) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') `<!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <title>BizPage Bootstrap Template</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="" name="keywords"> <meta content="" name="description"> <!-- Bootstrap CSS File --> <link href="{% static 'lib/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Libraries CSS Files --> <link href="{% static 'lib/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet"> <link href="{% static 'lib/animate/animate.min.css' %}" rel="stylesheet"> <link href="{% static 'lib/ionicons/css/ionicons.min.css' %}" rel="stylesheet"> <link href="{% static 'lib/owlcarousel/assets/owl.carousel.min.css' … -
How to show assigned members its balance in html page?
I have assigned some random numbers as a balance to every user who sign up but I am not able to show them in html page. How to do it? Maybe I have made some mistakes in python files also. I have added those numbers(balance) in my database. So please let me know and correct my mistake. models.py class Payment(models.Model): payment_numbers = models.CharField(max_length=100) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py def payment(request): receiving1 = Payment.objects.filter(owner=request.user) for field in receiving1: field.payment_numbers context = { 'receiving1': receiving1 } return render(request, 'index.html', context) HTML page {% for numbers1 in receiving1 %} {% if numbers1 %} <li style="float: right;">Your Balance: Rs. {{numbers1.payment_numbers}}</li> {% endif %} {% endfor %} -
ImportError: Couldnt import Django ... Did you forget to activate a virtual environment?
I know there are several questions/answers about this but I cant figure out what I should do. So I wanted to get started with Django and installed it with pip install and added Python37 and Python37-32 to my enviromental variables and it I guess it worked because I can run several python commands in my shell. But everytime I try to python manage.py runserver it gives me an Error. I also set up my virtual environment and activated it but I think theres a problem with Django. But because I installed it with pip install django I know its there and I can use commands like django-admin startapp ... So I guess Django is working. I dont rlly know what PYTHONPATH means and where to find it. Would be pretty nice if anybody could take a look at my error. Here you can see that Django is installed : # **C:\Users\Kampet\Desktop\Python-Django\mysite>pip install django Requirement already satisfied: django in c:\users\kampet\appdata\local\programs\ python\python37-32\lib\site-packages (2.2.4) Requirement already satisfied: pytz in c:\users\kampet\appdata\local\programs\py thon\python37-32\lib\site-packages (from django) (2019.2) Requirement already satisfied: sqlparse in c:\users\kampet\appdata\local\program s\python\python37-32\lib\site-packages (from django) (0.3.0)** # And thats my error **C:\Users\Kampet\Desktop\Python-Django\mysite>python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main … -
Why does my django pagination keeps returning the same items infinitely?
I am using django and ajax to create a infinite scroll on my website. I would like it to load more items from the database (that are in the next page) when the user scrolls to the bottom of the page. Everything is working perfectly except that it keeps returning the first page's items infinitely. For example if a user scrolls down to the end of a page instead of adding page 2's elements it just add the same elements from the first page to the bottom again. I am very sure this issue is from my views.py. I can't seem to figure out what's wrong. def feed(request): queryset2 = Store_detail.objects.filter(store_lat__gte=lat1, store_lat__lte=lat2)\ .filter(store_lng__gte=lng1, store_lng__lte=lng2) queryset3 = Paginator(queryset2, 4) page = request.GET.get('page',1) try: queryset = queryset3.page(1) except PageNotAnInteger: queryset = queryset3.page(page) except EmptyPage: queryset = "" context = { "location":location, "queryset":queryset, } # return HttpResponse(template.render(context,request)) return render(request, 'main/feed.html', {'queryset': queryset, 'location':location,}) So basically I would like to load the next page when a user scrolls to the end of the screen and if there are no more items in the next page or the next page does not exist then stop adding items. -
Converting to and from CamelCase within DRF
I am making a SOAP post request which returns data in CamelCase. I need to refactor the response back from SOAP request into snake_case. Then again I receive a request from a Restful API in snake case which I need to convert into CamelCase and then send a SOAP request. I have a mini serializer which I wrote to convert between the two, i.e. extended the to_representation method and then returned the respective CamelCase or snake_case, however I'm not sure if this mini serializer is a good way of doing it, should maybe be a helper function than serializer? Here is the serializer converting a list of objects containing name and attribute_given keys into CamelCase. class ToCamelCase(serializers.Serializer): name = serializers.CharField() attribute_given = serializers.CharField() def to_representation(self, value): data = [] for x in range(len(value)): data.append({ 'Name': value['name'], 'AttributeGiven': value['attribute_given'], }) return data I'm just looking for the best approaching solving this. Is solving this by extending the to_representation and returning custom key name at serializer level a good way or shall I write a helper function for it? -
Unable to create the django_migrations table with DateTime Field
I was migrating my Django app from local system to production server. Configurations on local server are as below: Django2.2 MySQL 5.7.27-0ubuntu0.16.04.1 mysqlclient-1.4.2.post1 sqlparse-0.3.0 On production server, configurations are as below: Django2.2 MySQL 5.5.53 mysqlclient-1.4.2.post1 sqlparse-0.3.0 Only difference between local and production configurations is of MySQL server version. There is a model with below code: class Tracking404Model(models.Model): url = models.CharField(max_length=512, null=False, blank=False) timestamp = models.DateTimeField(null=False, blank=False) After running migration, I ran the commnd python manage.py sqlmigrate app-name migration-file-number to check MySQL syntax generated, which is as below: CREATE TABLE `404_tracking` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `url` varchar(512) NOT NULL, `timestamp` datetime(6) NOT NULL); Show create table statement output on Local: mysql> show create table 404_tracking\G *************************** 1. row *************************** Table: 404_tracking Create Table: CREATE TABLE `404_tracking` ( `id` int(11) NOT NULL AUTO_INCREMENT, `url` varchar(512) NOT NULL, `timestamp` datetime(6) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 1 row in set (0.00 sec) Migrations ran just fine on local, tables were created and I was able to perform all mysql operations. Basically everything was just fine. When running migrations on production, I am getting below error: raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable … -
How to send signal from django to java script trigger
I want create a signal in my django and javascript can find out this signal and do specific action. -
html data is not rendering property in html using python django
i could not display the html data sent from python in the html page. when i open the html in view source mode, it thing data is rendered as messed html code <table border="1"> <tr> <th>servername</th> <th>cpu</th> <th>memory</th> <th>cdrivespace</th> <th>ddrivespace</th> <th>fdrivespace</th> <th>gdrivespace</th> <th>pdrivespace</th> <th>kdrivespace</th> {{ data }} </table> python view data = callFileReaderMain( form.cleaned_data['session_key'] ) return render(request,'marketplace_output.html',{'data' : data }) view source code <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>marketplace output server details</title> </head> <body> <table border="1"> <tr> <th>servername</th> <th>cpu</th> <th>memory</th> <th>cdrivespace</th> <th>ddrivespace</th> <th>fdrivespace</th> <th>gdrivespace</th> <th>pdrivespace</th> <th>kdrivespace</th> &lt;tr&gt;&lt;td&gt;W01GCTIAPP01A&lt;/td&gt;&lt;td&gt;3.0&lt;/td&gt;&lt;td&gt;93.0&lt;/td&gt;&lt;td&gt;42.0&lt;/td&gt;&lt;td&gt;40.0&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt; </table> </body> </html> -
import django.http from HttpResponse ^ SyntaxError: invalid syntax
I am trying to run this but getting syntax error import django.http from HttpResponse ^ SyntaxError: invalid syntax import django.http from HttpResponse def index(request): return HttpResponse("Hello") -
Efficient replacement of source urls with django static urls
In django when we load image we use tag something like this: <img alt="background" src="{% static "img/inner-6.jpg" %}" /> and I use templates and build backend to those templates to learn django (for now) so when I start project all the images source urls and css file urls and javascript urls are given like : <img alt="background" src="img/inner-6.jpg" /> so I have to replace all of them with the above one which is time consuming and non-productive. Can someone please tell me the efficient way to do this (like notepad text replacement system or something like that). How do experience django developers deal with this kind of problems? Thanks in advance. (I have searched a lot about it before asking on stackoverflow but couldn't find anything) -
Django is complex select query possible for this?
I have the following model used to store a bidirectional relationship between two users. The records are always inserted where the smaller user id is user_a while the larger user id is user_b. Is there a way to retrieve all records belonging to a reference user and the correct value of the status based on whether the reference user id is larger or smaller than the other user id? Perhaps two separate queries, one where reference user = user_a and another where reference user = user_b, followed by a join? class Relationship(models.Model): RELATIONSHIP_CHOICES = ( (0, 'Blocked'), (1, 'Allowed'), (-2, 'Pending_A'), (2, 'Pending_B'), (-3, 'Blocked_A'), (3, 'Blocked_B'), ) user_a = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, related_name='user_a',null=True) user_b = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, related_name='user_b',null=True) relationship_type = models.SmallIntegerField(choices=RELATIONSHIP_CHOICES, default=0) -
How to fetch the selected dropdown values in the editable form in the dropdown using django
Dropdown value is stored in separate table,how to retrieve the dropdown value in the editable form views.py def edit(request, id): form = DeptForm(request.POST) form1 = DesigForm(request.POST) dt = Department.objects.all() dg = Designation.objects.all() dept = request.POST.get("depart") Department.id = dt desig = request.POST.get("design") Designation.id = dg print(Designation) edit_record = Emp_Profile.objects.get(pk=id) print(edit_record) context = { 'edit_record': edit_record } print(context) print(edit_record.department) return render(request, 'registration/register_edit.html', context,{'form' : form, 'form1' : form1}) def update(request, id): form = DeptForm(request.POST) form1 = DesigForm(request.POST) dt = Department.objects.all() dg = Designation.objects.all() if request.method == "POST": First_name = request.POST['First_name'] lname = request.POST['lname'] depart = request.POST.get("depart") Department.id = dt print(depart) uname = request.POST['uname'] design = request.POST.get("design") Designation.id = dg print("design") print(design) mnumber = request.POST['mnumber'] Emp_Profile.objects.filter(pk=id).update( first_name=First_name, last_name=lname, Mobile_Number=mnumber, username=uname, ) return redirect('/accounts/profile/') return render(request,'register_edit.html',{'form':form, 'form1':form1}) In this department and designation is two separate table,while storing it is stored in another table called "Emp_Profile".while editing,the selected value of department and designation should come with dropdown. -
How to retrieve the save checkbox value in the editable form in django
Data is save to DB, Retrieve the data in enabled checkbox. How can I write code for edit the form in views.py file In models username field is the foreign key of Emp_Profile model and Process is the foreign key of Client_Process table Models.py class Emp_Process(models.Model): username = models.ForeignKey(Emp_Profile, on_delete=models.CASCADE) process = models.ForeignKey(Client_Process, on_delete=models.CASCADE) class Meta: db_table : 'emp_process' html file {% extends 'client_pannel.html' %} {% block content %} <br><br> <br><br> <div class="data-table-area mg-b-15"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="sparkline13-list"> <div class="sparkline13-hd"> <div class="main-sparkline13-hd"> <label>{{ emp.first_name }} {{ emp.last_name }} - {{ emp.designation }}</label> </div> </div> <div class="sparkline13-graph"> <div class="datatable-dashv1-list custom-datatable-overright"> <table id="table" data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true" data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true" data-toolbar="#toolbar"> <thead> <tr> <th >Client</th> <th>Process</th> </tr> </thead> <tbody> {% for client in form %} <tr> <td> <input type="checkbox" name="cname[]" value="{{ client.id }}"> {{ client.Name }} </td> <td> {% for process in client.clients %} <input type="checkbox" name="process[]" value="{{ process.id }}"> {{ process.process }}<br /> {% endfor %} </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> </div> </div> {% endblock %} -
How to solve the datetime.datetime issue after running migrate in django?
Whenever I run python manage.py migrate, I get following error. How to resolve this issue? I am not understanding. Error value = self.get_prep_value(value) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\models\fields\__init__.py", line 966, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' __init__.py def get_prep_value(self, value): from django.db.models.expressions import OuterRef value = super().get_prep_value(value) if value is None or isinstance(value, OuterRef): return value return int(value) -
unable to install Django 2.2.4 for python3.7.4 on Linux mint 19.1
I want to install Django web framework version 2.2.4 on the Linux.I'm using Linux mint 19.1 with python2(default), python3.6.8(default) and python3.7.4(sudo installed from source). I am using command 'pipenv --python3.7 install django==2.2' to install but it's not working. I tried this tutorial to install Django- link to the youtube tutorial $ python3.7 -V Python 3.7.4 $ pip3 -V pip 19.2.1 from /usr/local/lib/python3.7/site-packages/pip (python 3.7) ~ dev/try_django$ pipenv --python3.7 install django==2.2.4 Usage: pipenv [OPTIONS] COMMAND [ARGS]... Try "pipenv -h" for help. Error: no such option: --python3.7