Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django optional URL captured value
For following Django code: class PollMessageView(generics.ListAPIView): serializer_class = MessageSerializer lookup_url_kwarg = 'count' def get_queryset(self): count = self.kwargs.get(self.lookup_url_kwarg) queryset = Message.objects.all()[:count] return queryset urlpatterns = [ path('poll_message/<int:count>', PollMessageView.as_view(), name="poll_message"), ] How do I make the count parameter optional in the URL pattern? For example, if I visit /poll_message/ without a count, it would still call the PollMessageView (and I can set a default number for count if it's missing)? -
Django Circular Dependency error on two independent apps models that depend upon model from another app
So here is my problem. I got three django apps. paper,feeds,activity. Activity has model defined as: from django.db import models from django.contrib.auth.models import User from django.db.models import Q class Tag(models.Model): name = models.CharField(max_length=20) Paper has following model. from django.db import models from django.contrib.auth.models import User from activity.models import Tag class Paper(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) published_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length=200) tag = models.ManyToManyField("activity.Tag") & feeds has following model. from django.db import models from django.contrib.auth.models import User class Feeds(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) published_at = models.DateTimeField(auto_now=True) text = models.CharField(max_length=1000) tag = models.ManyToManyField("activity.Tag") While running makemigrations it is giving me error of django.db.migrations.exceptions.CircularDependencyError: paper.0001_initial, activity.0001_initial The migration of activity is class Migration(migrations.Migration): initial = True dependencies = [ ('paper', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('feeds', '0001_initial'), ] Any ways to solve this issue? I am not that experienced with database and stuffs. Any help would be highly appreciated. Better if it has explanation to the answer too. :p -
Why owl carousel not working in my Django template?
Here is my template <div class="home"> <!-- Home Slider --> <div class="home_slider_container"> <div class="owl-carousel owl-theme home_slider"> <!-- Slide --> <div class="owl-item"> <div class="background_image" style="background-image:url(images/home_slider.jpg)"> </div> <div class=" home_slider_content_container"> <div class="container"> <div class="row"> <div class="col"> <div class="home_slider_content"> <div class="home_title"> <h2>Let us take you away</h2> </div> </div> </div> </div> </div> </div> </div> here is the static URL STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') already executed collectstatic command I think there is a problem with background-image:url() css also done {{% load static %}} why the js plugin not working, expecting help from experts -
Login doesn't work and says NoReverseMatch at /basic_app/user_login/ but registration seems to work fine with similar url pattern and template tagging
I couldn't find the solution to this problem, not even in Stack Overflow. Same question was asked but I could not find a definite answer. Code in views.py: from django.shortcuts import render from basic_app.forms import UserForm, UserProfileInfoForm # For Login from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import login, logout, authenticate from django.urls import reverse from django.contrib.auth.decorators import login_required def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username='username', password='password') if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: HttpResponse("ACCOUNT IS NOT ACTIVE! PLEASE REGISTER FIRST!") else: print('Someone tried to login $ failed!') print('Username: {} and Password: {}'.format(username, password)) return HttpResponse('INVALID USERNAME AND/OR PASSWORD') else: return render(request, 'basic_app/login.html', {}) And the code in base.html with link to get to login page: {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'user_logout' %}" >Logout</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'basic_app:user_login' %}" >Login</a> </li> {% endif %} This is the code in urls.py: from django.urls import path from basic_app import views app_name = 'basic_app' urlpatterns = [ path('', views.index, name='index'), path('register/', views.register, name='register'), path('user_login/', views.user_login, name='user_login'), ] -
Django many to one api for React js
I am really new in Django and it relationships. I have made one small Ecommerce models. In my models there are customer, products, product-tags and orders. product and product-tags have many to many relationship. In Order model many-to-one relationship with customer and Product. I think my relationship model looks good. I have made api end points for React frontend. Where I want to pull specific single customer's specific product order. I saw in Django documentation _set.all() and but still I could not able to get the customer specific order. In my React frontend the order-list-image and customer-list-image looks like this. I want to pull customer's order list. But could not able to do that. I share my code in Gitlab This is django models # ################## # ##### MODELS ##### # ################## from __future__ import unicode_literals from django.db import models class Customer(models.Model): name = models.CharField(max_length=200, null= True) email = models.CharField(max_length=20, null=True) phone = models.CharField(max_length=20, null=True) date_created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tag(models.Model): name= models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY=( ('Indoor', 'Indoor'), ('Outdoor', 'Outdoor'), ) name= models.CharField(max_length=200, null=True) price= models.FloatField(null=True) category=models.CharField(max_length=200,null=True, choices=CATEGORY) description= models.CharField(max_length=200,null=True, blank= True) date_created=models.DateTimeField(auto_now_add=True, null=True) tags= models.ManyToManyField(Tag) def __str__(self): return self.name class Order(models.Model): STATUS … -
how to keep show data when i use ' Show more / hide Button ' more than once not once time in - Django & JavaScript
how to keep show data when i use ' Show more / hide Button ' more than once not once time in JavaScript my question how i can keep show more button work after it show all data at first time , i mean when user press on show more button and it show all item then he press on ' hide button' it will hide all posts right? then user want show data again and press on show more again it must show data again why here don't do that ? i want keep show data and hide it many times not once html page : {% for tech in techhome %} <div class="contact"> <div class="card-deck"> <div class="card mb-3" style="max-width: 800px;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="Tech/{{ tech.slug }}"><img style="height:100%;width:100%;border-radius:6.5px;" src="{{ tech.get_image }}" class="rounded float-right" alt="..."></a> </div> <div class="col-md-8"> <div class="card-body"> <a href="Tech/{{ tech.slug }}"> <h5 class="card-title" id="primary_site_pages_app_name_control"> <b>{{ tech.name }}</b></h5></a> <p class="card-text" id="font_control_for_all_pages">{{ tech.app_contect|truncatechars_html:153|safe}}</p> </div> <div class="card-footer"> <small class="text-muted" id="date_post_control">{{ tech.post_date}}</small> <small class="firstsmall"><a class="bg-orange" href="{% url 'tech' %}" id="tag_name_control">مقالات تنقية</a></small> </div> </div> </div> </div> </div> </div> {% endfor %} <!-- show more button --> <div class="text-center mt-4"> <a role="presentation" type="button" class="btn btn-lg loadMore" style="width:30%;color:white;background-color:#7952b3">show more </a> </div> … -
Multiple User Login Django
I have my Django application where I need 5 different types of users- Customer, Assistant, ProductsAdmin, ProductSeller, BaseAdmin next I want that a single login page should be used where the user enters his email and password and then gets redirected to his page, I have seen only limited to two user roles tutorials and blogs is this even possible in any way I am just a beginner so just wanted to ask this/ -
How can I handle multiple forms on one page using the DRY method
I have a total of 10 forms I need to display. I am using a DetailView to display them and a CreateView to handle their logic. So far my views.py looks like this: from .forms import ( WeightRepsModelForm as wr_form, WeightDistanceModelForm as wd_form, WeightTimeModelForm as wt_form, RepsDistanceModelForm as rd_form, RepsTimeModelForm as rt_form, DistanceTimeModelForm as dt_form, WeightModelForm as w_form, RepsModelForm as r_form, DistanceModelForm as d_form, TimeModelForm as t_form, ) class ExerciseDetailView(DetailView): model = Exercise template_name = 'workouts/types.html' def get_context_data(self, **kwargs): context = super(ExerciseDetailView, self).get_context_data(**kwargs) context['wr_form'] = wr_form context['wd_form'] = wd_form context['wt_form'] = wt_form context['rd_form'] = rd_form context['rt_form'] = rt_form context['dt_form'] = dt_form context['w_form'] = w_form context['r_form'] = r_form context['d_form'] = d_form context['t_form'] = t_form return context class WeightRepFormView(CreateView): form_class = wr_form def form_valid(self, form): form.instance.exercise_id = self.kwargs['pk'] return super().form_valid(form) def get_success_url(self): return reverse('workouts:exercise_detail', kwargs={'pk': self.kwargs['pk']}) This works fine for the first form but I would need to create 10 near identical CreateViews in order to continue with this method. Is anyone able to recommend a more efficient way of doing this? -
for security reasons, How to prevent code modifications in python?
We know that MettaClasses can do Black magic to any module (running or not), therefore the hackers can use their metaclasses to modify any code within a module or even within an entire project -
profiling api with django, gunicorn and threadpool
I have an API to do the below operations. I am using python, Django framework and gunicorn/nginx for deployment. API has deployed in AWS lightsail. Request will come in for every 2secs. receives data from the client. creates record in local SQLite database and sends response. runs task asynchronously in thread. (running in thread). Entire task takes about 1 sec on average. a. gets the updated record from step 2 with ID. (0 sec) b. posts data to another API using requests. (.5 secs) c. updates to database (AWS RDS) (.5 secs) Setup: I have ThreadPoolExecutor max_workers=12. gunicorn has one worker as the instance has 1vCPU. I don't use gunicorn workers with threads, since I have to perform some other task within the api. The reason asyncio is used was that base update in Django is not supported with this. So I kept the post API in the threading itself. Each request will be unique. No same request. Even If I keep max_worker to 1 in threadpool, it is bursting 10% mark in AWS 5$ instance. API only receive request for every 2secs. I am not able to profile this situation where it is causing the CPU usage. There are … -
React native Axios Django - Csrf failed referer checking failed no referer
I am calling a Django back-end api from React front-end using axios. For that api which is login api, I am using Django Knox package in logic. React.js - I am calling axios.request(method, url, data) and the api call is working correctly. When I went to Developer tools>Network, I can see Referer header set to React.js website in request header and no other csrf-related header. In Response headers I can see two set-cookie headers, csrftoken and sessionid. React Native - same way I am calling api but api returns error csrf failed referer checking failed - no referer . When I checked response.config, Referer header is not set unlike React.js Curl - works fine httpie - works fine How can I get rid of this error. Note 1 - My Django back-end is based on api token logic and not csrf in any way. Note 2 - React.js and Django are hosted on different domains. I am facing error in React Native which is in debug mode. -
How do i save a message to database in consumers.py
I followed the channels documentation to create a chat app. I've created a Message model and a model form, but when i type in a message and click send, it responds accordingly but the message doesnt save to database. I want the message to save when I click send. I believe I'm supposed to write a save method in consumers.py but I'm not sure of how to do that. views.py from .forms import MessageForm def index(request): return render(request, 'chat/index.html') def room(request, room_name): if request.method == 'POST': form = MessageForm(request.POST, request.FILES) if form.is_valid(): message = form.save(commit=False) message.user1 = request.user message.save() else: form = MessageForm() return render(request, 'chat/room.html', { 'room_name': room_name, 'form': form }) consumers.py from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Message class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send … -
TypeError at /updateTodo/7/ Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken':
I was trying to update a form for my Todo App, it showed the form instance and all but when i tried to update it, I got this weird error. Internal Server Error: /updateTodo/7/ Traceback (most recent call last): File "C:\Dev\btre_project\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'QueryDict' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Dev\btre_project\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Dev\btre_project\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Dev\btre_project\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Eyimofe Ayo Pinnick\Desktop\Published\todo\core\views.py", line 79, in updateTodo form = TodoForm(request.POST, instance=todo) File "C:\Users\Eyimofe Ayo Pinnick\Desktop\Published\todo\core\forms.py", line 36, in __init__ self.fields["category"].queryset = Category.objects.filter(user=user) File "C:\Dev\btre_project\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Dev\btre_project\venv\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Dev\btre_project\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Dev\btre_project\venv\lib\site-packages\django\db\models\sql\query.py", line 1351, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Dev\btre_project\venv\lib\site-packages\django\db\models\sql\query.py", line 1378, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Dev\btre_project\venv\lib\site-packages\django\db\models\sql\query.py", line 1312, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Dev\btre_project\venv\lib\site-packages\django\db\models\sql\query.py", line 1166, in build_lookup lookup = lookup_class(lhs, … -
Systemd process boot order using saltstack
I need to specify a boot order for processes to start. I have supervisor and etcd running on Debain. Supervisor process is used to start django sever eventually, but my django server needs etcd to be up to work properly. How can I have the etcd to be up, then supervisor? Can this be done through salt states? I want this order because if supervisor start django service before etcd is up, it breaks things. I have enabled etcd to start with systemctl enable etcd.service. I have also enabled supervisor with systemctl enable supervisor.service -
unicode decode error from mySQL for emojis when the Django queryset is converted to a list
I am on Django 1.11 and python 3.6. I need to convert a Django queryset into a list. The objects in the queryset have a field with a unicode emoji value. (see: field=u'✅ This is the field value') That particular table and field in mySQL are using utf8mb4_unicode_ci encoding. When I run qs_list = list(qs), MySQL throws a Unicode error which I think is caused by the emoji in the field when the queryset is evaluated. File encoding: # -*- coding: utf-8 -*- from __future__ import unicode_literals Queryset: qs = Fake.objects.filter(..) qs_list = list(qs) Error: <class 'UnicodeDecodeError'> Exception: 'utf-8' codec can't decode byte 0xed in position 11: invalid continuation byte File "/home/mysite/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/home/mysite/lib/python3.6/site-packages/django/db/models/query.py", line 1121, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/mysite/lib/python3.6/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/home/mysite/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 899, in execute_sql raise original_exception File "/home/mysite/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 889, in execute_sql cursor.execute(sql, params) File "/home/mysite/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/mysite/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "/home/mysite/lib/python3.6/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/home/mysite/lib/python3.6/site-packages/MySQLdb/cursors.py", line 317, in _query self._post_get_result() File "/home/mysite/lib/python3.6/site-packages/MySQLdb/cursors.py", line 352, in _post_get_result self._rows = self._fetch_row(0) File "/home/mysite/lib/python3.6/site-packages/MySQLdb/cursors.py", line 325, in _fetch_row … -
Show more / hide Button | keep show data and hide more than once not once time in JavaScript
my question how i can keep show more button work after it show all data at first time , i mean when user press on show more button and it show all item then he press on ' hide button' it will hide 5 posts right? then user want show data again and press on show more again it must show data again why here don't do that ? i want keep show data and hide it many times not once html page : {% for tech in techhome %} <div class="contact"> <div class="card-deck"> <div class="card mb-3" style="max-width: 800px;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="Tech/{{ tech.slug }}"><img style="height:100%;width:100%;border-radius:6.5px;" src="{{ tech.get_image }}" class="rounded float-right" alt="..."></a> </div> <div class="col-md-8"> <div class="card-body"> <a href="Tech/{{ tech.slug }}"> <h5 class="card-title" id="primary_site_pages_app_name_control"> <b>{{ tech.name }}</b></h5></a> <p class="card-text" id="font_control_for_all_pages">{{ tech.app_contect|truncatechars_html:153|safe}}</p> </div> <div class="card-footer"> <small class="text-muted" id="date_post_control">{{ tech.post_date}}</small> <small class="firstsmall"><a class="bg-orange" href="{% url 'tech' %}" id="tag_name_control">مقالات تنقية</a></small> </div> </div> </div> </div> </div> </div> {% endfor %} <!-- show more button --> <div class="text-center mt-4"> <a role="presentation" type="button" class="btn btn-lg loadMore" style="width:30%;color:white;background-color:#7952b3">show more </a> </div> <!-- hide --> <div class="text-center mt-4"> <a role="presentation" type="button" class="btn btn-lg" id="hide" style="width:30%;color:white;background-color:#7952b3"> hide 5 posts </a> </div> <br> <script> // this for … -
Forward traffic to default upstream server nginx django
I want to route traffic from a client through my firewall host. The process flow will be like this: Client computer >>> my firewall host>> my web server. I followed this tutorial as I'm also hosting my servers on Digitalocean. I was able to get it done. but my problem is making it have full access to my django site powered with gunicorn. When I curl my firewall ip address it will hit my web server and return the default nginx homepage message. Now, instead of returning the nginx default page, I want to return my django homepage. I tried adding location / {proxy_pass: http://upstream_server } it returned 400 bad request. But when i call stage.example.com directly everything works fine. My conf file looks like this. upstream example_app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Gunicorn master nukes a # single worker for timing out). server unix:/var/www/example.com/fend/run/examd.sock fail_timeout=0; } server { server_name stage.example.com; index index.html index.htm index.php; location = /favicon.ico { access_log off; log_not_found off; } access_log /var/www/example.com/logs/access.log; error_log /var/www/example.com/logs/error.log; client_max_body_size 20M; location / { include proxy_params; proxy_pass http://example_app_server; proxy_intercept_errors on; uwsgi_read_timeout 500s; keepalive_timeout … -
Django Cumulative Group By
I'm trying to get the cumulative of a field called 'pl' by another field called 'prediction__fixture__date'. The 'pl' field is a FloatField and the 'prediction__fixture__date' field is a DateTimeField. I wrote the following code: Tip.objects.filter(channel__name__contains="Premium").annotate(cum_pl=Window(Sum('pl'), order_by=F('prediction__fixture__date__date').asc())).values("cum_pl", "prediction__fixture__date__date").order_by("prediction__fixture__date__date") This code returns the cumulative of the field 'pl' per Tip (the entity to which 'pl' belongs). How do I fix this? -
Django loading on the same page after selecting filter
I have a submit button on if I click after selecting checkboxes, the results show up on a different webpage but I want the results to show on the same page which has the submit button. I want the webpage to load inside a .. on the same page itself. Any idea on how to handle this when your website is on Django? -
Configure Apache/Django on elastic beanstalk to address INVALID_HOST errors
Background: Current setup is Have a website hosted in AWS S3 (e.g. app.com) Have api server hosted in elastic beanstalk (e.g. api.com) Website makes api requests to api server ALLOWED_HOST has been set in Django so that it includes The elastic beanstalk address The url for the api Issues: The web app is working fine. However, I am seeing numerous requests to the api from random urls (bots, exploits, etc). This is firing off hundreds of Invalid HTTP_HOST header errors. I could obviously turn off the error notification, but that does not feel right. The log suggests adding bunch of ip addresses to the ALLOWED_HOST, most of which is the ip address of my load balancer. However, as my regular api requests are going through without problem, I doubt adding the IP address of load balancer to ALLOWED_HOST is the solution either. So that would leave changing the load balancer itself so that it does not direct requests to Django if it is invalid. I have found a few answer with regards to this such as How to disable Django's invalid HTTP_HOST error? Django Invalid HTTP_HOST header on Apache - fix using Require? Two questions: Is the above modification the … -
A question about django and MyModel_meta.get_fields()
I have used the sentence Scenario._meta.get_fields() in order to get a list of all fields of my model class called Scenario. I printed the list and i saw there are two types of fields: Some of them are like <ManyToOneRel: sizigia.demand> and other like <django.db.models.fields.related.OneToOneField: parent>. I want to create a list with only "django.models" fields like <django.db.models.fields.related.OneToOneField: parent>. How can i do that with a simple sentence? -
python3 manage.py runserver does not work without specifying the localhost
Earlier when I executed, python3 manage.py runserver It used to start the server at my localhost http://127.0.0.1:8000/ but somehow it isnt doing so now, when I type it in now and press enter, nothing happens and the cursor just goes to the next prompt. However if I type in, python3 manage.py runserver 127.0.0.1:8000 It works correctly and starts the server. What could be the issue? Is doing ctrl+C not stopping the already running server? How do I find out if I have any other servers still running in the background? -
how make link dynamic
I have one template in that I have some blocks of services I want make all contain of block dynamically so I can make any change from admin dashboard. {% for services in servicess %} <div class="col mb-4"> <div class="card"> <img src="{{services.img.url}}" class="card-img-top" alt="..."/> <div class="card-body"> <h5 class="card-title">{{services.title}}</h5> <p class="card-text">{{services.desc}}</p> <a href="what should i write here?" class="btn btn-primary">Learn More</a> </div> </div> </div> {% endfor %} in this code I want to make Learn More button dynamic what should I put in link so I can redirect with corresponding service page I have 7 service pages in my site # services path('road-transport/', views.road, name = "road"), path('air-freight/', views.air, name = "air"), path('ocean-freight/', views.ocean, name = "ocean"), path('custom-clearance/', views.custom_clear, name = "custom_clear"), path('warehousing/', views.werehousing, name = "warehousing"), path('break-bulk/', views.break_bulk, name = "break_bulk"), path('project-cargo/', views.project_cargo, name = "project_cargo"), -
Save data with form.save() to Postgres ArrayField
I Recently migrated my Django project to Postgresql, but now my form which used to be able to save height, weight and date is not working. Models: In my models, I changed my weight and my date fields to ArrayField, that's when the problem started to occur. I never used Postgresql before. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.postgres.fields import ArrayField # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) weight = ArrayField( models.FloatField(max_length=20, blank=True, null=True), null=True, ) height = models.FloatField(max_length=20, blank=True, null=True) date = ArrayField( models.DateField(auto_now_add=True), null=True, ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Views: def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(Profile, id = request.user.id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save() return JsonResponse({ 'msg': 'Success' }) return render(request, 'Landing/index.html',{'form':form}) -
Django Add Record invalid literal for int() with base 10
I have the model models.py class StopRequestLog(models.Model): STOP_REQUEST_STATUSES = ( ('New', 'New'), ('Pending', 'Pending'), ) rafiki_profile_id = models.ForeignKey(RafikiProfileModel, on_delete=models.CASCADE, null=True) vehicle_profile_id = models.ForeignKey(VehicleProfile, on_delete=models.CASCADE, null=True) driver_profile_id = models.ForeignKey(DriversProfile, on_delete=models.CASCADE, null=True) tega_id = models.ForeignKey(Tega, on_delete=models.CASCADE, null=True) created_date = models.DateField(auto_now=False, null=True) created_time = models.TimeField(auto_now=False, null=True) completed_date = models.DateField(auto_now=False, null=True) completed_time = models.TimeField(auto_now=False, null=True) status = models.CharField(choices=STOP_REQUEST_STATUSES, max_length=30) Admin.py class StopRequestLogAdmin(admin.ModelAdmin): fields = ['rafiki_profile_id', 'vehicle_profile_id', 'driver_profile_id','tega_id', 'created_date', 'created_time', 'completed_date', 'completed_time' ,'status'] list_display = ['rafiki_profile_id', 'vehicle_profile_id', 'driver_profile_id','tega_id', 'created_date' , 'created_time', 'completed_date', 'completed_time','status'] readonly_fields = ['created_date', 'created_time', 'completed_date', 'completed_time'] Upon opening the Model and trying to add a record I get the error invalid literal for int() with base 10: b'07 08:49:15.819365' This b'07 08:49:15.819365' always being my current server time Please assist.