Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to save model form data in database. gives patientmedinfo.errors = none and patientmedinfo.is_valid() = false
'I am new to django , trying to save my form data in the database.created two model classes PatientInfo and patientHist, which is inheriting PatientInfo class. I do not understand where i am going wrong. models.py from django.db import models # Create your models here. class PatientInfo(models.Model): sex = ( ('M', 'Male'), ('F', 'Female') ) first_name = models.CharField(max_length=35) middle_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length= 30) sex = models.CharField(max_length=1,choices=sex) date_of_birth = models.DateField() height = models.FloatField() weight = models.FloatField() phone_no =models.CharField(max_length=15) class PatientHist(PatientInfo): Yes_No = ( (True, 'Yes'), (False, 'No'), ) Veg_nonveg =( (True,'Veg'), (False,'Non-Veg'), ) diabetes = models.BooleanField(default=False,choices=Yes_No) diabetes_long = models.CharField(max_length=20) hypertension = models.BooleanField(default=False,choices=Yes_No) hypertension_long = models.CharField(max_length=20) obesity = models.BooleanField(default=False,choices=Yes_No) obesity_long = models.CharField(max_length=20) pcod = models.BooleanField(default=False,choices=Yes_No) pcod_long= models.CharField(max_length=20) thyroid = models.BooleanField(default=False,choices=Yes_No) thyroid_long = models.CharField(max_length=20) heartdiease = models.BooleanField(default=False,choices=Yes_No) heartdiease_long = models.CharField(max_length=20) liverdisease = models.BooleanField(default=False,choices=Yes_No) liverdisease_long = models.CharField(max_length=20) kidney = models.BooleanField(default=False,choices=Yes_No) kidney_long = models.CharField(max_length=20) familyhistory = models.BooleanField(default=False,choices=Yes_No) currentmed = models.CharField(max_length=20) foodhabit= models.BooleanField(default=False,choices= Veg_nonveg) hba1c = models.FloatField(max_length=20) fasting = models.FloatField(max_length=20) pp = models.FloatField(max_length=20) forms.py from django import forms from .models import * class Patient_form(forms.ModelForm): class Meta: model = PatientInfo fields = "__all__" class PatientHistory_form(forms.ModelForm): class Meta: model = PatientHist widgets = { 'diabetes': forms.RadioSelect, 'hypertension': forms.RadioSelect, 'obesity': forms.RadioSelect, 'pcod': forms.RadioSelect, 'thyroid': … -
mypy gives an error while importing submodule : Module has no attribute
When I am checking my modules through mypy it gives me this error: Module 'django.contrib.gis' has no attribute 'forms' and I am importing forms like this " from django.contrib.gis import forms ". I know it is correct but mypy shows this error message. I could import like this: from django.contrib import gis and use forms as gis.forms but I do not want to. Can anyone help me to fix this? Thanks. -
What is difference between django-bootstrap4 and bootstrap4?
I am beginner in Django web development & currently I am using using bootstrap4 by loading bootstrap.min.css & bootstrap.min.js as below in html files. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> Recently I have found that there been module in Django named django-bootstrap4 & I am reading its documentation also. https://django-bootstrap4.readthedocs.io/ I have tried to find difference between those but not found any. Which will be suitable to use in web development? Tried to find answer on google but not found any so please can someone explain me difference between these two? -
How to append values in a tabular format from JSON in Django Template?
I am making a small web application that allow user to perform OCR on the selected image and provides the JSON output in a tabular Format like this. What I'm facing now is when I'm selected new image to add values in the table, it overrides the values instead of appending. And what I want is to append new value in the table by choosing another image, the previous row show me stay as it is and new will get append. So that finally I can submit all the values to the database all together by clicking on the submit button. Here is my template code : <form method="post">{% csrf_token %} <div class="table-responsive"> <table id="datatable2" class="table order-column hover"> <thead> <tr> <th>Investigation Name</th> <th>Result</th> <th>UOM</th> <th>Low Range</th> <th>High Range</th> </tr> </thead> <tbody> {% for key, value in data.items %} {% for key2,value2 in value.items %} <tr class="gradeX"> <td>{{ value2.test_name }}</td> <td>{{ value2.results }}</td> <td>{{ value2.units }}</td> <td>{{ value2.low_range }}</td> <td>{{ value2.high_range }}</td> </tr> {% endfor %} {% endfor %} </tbody> </table> </div> <!--end .table-responsive --> <button type="submit" class="btn btn-primary" name="data">Submit</button> </form> How can we use list in DTL to store the previous values and stay as it is and the new … -
Does django caches queryset results if those querysets are used (or deleted) later?
a = SampleModel.objects.filter(Id=2) b = SampleModel.objects.filter(Id=3) If a and b: print(true) a.delete() b.delete() Now in above code...how many time is database hit? It will be hit when calling a and b in if statement. But will database also be hit on .delete() operations. Or django has some cache mechanism which caches the queryset results? -
Getting ImportError on Django3.0.4 while running runserver [duplicate]
I have been trying to run the latest versionof django3.0.4, but I'm getting error while trying to run the local server. I tried installing the package six eventhough it was already installed. pip install six current version being used is six-1.14.0 pip install --upgrade django-cors-headers current versio being used is django-cors-headers-3.2.1 Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/rest_framework/templatetags/rest_framework.py", line 9, in <module> from django.utils import six ImportError: cannot import name 'six' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/username/Documents/Projects/VirtualEnv/lib/python3.6/site-packages/django/utils/autoreload.py", … -
how to change input durationfield format using forms like 3w 3h 3m. I tried several ways.Please help .I am fresher
Forms.py class Meta: model = Issues fields ='__all__' exclude=['CREATOR','UPDATOR','CREATED_DATE_TIME','UPDATED_DATE_TIME','EPIC_LINK','WATCHER','PARENT','ORDER','SERIAL_NUMBER','COLOR','DEFECT_TYPE','STATUS','EPIC_NAME'] widgets = { 'START_DATE': DateInput(), 'DUE_DATE': DateInput(), 'ESTIMATION_TIME': DurationInput(), } class DurationInput(TextInput): def _format_value(self, value): duration = parse_duration(value) seconds = duration.seconds minutes = seconds // 60 seconds = seconds % 60 minutes = minutes % 60 return '{02w}{02d}{02h}{02m}'.format(minutes, seconds) models.py ESTIMATION_TIME = models.DurationField(null=True, blank=True) -
Email to Register Confirmation Django
The confirmation email is arriving normal at test@hotmail.com. But whenever I click the message appears:'Activation link is invalid!' ever. Can someone help me? Views.py def register(request): if not request.user.is_authenticated: if request.method == 'POST': register_status = register_user(request) if register_status != 1: messages.error(request, register_status) return redirect('register') #Register Success else: user = get_user_model() subject = 'Confirm your account' current_site = get_current_site(request) message = render_to_string('users/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) from_email = 'myacount@gmail.com' to_list = [from_email , 'test@hotmail.com'] send_mail( subject, message, from_email, to_list, fail_silently=False, ) messages.success(request, 'Please confirm your email') return redirect('login') else: return render(request, 'users/register.html') else: messages.error(request, 'You are already logged in') return redirect('index') def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) User = get_user_model() user = User.objects.get(pk=uid) print(user) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() url.py from django.urls import path from . import views urlpatterns … -
Why django PermissionRequiredMixin is not working as it intended to be
Here i have got a Django view that should normally redirect me to the Settings.LOGIN_URL if user has not the required permission but the issue is it's always displaying the 403 FORBIDDEN page. the url defined in Settings.LOGIN_URL is 'accounts/login/'. class LibrairianListView(PermissionRequiredMixin, View): model = BookInstance template_name = 'catalog/librairian_list_borrowed.html' permission_required = 'catalog.can_mark_returned' def get_queryset(self): return BookInstance.objects.filter(status__exact='o').order_by('due_back') def get_context_data(self, **kwargs): print(self.raise_exception) context = {} context['bookinstance_list'] = self.get_queryset() return context def get(self, request, *args, **kwargs): return render(request, self.template_name, self.get_context_data()) And i change this to a function based view and everything is working fine, but i wanted to use class base view since this should do the same work -
Django: Where to go from "pinax.notifications?"
With regards to a deployed web-site I am rudely confronted with unexpected upgrade problems. "pinax.notifications" in particular is throwing problems such as a dependency on a package named "six" and inability to understand the decorator @python_2_unicode_compatible. The Django version that this app has been running was 2.1.11 and now the latest is 3.0.4 and this seems to have caused me a boatload of problems all of the sudden. Any advice appreciated ... -
How to add User model to Profile model in Django right way?
I am new to Django and trying to create a Profile(Patient) model. Here are my models. class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.PositiveSmallIntegerField() gender = models.CharField(max_length=1) def __str__(self): return str(self.user.username) class Doctor(models.Model): name = models.CharField(max_length=50) max_slots = models.PositiveIntegerField(default=10) available = models.PositiveIntegerField(default=0) def __str__(self): return str(self.name) class Assistant(models.Model): name = models.CharField(max_length=50) docid = models.OneToOneField('Doctor', on_delete=models.CASCADE) def __str__(self): return str(self.name) class Appointment(models.Model): confirmed = models.BooleanField(default=False) patid = models.OneToOneField('Patient', on_delete=models.CASCADE) docid = models.ForeignKey('Doctor', on_delete=models.CASCADE) assid = models.ForeignKey('Assistant', on_delete=models.CASCADE) def __str__(self): return str(self.patid) Last migration file class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('doctor', '0014_auto_20200318_0219'), ] operations = [ migrations.AlterField( model_name='patient', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ] and error I am getting when I run migrations Operations to perform: Apply all migrations: admin, auth, contenttypes, doctor, sessions Running migrations: Applying doctor.0011_auto_20200318_0211...Traceback (most recent call last): File "C:\Users\syd's\.virtualenvs\django-hospital-0gp1XnhJ\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "doctor_patient" does not exist I tried dropping all my tables and running migrations again but no use. P.S. The name of my Django app is "doctor" and I am using PostgreSQL. -
Python 3.8 + Apache 2.4 + mod_wsgi to run django site
so I am running out of things I can possibly check for, I've made sure my python as well as apache are both 64 bit, python is a system wide install, I've uninstalled the 32 bit version before and reinstalled mod_wsgi to get the 64 bit module file, just in case I had the wrong build tools I even tried a pre-compiled mod_wsgi-4.7.1+ap24vc15-cp38-cp38-win_amd64.whl, but I did have the right build tools, I keep getting an error that says 'c:/users/eryk/pycharmprojects/django blog/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd into server: The specified module could not be found. .' The file is there, these are my parameters for the config that mod_wsgi-express module-config produces: LoadModule wsgi_module "c:/users/eryk/pycharmprojects/django blog/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd" WSGIPythonHome "c:/users/eryk/pycharmprojects/django blog/venv" And here is my httpd.conf, in case anyone's wondering i disabled ssl cause I was getting an error saying 443 is taken, will troubleshoot that once I can actually get the apache service to start as this is getting silly, anyone got an idea what the issue might be? Would be greatly appreciated. CTRL + F "python" will find the python edits in the apache config ''' # Apache Hause .conf file for TLS/1.3 supported versions # # This is the main Apache HTTP server configuration file. It … -
ValueError: Cannot assign foreign key, value must be instance
Models.py class SalesOrder(BaseOrder): customer = models.ForeignKey(.... In serializers.py sales_order, sales_order_created = models.SalesOrder.objects.get_or_create( status_there = True, is_internal=False, ).first() billing_address = models.Address.objects.filter(sap_id__icontains='123').first() and sales_order.billing_address=billing_address sales_order.save() ValueError: Cannot assign "(Customer-Cyberdyne Systems-a5233,)": "SalesOrder.customer" must be a "Customer" instance. I'm having the same error everywhere. this wherein files serializer, I am updating the sales order model. even with booleans ** When I print the billing address its just Customer-Cyberdyne Systems-a5233, But when I'm assigning to the sales order it is looking like this "(Customer-Cyberdyne Systems-a5233,)": "SalesOrder.customer" ** Please let me know where I'm missing something, and is it okay to update a model from another serializer -
How to get python python-decouple to work on a live server?
I can't seem to get python-decouple to work on a live server. I have a Django project in which python-decouple is used to separate my important variables such as secret key, debug, database vars, and so on in a .env file. When the project is run locally, python-decouple works well and I have no problems. After confirming that it works well locally, I then added the .env file to my .gitignore file, pushed the code to my GitHub repository, then pulled the code to the AWS live server. However, when trying to make migrations while configuring the project on an AWS EC2 Ubuntu server, I get the error below. It seems as though the variables in the .env file are not being applied on the AWS Ubuntu server which would make sense because of the .gitignore file. But I thought the whole point of python-decouple was to not have the important variables on the live server. Does anyone know why this error is occurring? and how I can fix it? or do not fully understand the use cases of python-decouple? $ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, … -
Make a custom of periodic tasks in django celery
i read about celery about periodic tasks use : # Import for custom tasks from __future__ import absolute_import, unicode_literals from celery import shared_task from celery import Celery from celery.schedules import crontab @periodic_task(run_every=crontab(minute="*/2")) def print_mail(): print("Send Mail to A Specific Time") i want to know if i can change the time in minute not set already but from an input of the form and the task will run periodic by the time of form input , can celery do that and how ??? , tks you ! -
Can we edit the user profile without using forms.py in django?
How to create view for the registered user to edit there profile in the user dashboard using django ? Please provide the view . I have created the register profile without using the forms.py , Now I want to create the userprofile edit only without using forms.py. And Is it possible to submit the data again to the database. (Dont use forms.py) Accounts/views.py def register(request): if request.method == 'POST': #get form values first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] #Check if passwords match if password == password2: #check username if User.objects.filter(username = username).exists(): messages.error(request,'That username is taken') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request,'That email is being used') return redirect('register') else: #looks good user = User.objects.create_user(username = username, password = password, email = email, first_name = first_name, last_name = last_name) #login after register # auth.login(request, user) # messages.success(request, 'You are now logged in') # return redirect('index') user.save() messages.success(request, 'You are now registered and can log in') return redirect('login') else: messages.error(request,'passwords do not match') return redirect('register') else: return render(request, 'accounts/register.html') -
OperationalError at /admin/weather/city/
i am following this tutorial and it created migrations folder without any error but when i logon to localhost:8000/admin and click cities i get OperationalError at /admin/weather/city/ models.py from django.db import models # Create your models here. class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' views.py import requests from django.shortcuts import render # Create your views here. def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=###' city = 'Las Vegas' r = requests.get(url.format(city)).json() city_weather={ 'city':city, 'temperature':r['main']['temp'], 'description':r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } context = {'city_weather': city_weather} return render(request,'weather/weather.html',context) after performing python manage.py makemigrations python manage.py migrate 0001_initial # Generated by Django 3.0.3 on 2020-03-18 02:30 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='City', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25)), ], options={ 'verbose_name_plural': 'cities', }, ), ] then added below code in admin admin.py from django.contrib import admin from .models import City # Register your models here. admin.site.register(City) After several similar questions and answers i had deleted migration folder and again performed python manage.py makemigrations python manage.py migrate tried python manage.py migrate --run-syncdb too but all in vain getting the same error , please help stuck for … -
Django annotate string value
I'm trying to use the following SQL query in my the django query UNION query: 'transfer' AS transaction_type, And as using annotate i would use: annotate(transaction_type=Value('transfer', CharField())) But i keep getting this following error in my view : invalid literal for int() with base 10: 'transfer' I even tried annotate(transaction_type=Value('transfer', output_field =CharField())) but still got the same error How do i use string in annotate ? -
Django Method Not Allowed (POST) 405
Can anyone help me with this. I'm trying to get the value of my input in html by using javascript but when i ran my project it shows this. Method Not Allowed (POST) May you help me find what is the problem and how am i gonna solve this? url: from django.conf.urls import url,include from . import views from django.contrib.auth.decorators import login_required from django.views import View urlpatterns = [ url(r'^change-nameserver/$', login_required(views.bulkNSChange.as_view()), name='change_NS'), ] views: class bulkNSChange(GENERIC_PERMISSION_MIXIN,View): permissions_required = 'can_use_DNS_API' def post(self, request): context = { 'result': { 'bulkChange': False, } } body = json.loads(request.body) print body,'loaded' if body: assert type(body == dict) print 'eto po' log.info('PROCESSING CHANGE NS- {1} to {2}'.format(body['domain'], body['nameServer'])) context['result']['bulk'] = { 'bulkChange': True, 'bulkNS': 'YEAH' } return HttpResponse(json.dumps(context), content_type='application/json') js: function bulkUpdateNS(){ var prompt = confirm('Execute Bulk NS Changes? (This event is logged)') if (prompt){ var domain = document.getElementById('domain') var nameServer = document.getElementById('nameServer') var nsbody = { 'domain': domain.value, 'nameServer': nameServer.value } console.log(nsbody) $.ajax({ type: "POST", dataType: "json", url: "/domains/change-nameserver/", data: JSON.stringify(nsbody), success: function(result) { alert('Bulk Changing Domain NS started') }, error: function(err) { console.log(err) }, complete: function(){ domain.value ='' nameServer.value ='' $('#bulkChangeNSModal').modal('hide'); } }); } } -
How to use the Django DRF serializer for ManyToManyField
I'm trying to write a serializer for my models which has a ManyToManyField. My problem seems to be very similar to this example, but at this time I'm not interested in using a SlugField and nevertheless it's not clear to me what my problem is. models.py class Objective(models.Model): objective_name = models.CharField(max_length=10) objective_description = models.CharField(max_length=30) def __str__(self): return self.objective_name class Assessment(models.Model): objective = models.ManyToManyField(Objective) date_completed = models.DateField(auto_now_add=True) serializers.py class AssessmentSerializer(serializers.ModelSerializer): objective = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Assessment fields = ['name', 'date_completed', 'objective'] class ObjectiveSerializer(serializers.ModelSerializer): class Meta: model = Objective fields = '__all__' From the DRF docs, I thought that the following POST would create an Assessment object where I already have two Objective objects with id's of 3 and 4 respectively. { "name": "Quiz 3", "objective": [ 3, 4 ] } However, this creates the Assessment object but there is no link between it and the Objectives. { "name": "Quiz 3", "date_completed": "2020-03-17", "objective": [] } Is my serializer incorrect, or am I using wrong syntax for the POST, or is there a different issue? -
Convert virtualenv project to pipenv Without a requirements.txt File
I've set up a DigitalOcean droplet with Ubuntu, python 3.6, and django 3.0. The instructions I used installed virtualenv. I'd like to change to pipenv, which is what I use in development. The answers I've seen say to set it up in the same directory as the requirements.txt file. I've never seen any such file. I'm new to django so I'm guessing it was used in older versions. I do have a projectXdir that contains projectX and projectXenv. ProjectX contains the actual project. ProjectXenv contains bin, include, lib, lib64, pyvenv.cfg, and share. The bin has the packages I've installed. Where do I run pipenv to set it up for the project? What do I get rid of afterwards? -
Unknown Command: 'manage.py' in runserver in Pycharm
I have an app I want to run in Django and when I run it or just try to test in in runserver in Pycharm, it gives me the "Unknown command: 'manage.py' manage.py@ATWM_Django > manage.py "C:\Program Files\JetBrains\PyCharm 2019.1.3\bin\runnerw64.exe" C:\Users\dbkar\Desktop\ATWM_Django\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\pycharm\django_manage.py" manage.py C:/Users/dbkar/Desktop/ATWM_Django Tracking file by folder pattern: migrations Unknown command: 'manage.py' Type 'manage.py help' for usage. Process finished with exit code 1 -
Mounted a local direcotry in my Docker image, but it can't read a file from that directory
I'm trying to build a docker container with MySql, Django, and Apache images. I have set up this docker-compose.yml ... version: '3' services: mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3306" volumes: - my-db:/var/lib/mysql command: ['mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci'] web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application --reload -w 2 -b :8000 volumes: - ./web/:/app depends_on: - mysql apache: restart: always build: ./apache/ ports: - "9090:80" links: - web:web volumes: my-db: I would like to mount my docker Django image to a directory on my local machine so that local edits can be reflected in the docker container, which is why I have this volumes: - ./web/:/app in my "web" portion. This is the web/Dockerfile I'm using ... FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m … -
How do I correctly retrieve objects from a database using Django REST api?
I'm teaching my self how to use the Django REST api but I'm running into a JSONDecodeError. I'm trying to display posts depending on the user that is stored in the session. I'm storing the user username, password, and id in the session for later use. The JSONDecodeError is targeting the line with instruction posts = posts_response.json() when I look at the HTML error page Here's my views.py: posts_path = "http://127.0.0.1:8000/posts/" def index(request): if request.method=='GET': post_form = PostForm() posts_response = requests.get(posts_path) posts = posts_response.json() context = { 'post_form': post_form, 'post_list': posts, } return render(request, 'UserLanding/index.html', context) else: return render(request, "UserLanding/index.html") This is my viewsets: class PostView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer def get_queryset(self): query_set = self.queryset.filter(user=self.request.session['id']) return query_set class SubscriberView(viewsets.ModelViewSet): queryset = Subscriber.objects.all() serializer_class = SubscriberSerializer My registered urls: router = routers.DefaultRouter() router.register('posts', viewsets.PostView) router.register('users', viewsets.SubscriberView) And serializers: class SubscriberSerializer(serializers.ModelSerializer): class Meta: model = Subscriber fields = ('id', 'username', 'password') class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'post_text', 'pub_date', 'user') Please help me spot the problem. Thanks in advance -
Django Rest Framework - create object with field value from URL
Is it possible to use a ModelViewSet to create an instance from a POST request where one of the field values is specified in the URL? EG: POST /teams/3/members with data name = Bob should create Member(team_id=3, name="Bob") Conceptually similar to filtering against the url