Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy Django Based Server and Laravel Project Simultaneously on a Single Droplet
I am new to Digital Ocean and was wondering on how to deploy Django and Laravel code side-by-side. The code works fine locally but I don't know how to deploy the both sources over Digital Ocean droplet. We bought cloudways server but it doesn't offer anything other than PHP which was the limitation. So, we don't have any experience with deployment on Digital Ocean. Is there anyone who can help me with this? Thank you! -
Download face-api video in Django with Javascript
So i want to ask a question about Django. I have a project that detect deepfake video. And the result will come as a video and some face detection on it like this; result example Is it possible to make a function to download the video with the facebox too? I'm still new using Django and javascript, thank you very much -
Django filter by month inside views dictionary
def testing(request): totals_dict = { 'Eating': Daily.objects.aggregate(eats=Sum('transamount', filter=Q(transcategory_id=5) & Q(transdate__month=1) | Q(transcategory_id=19) & Q(transdate__month=1) | Q(transcategory_id=20) & Q(transdate__month=1) | Q(transcategory_id=28) & Q(transdate__month=1) | Q(transcategory_id=31) & Q(transdate__month=1)))['eats'], 'Trans_List': Daily.objects.all(), 'Total_Bal': Daily.objects.all().aggregate(tb=Sum('transamount'))['tb'], 'Cash_Bal': Daily.objects.aggregate(CashBAL=Sum('transamount', filter=Q(transmode__name='Cash')))['CashBAL'], 'Enbd_Bal': Daily.objects.aggregate(ENBDBAL=Sum('transamount', filter=Q(transmode__name='ENBD')))['ENBDBAL'], 'NoL_Bal': Daily.objects.aggregate(NoLBAL=Sum('transamount', filter=Q(transmode__name='NoL')))['NoLBAL'], 'PayIT_Bal': Daily.objects.aggregate(PayITBAL=Sum('transamount', filter=Q(transmode__name='Pay IT')))[ 'PayITBAL'], 'Sib_Bal': Daily.objects.aggregate(SibBAL=Sum('transamount', filter=Q(transmode__name='SIB')))['SibBAL'], } return render(request, 'testing.html', totals_dict) In my above ‘view’, I am getting correct result for ‘Eating’ but I have hardcoded the month as ‘1’, so it’s 'Sum’ming only for January. Please guide me to make every ‘Sum’ based on months. Is it possible to create the dict values inside a loop like "for i in 1 to 12 " -
Django : i want to filter exam to buy users category (in checkout)
class Category(models.Model): STATUS = ( #متاح ('True','True'), #غير متاح ('False','False'), ) title = models.CharField(max_length=200) deatil = models.CharField(max_length=200) descrption = RichTextUploadingField() image = models.ImageField(upload_to='images/') status = models.CharField(max_length=50 , choices=STATUS) price = models.FloatField(blank=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = ("Category") verbose_name_plural = ("Category") ordering = ['-create_at'] def __str__(self): return self.title def image_tag(self): return mark_safe('<img src="{}" height="50"/>'.format(self.image.url)) image_tag.short_description = 'Image' checkout by users courses class Chekout(models.Model): category = models.ForeignKey(Category , on_delete=models.CASCADE) user = models.ForeignKey(User , on_delete=models.CASCADE) total = models.FloatField(blank=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = ("chekout") verbose_name_plural = ("chekout") def __str__(self): return self.user.username (A user can buy more than one course) the model Exam class Exam(models.Model): category = models.ForeignKey(Category , on_delete=models.CASCADE , blank=True) course_name = models.CharField(max_length=200) question_number = models.PositiveIntegerField() total_marks = models.PositiveIntegerField() create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = ("Exam") verbose_name_plural = ("Exam") ordering = ['-create_at'] def __str__(self): return self.course_name i can used loop But only the last course comes out def student_exam_view(request): checkout = Chekout.objects.filter(user_id = request.user.id ) for test in checkout: exam = Exam.objects.filter(category = test.category) -
Internal Server Error : apache2 Target WSGI script cannot be loaded as Python module
I am running django project with mysql database on apache2. my default python version is 3.9 $ python -V Python 3.9.7+ i am using the vscode and source code is in remote machine i am using virtual environment to run project but my error logs/var/logs/apache2/stability-dashboard/error.log shows python 3.6 [Wed May 18 09:53:47.634182 2022] [wsgi:error] [pid 10955:tid 140320866711296] [remote 10.104.48.133:52511] mod_wsgi (pid=10955): Target WSGI script '/home/ess/Desktop/dashcode/stability-dashboard/dashboard/dashboard/wsgi.py' cannot be loaded as Python module. [Wed May 18 09:53:47.634287 2022] [wsgi:error] [pid 10955:tid 140320866711296] [remote 10.104.48.133:52511] mod_wsgi (pid=10955): Exception occurred processing WSGI script '/home/ess/Desktop/dashcode/stability-dashboard/dashboard/dashboard/wsgi.py'. [Wed May 18 09:53:47.634749 2022] [wsgi:error] [pid 10955:tid 140320866711296] [remote 10.104.48.133:52511] Traceback (most recent call last): [Wed May 18 09:53:47.634853 2022] [wsgi:error] [pid 10955:tid 140320866711296] [remote 10.104.48.133:52511] File "/usr/lib/python3.6/logging/config.py", line 565, in configure [Wed May 18 09:53:47.634868 2022] [wsgi:error] [pid 10955:tid 140320866711296] [remote 10.104.48.133:52511] handler = self.configure_handler(handlers[name]) [Wed May 18 09:53:47.634884 2022] [wsgi:error] [pid 10955:tid 140320866711296] [remote 10.104.48.133:52511] File "/usr/lib/python3.6/logging/config.py", line 738, in configure_handler [Wed May 18 09:53:47.634892 2022] [wsgi:error] [pid 10955:tid 140320866711296] [remote 10.104.48.133:52511] result = factory(**kwargs) [Wed May 18 09:53:47.634907 2022] [wsgi:error] [pid 10955:tid 140320866711296] [remote 10.104.48.133:52511] File "/usr/lib/python3.6/logging/handlers.py", line 202, in __init__ [Wed May 18 09:53:47.634916 2022] [wsgi:error] [pid 10955:tid 140320866711296] [remote 10.104.48.133:52511] BaseRotatingHandler.__init__(self, filename, 'a', encoding, … -
DRF How to display only not blank value of serializing nested object
I've create serializing nested like this [ { "id": 1, "name": "Auto", "iconname": "taxi_alert_outlined", "budgetamount": "0.00", "iconcolor": "4294951175", "dailyexpense_category": [] }, { "id": 2, "name": "Foods:Breakfast", "iconname": "emoji_food_beverage", "budgetamount": "0.00", "iconcolor": "4294951175", "dailyexpense_category": [ { "id": 24574, "payee_item_desc": "เซเว่น", "amount": "-100.00", "remarks": "เฟิส", "tran_date": "2022-04-01T00:00:00Z", "isnotclear": false, "category": 2 } ] } ] Expected result after filter only not blank value is [ { "id": 2, "name": "Foods:Breakfast", "iconname": "emoji_food_beverage", "budgetamount": "0.00", "iconcolor": "4294951175", "dailyexpense_category": [ { "id": 24574, "payee_item_desc": "เซเว่น", "amount": "-100.00", "remarks": "เฟิส", "tran_date": "2022-04-01T00:00:00Z", "isnotclear": false, "category": 2 } ] } ] I've tried to create custom field such as sum nested object or count nested object but I want something that more easier to filter only not blank objected. -
Django Rest Framework - Post more info User from Foreign Key
I am new to Django Rest Framework and checked some tutorials. Now I am trying to create my own user profile with more fields like: company name, phone, ....I created OneToOneField (one-to-one relationship) table with more info for my extend user. Now i want to create new user with all fields in post method, but i got error. How can i fix this? models.py class MoreInfo(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) compName = models.CharField(max_length=100) title = models.CharField(null=True,max_length=128) birthday = models.DateField(null=True, blank=True) phone = models.CharField(max_length=20,blank=True) api/serializer.py class MoreInforSerializer(serializers.ModelSerializer): class Meta: model = MoreInfo fields = '__all__' class CreateUserSerializer(serializers.ModelSerializer): moreInfoUser = MoreInforSerializer() class Meta: model = User fields = '__all__' extra_kwargs = {'password':{'write_only':True}} def create(self,validated_data): user = User.objects.create( email=validated_data['email'], username = validated_data['username'], password = make_password(validated_data['password']) ) info_data = validated_data.pop('moreInfoUser') moreInfo = MoreInfo.objects.create( user = user, compName = info_data['compName'], title = info_data['title'], birthday = info_data['birthday'], phone = info_data['phone'] ) # user.save() return user views.py class ListCreateUser(ListCreateAPIView): serializer_class = CreateUserSerializer def post(self, request, *args, **kwargs): serializer = CreateUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse({ 'message': 'Create a new Info successful!' }, status=status.HTTP_201_CREATED) return JsonResponse({ 'message': 'Create a new Info unsuccessful!' }, status=status.HTTP_400_BAD_REQUEST) urls.py path('createUser',views.ListCreateUser.as_view()), POST: { "username":"user5", "password":"12345aA@", "email":"user5@gmail.com", "compName":"A", "title":"test", "birthday":"1997-05-04", "phone":"01234567" } Table for … -
How to use threading with django and gunicorn
I am trying to use the threading library inside of a django application that uses gunicorn. When I run my code locally everything is good, but as soon as I try to call the view from production I get a context error. I believe this is due to gunicorn. Here is the error RuntimeError: cannot exit context: thread state references a different context object Here is my code. t = threading.Thread( target=myFunction, args=[arg1] ) t.setDaemon(True) t.start() -
CK editor with different height in Django
I have used CK editor in 4 places on my Django website on the first two places I want to keep the default height and toolbar and in the second two places I want the 50% height and 'Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['NumberedList','BulletedList'], toolbars Settings for first two editor CKEDITOR_CONFIGS = { 'default': { 'toolbar_Full': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink', ], [ 'Flash', 'HorizontalRule'], ['TextColor', 'BGColor'], ['SpecialChar'], ['Source'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['NumberedList','BulletedList'], ['Indent','Outdent'], ['Maximize'], ], 'extraPlugins': 'justify,liststyle,indent', 'width': 'auto', }, } please help me to figure it out -
Error in the create method of Writable Nested serializers in django
models.py class Job(models.Model): job_id = models.CharField(max_length=50, default=uuid.uuid4, editable=False, unique=True, primary_key=True) org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='org_job', null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_job', null=True) job_name = models.CharField(max_length=100) start_date = models.DateField(null=True,blank=True) end_date = models.DateField(null=True,blank=True) hours = models.DurationField(null=True,blank=True) assignee = models.ForeignKey(User_Master, on_delete=models.CASCADE, related_name='user_master_job', null=True) rate_per_hour = models.IntegerField(null=True,blank=True) description = models.TextField(max_length=500,null=True,blank=True) # attachment_url = models.URLField(upload_to=upload_to , null=True, blank=False) remainder = models.BooleanField(null=True,blank=True,default=False) billable_status = models.ForeignKey(User_billable_status, on_delete=models.CASCADE, related_name='user_billstatus_job', null=True) work_item = ArrayField(models.CharField(max_length=300),null=True,blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.IntegerField(default=0, choices=STATUS_CHOICES) class User_billable_status(models.Model): billable_status_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='user_billable_status_org_id', null=True) billable_status_name = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) serializers.py class User_billable_status_Serializers(serializers.ModelSerializer): class Meta: model = User_billable_status fields = ('billable_status_id', 'billable_status_name') class Jobpost_Serializers(serializers.ModelSerializer): billable_status = User_billable_status_Serializers() class Meta: model = Job fields = ('job_id','project','job_name','start_date','end_date','hours','assignee','rate_per_hour','description','remainder','billable_status','work_item') def create(self, validated_data): job = validated_data.pop('billable_status') billable_status = Job.objects.create(**validated_data) User_billable_status.objects.create(billable_status=billable_status, **job) return billable_status I was trying to create a billable status data while posting a Job, but when I tried I was getting an error as " TypeError at /api/onboarding/job/ User_billable_status() got an unexpected keyword argument 'billable_status' Request Method: POST Request URL: http://127.0.0.1:8000/api/onboarding/job/ Django Version: 3.2.12 Exception Type: TypeError Exception Value: User_billable_status() got an unexpected keyword argument 'billable_status' Exception Location: C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py, line 503, in init Python Executable: … -
Is request_finished a non-blocking signal?
Django documentation says that request_finished signal is sent when Django finishes delivering an HTTP response to the client. Does that mean any operation can be done after the request-response cycle being finished. Is it a non-blocking and asynchronous signal? -
How to Output More than Once In frontend In DJango
I am building a web app that makes use of the HackerNews API and I keep running into the same error. I am trying to Output the 10 requested result from API but everytime i use the return response it only outputs the first result. I want it to output 10 articles from the API instead of just the One. This is my code: from operator import itemgetter import requests from django.shortcuts import render # Make an API call and store the response. def home(request): url = 'https://hacker-news.firebaseio.com/v0/topstories.json' r = requests.get(url) print(f"Status code: {r.status_code}") # Process information about each submission. submission_ids = r.json() submission_dicts = [] for submission_id in submission_ids[:10]: # Make a separate API call for each submission. url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json" r = requests.get(url) print(f"id: {submission_id}\tstatus: {r.status_code}") response_dict = r.json() # Build a dictionary for each article. submission_dict = { 'title': response_dict['title'], 'hn_link': f"http://news.ycombinator.com/item?id={submission_id}", # 'comments': response_dict['descendants'], } submission_dicts.append(submission_dict) # submission_dicts = sorted(submission_dicts, key=itemgetter('comments'), # reverse=True) for submission_dict in submission_dicts: print(f"\nTitle: {submission_dict['title']}") print(f"Discussion link: {submission_dict['hn_link']}") # print(f"Comments: {submission_dict['comments']}") count = 0 if count < 10: return render(request, "news_api/home.html", submission_dict) -
Heroku Django deployment ModuleNotFoundError: No module named 'appointmentApp'
Im trying to deploy a django site using Heroku and I keep running into this error when the page tries to load with heroku logs --tail » Warning: heroku update available from 7.53.0 to 7.60.2. 2022-05-18T01:09:37.493808+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-05-18T01:09:37.493808+00:00 app[web.1]: worker.init_process() 2022-05-18T01:09:37.493808+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-05-18T01:09:37.493809+00:00 app[web.1]: self.load_wsgi() 2022-05-18T01:09:37.493809+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-05-18T01:09:37.493810+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-05-18T01:09:37.493810+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-05-18T01:09:37.493810+00:00 app[web.1]: self.callable = self.load() 2022-05-18T01:09:37.493811+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-05-18T01:09:37.493811+00:00 app[web.1]: return self.load_wsgiapp() 2022-05-18T01:09:37.493811+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-05-18T01:09:37.493812+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-05-18T01:09:37.493812+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-05-18T01:09:37.493812+00:00 app[web.1]: mod = importlib.import_module(module) 2022-05-18T01:09:37.493813+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2022-05-18T01:09:37.493813+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-05-18T01:09:37.493813+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-05-18T01:09:37.493814+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2022-05-18T01:09:37.493814+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2022-05-18T01:09:37.493814+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2022-05-18T01:09:37.493815+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2022-05-18T01:09:37.493815+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2022-05-18T01:09:37.493815+00:00 app[web.1]: File "/app/GroomingService/GroomingService/wsgi.py", line 16, in <module> 2022-05-18T01:09:37.493816+00:00 app[web.1]: application = … -
(Django-React App) API request to the backend returns 200 OK but not getting authenticated in frontend
What am I developing?: Hello, I am developing a Django-React App, where Django acts as backend for the authentication using Djoser library and JWT, and React acts as frontend application. In addition, I use Django-rest-framework, CORS headers, Axios and React Redux to do all the communication between backend and frontend. Context of the problem: I work on an Ubuntu 20.04, called 'pablo-dev.ivanlab.lan', through SSH connection on Visual Code, and I launch there the docker-compose file which start the microservices in docker containers that are exposed to the Ubuntu machine, so all the testing I have been doing is through the SSH on Visual Code. I am building a microservices architecture as a Django-React-Postgres application in docker-compose so I can deploy it on a Raspberyy Pi 4 with Raspbian OS. As the Raspberry is gonna run the frontend application in different IPs I decided to allow all origins in the CORS variables of Djando 'settings.py' instead the of the static IP I use right now in SSH development. The problem: Once I try to change the 'CORS_ALLOW_ALL_ORIGINS' to 'True', my system keeps receiving the requests to the backend but even with a 200 HTTP response I am not getting authenticated in … -
How can I show a star rating based on the average?
I am currently working with Django and Jquery, I need to show some hotels with the stars rated in orange based on the average obtained from a score and the number of people who have voted for that hotel. I'll give an example score = 8 vote= 2 overage = 4 Therefore I need to display 4 orange stars and 1 black. I have this code, but it only works for the first hotel and there are many, so I use a for. {% for hotel in hotels %} <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous"/> <div class="col-12" > <span class="fa fa-star" id="1star" ></span> <span class="fa fa-star" id="2star" ></span> <span class="fa fa-star" id="3star" ></span> <span class="fa fa-star" id="4star" ></span> <span class="fa fa-star" id="5star" ></span> </div> <script type="text/javascript" src="{% static 'js/jquery.js' %}"></script> <script type="text/javascript"> $(document).ready(function () { let score = '{{hotel.score}}' let vote = '{{hotel.vote}}' let overage = (parseInt(score)/ parseInt(vote)) let star = document.getElementById('star') for(let i = 0; i < overage; i++) { document.getElementById((i+1)+'star').style.color='orange' } }); </script> {% endfor%} I don't know much Js. I'm looking forward you can healp me please. -
Can I create a django view that returns a json object rendered from JavaScript
I want to create a view that simply executes some JavaScript and displays the output in JSON form. I want to keep this JavaScript execution away from the user, so is it possible to have a client-side view that waits for the resulting JSON string. Or in other words "waits" and gets for the first view to print the json to the HTML body? -
Django Rest - Using a SerializerMethodField and getting an error: 'QuerySet' object has no attribute 'birth_date'
I'm new to Django and APIs in general and I want to create a Django based API using Django Rest Framework. Here's what I want to do: Endpoint to age range report: curl -H 'Content-Type: application/json' localhost:8000/reports/employees/age/ Response: { "younger": { "id": "1", "name": "Anakin Skywalker", "email": "skywalker@ssys.com.br", "department": "Architecture", "salary": "4000.00", "birth_date": "01-01-1983"}, "older": { "id": "2", "name": "Obi-Wan Kenobi", "email": "kenobi@ssys.com.br", "department": "Back-End", "salary": "3000.00", "birth_date": "01-01-1977"}, "average": "40.00" } Here's my code so far: employees/model.py: class Employee(models.Model): name = models.CharField(max_length=250, default='FirstName LastName') email = models.EmailField(max_length=250, default='employee@email.com') departament = models.CharField(max_length=250, default='Full-Stack') salary = models.DecimalField(max_digits=15, decimal_places=2, default=0) birth_date = models.DateField() employees/serializers.py: class EmployeeSerializer(serializers.ModelSerializer): age = serializers.SerializerMethodField() class Meta: model = Employee fields = ['id', 'name', 'email', 'departament', 'salary', 'birth_date', 'age'] def get_age(self, obj): delta = datetime.now().year - obj.birth_date.year return delta class EmployeeAgeReportSerializer(serializers.Serializer): youngest = EmployeeSerializer() oldest = EmployeeSerializer() # average = serializers.FloatField() def create(self, validated_data): pass def update(self, instance, validated_data): pass employees/views.py: class EmployeeGenericViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet ): queryset = Employee.objects.all() serializer_class = EmployeeSerializer lookup_field = 'pk' In employees/services.py I have: class EmployeeAgeReport: def __init__(self, youngest, oldest): self.youngest = youngest self.oldest = oldest # self.average = average def get_employee_age_report(): age_report_dict = Employee.objects.aggregate( earliest_birth_date=Min("birth_date"), oldest_birth_date=Max("birth_date") ) youngest_employee … -
Data Tables not going to PostgreSQL
I am running a data parser/web scraper with python. The parser then pushes the data (SQL Tables) to postgresql. However, I can't find the tables in pgadmin. This is part of a full stack django webapp, using docker, which I did not create but I am trying to get to run locally. As far as I can tell docker containers are working as intended, and so is the dataparsing script. Since I don't know much about issues like this please let me know if there is anything else I should include Database connection in python class DatabaseConnection(object): def __init__(self, user="postgres", password="1234", host="127.0.0.1", port="5432", database="postgres", course_table="course_info", prereqs_table="prereqs", antireqs_table="antireqs", requirements_table="requirements", communications_table="communications", breadth_table="breadth_table"): Trying to access the backend in browser returns this, which makes me believes the tables don't exist in postgresql Output in txt file (roughly 300,000 lines, IDK if this is useful in analyzing the problem but thought I'd include it either way) -
Consumindo uma API de CNPJ no CreateView do Django
Estou fazendo um cadastro de cliente, nele gostaria de usar uma API para puxar o nome da empresa e o endereço. Criei na Views uma classe CreateView, porém ao rodar a api através de uma def, o ele entende que quero cadastrar o cliente. Como lidar com dois submits de POST no Django? -
Django: Formset not validating due to missing data
I am using the django-formset-js package (https://pypi.org/project/django-formset-js-improved/) to make a dynamic formset. There are three models involved. The Menu model, which has a title and a brief description. related to the menu model are multiple courses. They shall be attached dynamically, as the number of courses can vary. When posting the request, the on the website, the formset, does not validate. I am trying to debug the code for days now, and cannot find the answer. the request.POST returns values. request.POST <QueryDict: {'csrfmiddlewaretoken': ['1kdujphIO3iawZZJuqSTYSds4vGT8er88s1GDpteNhAy20gTRdNRUTefXPSI 3Kjz'], 'menu_name': ['Mein zweites Menu'], 'menu_description': ['asfasdg'], 'status': ['a'], 'form-TOTAL_FORMS': ['2'], 'form-INITIAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-1-course_name': ['B igger'], 'form-1-course_description': ['asdfasdfasdfasdfasdf']}> But, when I print course_formset.cleaned_data to the console, it shows an empty and dict and it also complains, that the formset does not validate due to missing data. further below, you find the model.py, form.py and the html code. Please, help me. You are my only hope html <h3 class="mt-5">Add courses to your menu</h3> <div id="formset" data-formset-prefix="{{ course_formset.prefix }}"> {{ course_formset.media }} {{ course_formset.management_form }} <div id="formset-body" data-formset-body> <!-- New forms will be inserted in here --> <div data-formset-form> </div> </div> <!-- The empty form template. By wrapping this in a <script> tag, the … -
Mass Upload Json data into Django Models using Views
I've been working on getting to learn Django and React to broaden my knowledge in Programming. I'm trying to create an API endpoint to Mass upload data from the front end (React) into Django models. Realistically it wont be more than 20 records at a time but I wanted to see if this can be done without having to upload a record individually. The front end would accept a CSV File and convert it into a Json array. Can anyone provide some guidance on how I would create a View to allow me to accept that json array and insert it into my models. I'm using Django, React, and Postgres as my DB. I tried to create some views for this functions but it doesn't really workout. Models: class Products(models.Model): date_added = models.DateTimeField(default=django.utils.timezone.now) on_hold_till = models.DateTimeField(default=django.utils.timezone.now) item_no = models.CharField(max_length=120, default="") description = models.CharField(default="", max_length=256) total_units = models.IntegerField(default=0, blank=True) is_featured = models.BooleanField(default=False) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) avg_cogs = models.DecimalField( max_digits=10, decimal_places=2, default=0.00) profit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) margin = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) mintage = models.IntegerField(default=0, blank=True) pop_known = models.CharField(default="", blank=True, max_length=100) ngc_pop = models.IntegerField(default=0, blank=True) pcgs_pop = models.IntegerField(default=0, blank=True) total_pop = models.IntegerField(default=0, blank=True) finer_known = models.IntegerField(default=0, blank=True) highlights = ArrayField(models.CharField( … -
Django: Call form clean before model clean
I have an Occurrence model that I am putting as TabularInline on the admin page of another model. It has a PointField and a PolygonField, of which at least one must exist. Here is part of the model: class Occurrence(models.Model): name = models.CharField(max_length=254) location = models.PointField(null=True, blank=True) bounding_polygon = models.PolygonField(null=True, blank=True) def clean(self): # Checks if at least one of the spatial fields is filled in if not self.location and not self.bounding_polygon: raise ValidationError('At least one of the spatial fields (point or polygon) is required.') In the TabularInline I wanted to put the name and location but when I add new rows the map of the location does not appear. To get around this problem, I used a form where you can enter the latitude and longitude, which is then converted to the Point of location. Here is my form: class OccurrenceForm(forms.ModelForm): latitude = forms.FloatField( min_value=-90, max_value=90, required=False, help_text="Enter coordinates as an alternative to selecting a point on the map." ) longitude = forms.FloatField( min_value=-180, max_value=180, required=False, ) class Meta(object): model = Occurrence exclude = [] def __init__(self, *args, **kwargs): super(OccurrenceForm, self).__init__(*args, **kwargs) coordinates = self.initial.get("location", None) if isinstance(coordinates, Point): self.initial["longitude"], self.initial["latitude"] = coordinates.tuple def clean(self): data = super(OccurrenceForm, self).clean() … -
How can I apply a common validator to all text inputs in my Django form?
I want to apply a special character whitelist to all non-password user text inputs across my site, so that validation will fail if a non-whitelisted character is entered. All of my forms already inherit from a single base form class, which itself inherits from django.forms.BaseForm. How can I apply this validator to every relevant field on all the forms that inherit from this form? -
patch in serializer django rest
I have 1 parent and 1 child serializers, right now child serializer inherits all fields, functions and methods from the parent serializer. I would like to modify patch request in child serializer, that while request is patch, then some fields will be unavailable for updating, cause there will be completely different two urls. For example in child class there will be unable to update name and surname. class Parent(serializers.ModelSerializer): class Meta(BaseMeta): model = Account fields = BaseMeta.fields + ( 'name', 'surname', 'age', 'city', 'country', 'job', 'family') extra_kwargs = {'name': {'required': True, 'allow_blank': False, 'allow_null': False, 'trim_whitespace': False}, 'surname': {'required': True, 'allow_blank': False, 'allow_null': False, 'trim_whitespace': False}, 'country': {'read_only': True}, 'job': {'required': True, 'allow_blank': False, 'allow_null': False, }, } class Child(ParentSerializer): class Meta(BaseMeta): model = Account fields = BaseMeta.fields + () extra_kwargs = { } -
Django - display the same chart in loop in jinja template with chart.js
I would like to display the same chart (of course with different data and labels) in loop. At this moment I have: <tbody> {% for key, value in game_details.items %} <tr> <td>{{ key }}</td> <td>{{ value.all }}</td> <td>{{ value.win }}</td> <td>{{ value.lost }}</td> </tr> <tr> <td> <canvas id="myChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'pie', data: { labels: ['Win', 'Lost'], datasets: [{ label: '# of Votes', data: [{{ value.win }}, {{ value.lost }}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </td> </tr> {% endfor %} </tbody> The first chart is displayed, but when I'm looking in console I can see: Uncaught SyntaxError: Identifier 'ctx' has already been declared (at (index):179:29). So my loop can't create another chart, because ctx is already declared. My goal is to display chart for each iteration over dictionary. I was looking at this post, but it doesn't sole my problem. How can I do it properly?