Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Redux Django REST API: How to properly detail an object
I am using React / Redux with the Django REST API. Still learning, so please give pointers. I am trying to return an object by id and display its properties. Here is my viewset for the objects that I am trying to interact with: class ViewsetCSVFile(viewsets.ModelViewSet): queryset = CSVFile.objects.all() permission_classes = [ permissions.IsAuthenticated ] serializer_class = SerializerCSVFile def get_queryset(self): return self.request.user.csv_files.all() def perform_create(self, serializer): serializer.save(author=self.request.user) def retrieve(self,request,*args,**kwargs): obj_id = kwargs['pk'] obj = CSVFile.objects.get(id=obj_id) serialized = self.get_serializer(obj) return Response(serialized.data) In my actions.js file, here is the action to get a file by id: // GET FILE by ID export const getCsvFile = (id) => (dispatch,getState) =>{ axios.get(`/api/csv/${id}/`,tokenConfig(getState)) .then(res => { console.log(res); dispatch({ type:GET_CSV_FILE, payload:res.data }) }) .catch(err=> { dispatch( returnErrors(err.response.data,err.response.status)) console.log(err); } ) } Here is the page to display the object on the front end: import { useParams } from "react-router-dom" const CsvFileDetail = (props) => { const propTypes = { csvFiles: PropTypes.array.isRequired } const {id} = useParams(); const [csvFiles] = useState(0); useEffect(()=>{ props.getCsvFile(id); },[]) return ( <div> <h1> File id: {id} </h1> {csvFiles} <h1> </h1> </div> ) } const mapStateToProps = state =>({ csvFiles:state.csvFile.csvFile }) export default connect(mapStateToProps,{getCsvFile,deleteCsvFile})(CsvFileDetail); When calling console.log(res) in getCsvFile, I can see that the api … -
the tables I want to create do not add to the database
I would like to create my own database which will contain a People table where usernames and passwords will be stored. I have to create my own model by inheriting from AbstractBaseUser appLogin/models.py class Sector(models.Model): jobName = models.CharField(verbose_name = "jobName", max_length=50) idSector = models.CharField(verbose_name = "idSector", max_length=50, primary_key=True) class Meta: db_table = "Sector" class People(AbstractBaseUser): firstName = models.CharField(verbose_name = "firstName", max_length=20) name = models.CharField(verbose_name = "name", max_length=20) regNumber = models.CharField(verbose_name="regNumber", max_length=20, primary_key=True) idSector = models.ForeignKey(Sector, on_delete=models.CASCADE) USERNAME_FIELD ="regNumber" REQUIRED_FIELDS = ["firstName", "name"] objects = UserManager() class Meta: db_table = "People" appLogin/admin.py from django.contrib import admin admin.site.register(Secteur) project/settings.py AUTH_USER_MODEL="appLogin.People" After having done this, i don't have the tables in the db.sqlite3 python manage.py makemigrations python manage.py migrate -
Django smart selects doesn't work with JS cloning
I'm trying to create a page with ability to add any amount of form-copy. I use django-smart-selects to make my form's field chained. It works fine if I have only 1 form on page. Then I'm using javascript to make a function to clone form instance by pressing button and addind new form's ids to these clones. The problem is when I press "+" button I get new cloned form on page, but chained-selection doesn't work anymore, and it seems that this clone copying all my choices from the firs form and remembering this state. I see in terminal this response every time I choose any selection in chained fields: [31/Oct/2022 16:42:27] "GET /chaining/filter/cash_table/LevelOne/flowtype/cash_table/CashFlowPattern/level_one/1/ HTTP/1.1" 200 115 [31/Oct/2022 16:42:29] "GET /chaining/filter/cash_table/LevelOne/flowtype/cash_table/CashFlowPattern/level_one/2/ HTTP/1.1" 200 105 But in cloned forms it doesn't happen. My Formset is: forms.py from django import forms from .models import CashFlowPattern from django.forms import modelformset_factory class CashFlowForm(forms.ModelForm): class Meta: model = CashFlowPattern fields = '__all__' CashFowFormSet = modelformset_factory( CashFlowPattern, fields=( 'flow_type', 'level_one', 'level_two', 'eom', 'amount', 'comment' ), extra=1 ) views.py class FormAddView(TemplateView): template_name = 'cash_table/index.html' def get(self, *args, **kwargs): formset = CashFowFormSet(queryset=CashFlowPattern.objects.none()) return self.render_to_response({'formset': formset}) def post(self, *args, **kwargs): end_of_month = (datetime.datetime.now() + relativedelta(day=31)).strftime('%Y-%m-%d') formset = CashFowFormSet(data=self.request.POST) if … -
EC2 Ubuntu - nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Unknown error)
I'm getting this error after running sudo nginx command nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Unknown error) nginx: [emerg] bind() to [::]:80 failed (98: Unknown error) nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Unknown error) nginx: [emerg] bind() to [::]:80 failed (98: Unknown error) nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Unknown error) nginx: [emerg] bind() to [::]:80 failed (98: Unknown error) nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Unknown error) nginx: [emerg] bind() to [::]:80 failed (98: Unknown error) nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Unknown error) nginx: [emerg] bind() to [::]:80 failed (98: Unknown error) nginx: [emerg] still could not bind() Here is my security settings on AWS EC2: In my Django project, I've created an config file for nginx: (nginx.conf) (I'm also using uwsgi as the second web server that is working fine) # the upstream components nginx needs to connect to upstream dcohort { server unix:///tmp/dcohort.sock; } server { listen 80; listen [::]:80; server_name *.amazonaws.com; access_log off; error_log /home/ubuntu/dcohort/logs/nginx_error.log; location / { include /etc/nginx/uwsgi_params; uwsgi_pass dcohort; } } then imported the configuration to /etc/nginx/nginx.conf http { include /home/ubuntu/dcohort/config/nginx.conf; # ... } -
How do i make my route path visible on a leaflet map?
I have a functionality in website that gets the users coordinates and create a route to the place where the user it going. like so http://www.liedman.net/leaflet-routing-machine/tutorials/basic-usage/ . However, it is not working i cant seem to figure out what is with the code // get place coordinates from a django variable I passed in the template const latitude = document.getElementById('lat').textContent; const longtitude = document.getElementById('lon').textContent; let btn = document.getElementById('create_route'); console.log('check w') // Creating map options let mapOptions = { center: [latitude, longtitude], zoom: 18, zoomControl: true, zoomAnimation: true, } // Creating a map object (I'm guessing the error is somewhere down here...) var map = new L.map('map', mapOptions); var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }); map.addLayer(layer); L.marker([latitude,longtitude]).addTo(map); btn.addEventListener("click",function create_route(e){ function success(pos) { const crd = pos.coords; let crdLat = crd.latitude, crdLon = crd.longitude; L.Routing.control({ waypoints: [ L.latLng(latitude,longtitude), L.latLng(crdLat,crdLon) ], autoRoute: true, routeWhileDragging: true }).addTo(map); } //get user location navigator.geolocation.getCurrentPosition(success); }) The two markers show up on the map when i click the button but the path/route i want isnt displayed.Also i get this error in the console. leaflet-routing-machine.js:88 GET https://router.project-osrm.org/route/v1/driving/-77.3396498,25.0781526;55.4333172,-4.6083844?overview=false&alternatives=true&steps=true&hints=; 400 and this leaflet-routing-machine.js:15868 Routing error: { "message": "HTTP request failed: undefined", "url": "https://router.project-osrm.org/route/v1/driving/-77.3396498,25.0781526;55.4333172,-4.6083844?overview=false&alternatives=true&steps=true&hints=;", "status": -1, "target": … -
Django-grpc-framework generates strange gRPC code
When I generate gRPC code in my django-grpc-framework project using command: python -m grpc_tools.protoc --proto_path=./ --python_out=./temp --grpc_python_out=./temp ./config.proto something generates, but config_pb2 looks so empty: # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: config.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0c\x63onfig.proto\x12\x0c\x63onfig_proto\x1a\x1bgoogle/protobuf/empty.proto\"u\n\rConfigMessage\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\t\x12\x0f\n\x07is_used\x18\x03 \x01(\x08\x1a\x31\n\x03Key\x12\x13\n\x0bservice_key\x18\x01 \x01(\t\x12\x15\n\rservice_value\x18\x02 \x01(\t\"\x1a\n\x18\x43onfigMessageListRequest\"*\n\x1c\x43onfigMessageRetrieveRequest\x12\n\n\x02id\x18\x01 \x01(\x05\x32\x88\x03\n\x10\x43onfigController\x12O\n\x04List\x12&.config_proto.ConfigMessageListRequest\x1a\x1b.config_proto.ConfigMessage\"\x00\x30\x01\x12\x44\n\x06\x43reate\x12\x1b.config_proto.ConfigMessage\x1a\x1b.config_proto.ConfigMessage\"\x00\x12U\n\x08Retrieve\x12*.config_proto.ConfigMessageRetrieveRequest\x1a\x1b.config_proto.ConfigMessage\"\x00\x12\x44\n\x06Update\x12\x1b.config_proto.ConfigMessage\x1a\x1b.config_proto.ConfigMessage\"\x00\x12@\n\x07\x44\x65stroy\x12\x1b.config_proto.ConfigMessage\x1a\x16.google.protobuf.Empty\"\x00\x62\x06proto3') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'config_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None _CONFIGMESSAGE._serialized_start=59 _CONFIGMESSAGE._serialized_end=176 _CONFIGMESSAGE_KEY._serialized_start=127 _CONFIGMESSAGE_KEY._serialized_end=176 _CONFIGMESSAGELISTREQUEST._serialized_start=178 _CONFIGMESSAGELISTREQUEST._serialized_end=204 _CONFIGMESSAGERETRIEVEREQUEST._serialized_start=206 _CONFIGMESSAGERETRIEVEREQUEST._serialized_end=248 _CONFIGCONTROLLER._serialized_start=251 _CONFIGCONTROLLER._serialized_end=643 # @@protoc_insertion_point(module_scope) So when I look at config_pb2_grpc i see imports: config__pb2.ConfigMessage But there is no implemented ConfigMessage in config_pb2. And more then this config_pb2 has one underscore and this import has two underscores. In my mind this is rather strange. Is it all right? For example when i generate code in my ordinary django-rest-framework project using: protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/data.proto I get in data_pb2.py: ... ConfigMessage = _reflection.GeneratedProtocolMessageType('ConfigMessage', (_message.Message,), { ... -
How to make an instance from Parent Model in Django
sorry if my question looks petty, I have a problem in making an instance from the below parent model below , I wanted to get doctor's name into the patient's table but in turn this error: Cannot assign "'Ann Lindsey'": "Patientinfo.Referred_doctor" must be a "Doctor" instance. (is there a way I can make field (Referred_doctor) an instance of DOCTOR model?) any help please. here is my code; models.py class Doctor(models.Model): Profile_picture = models.ImageField(null=True, default='avatar.png', upload_to='images/') First_Name = models.CharField(max_length=200) Last_Name = models.CharField(max_length=100) Doctor_Bio = models.TextField(null=True) Admission_Date = models.DateTimeField(auto_now=True) Date_of_Birth = models.DateField() Doctor_Category = models.CharField(max_length=200) def __str__(self): names = (self.First_Name, self.Last_Name) stringified = ' '.join(names) return stringified class Patientinfo(models.Model): Name = models.CharField(max_length=255) Gender = models.CharField(max_length=200) Marital_Status = models.CharField(max_length=100) Telephone = models.CharField(max_length=30) Admission_date = models.DateTimeField(auto_now=True) Patient_Status = models.CharField(max_length=200) Symptoms = models.TextField() Referred_deparment = models.CharField(max_length=200) Referred_doctor = models.ForeignKey(Doctor, on_delete=CASCADE) def __str__(self): return self.First_Name views.py def padmform(request): patientdata = Patientinfo.objects.all() doctors = Doctor.objects.all() if request.method == 'POST': Name = request.POST.get('Name') Gender = Request.POST.get('Gender') Marital_Status = Request.POST.get('Marital_Status') Telephone = Request.POST.get= Request.POST.get('Telephone') Patient_Status = Request.POST.get('Patient_Status') Symptoms = Request.POST.get('Symptoms') Referred_deparment = Request.POST.get('Referred_deparment') Referred_doctor = Request.POST.get('Referred_doctor') patientdata = Patientinfo(Name=Name, Gender=Gender, Marital_Status=Marital_Status, Telephone= Telephone, Patient_Status=Patient_Status, Symptoms=Symptoms, Referred_deparment=Referred_deparment, Referred_doctor=Referred_doctor) patientdata.save() messages.success(request, 'New patient successfully admitted') return redirect('Patients') context = {'patientinfo':patientdata, 'doctors':doctors} … -
ValueError: Cannot assign "1": "LeadFacilityAssign.assigned_facilities" must be a "Facility" instance
I've been trying to create an api endpoint to update my "lead" objects and add a list of facilities to them when sending a put request (each time a different amount of facilities). The lead objects already exist inside the database so do the facility objects. Since i need a date and time associated to each facility when they are being added to a lead i created the "LeadFacilityAssign" class. Since i wasn't able to get it to work i tried to do it just with a post request for now, during the lead creation process. I was told that i need to use bulk_create if i need to add more than one facility this way. I couldn't find anything on bulk_create inside the drf documentation so i decided to do this for now just with one facility and improve my code from there one issue at a time since i'm new to drf. Does anyone know what is causing this error? I tried a few different things but nothing worked so far. ValueError: Cannot assign "1": "LeadFacilityAssign.assigned_facilities" must be a "Facility" instance. serializers.py class LeadUpdateSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = serializers.IntegerField(required=True) datetime = serializers.DateTimeField(required=True) class Meta: model = Lead … -
Django Admin Templates Over-Ride
I am new to Django my task is to customize and override all the templates of Django Admin Could you please help in Finding a website or tutorial which helps me in building from scratch Thanks in advance -
Is it possible to create an artificial model in FactoryBoy?
I wanted to know if in the tests it is possible to somehow create an "artificial" model using FactoryBoy without touching models.py I mean a simple model such as: class SomeMod(models.Model): title = models.CharField(max_length=255, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.title -
SQL to Django ORM for group by with distinct
What would be the django orm translation of the below query? select date(start_date) as start, count(*) as tournament_count, count(distinct(user_id)) from tournament group by start I'm not sure how to do the count(distinct(user_id) part. I think it should look something like Tournament.objects.filter( Q(start_date__date__gte = start_date) & Q(end_date__date__lte = end_date) ).annotate(date=TruncDate('start_date')).values('date').annotate(tournaments=Count('id')).order_by() But this doesn't get me the distinct part of the original query -
error 400 bad request when sending a request using react (fetching data through react to django rest-framework)
i'm new here and excuse my unfamiliarity with the proper structure of the post. so i am trying to send json data to a django server using the following link http://localhost:8000/profiles/ and I kept searching for hours and I did eveything possible solving the popular 405 error which was the first error. I tried all options possible based on the internet, articles and answers here and finally the options in create.jsx eliminated the first 405 error related to cors. now i'm getting a bad request whenever I try to send data. this is my react code: create.jsx import { useState } from "react"; const Create = () => { const[name, setName] = useState(""); const[email, setEmail] = useState(""); const[mobile_number, setMobile] = useState(""); const[national_id, setID] = useState(""); const[password, setPassword] = useState(""); const handleSubmit = (e) => { e.preventDefault(); const blog = { name, email, mobile_number,national_id,password }; const options={ mode: 'no-cors', // no-cors, *cors, same-origin cache: 'no-cache', method: 'POST', headers: { 'Accept': 'application/json, text/plain, */*', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers', 'Access-Control-Allow-Methods': '*', "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}, body : JSON.stringify(blog) } fetch('http://localhost:8000/profiles/', options) .then(() => { console.log('new radiologist added'); }).catch(error => { // handle the error here console.log(e); }); } return … -
AttributeError: module 'os' has no attribute 'uname' (drf with docker)
Hi Im using docker and drf, and here is my actions and problems. first, I run this instruction: pip install -r requirements.txt --use-deprecated=legacy-resolver and my requirements file is this.: asgiref==3.5.2 backports.zoneinfo==0.2.1 Django==4.1.2 django-dotenv==1.4.2 djangorestframework==3.14.0 mysql-connector-python==8.0.26 mysqlclient==2.1.1 protobuf==4.21.9 pytz==2022.5 sqlparse==0.4.3 uWSGI==2.0.21 then this error arise: error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [8 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\jia52\AppData\Local\Temp\pip-install-2eb55qko\uwsgi\setup.py", li ne 3, in <module> import uwsgiconfig as uc File "C:\Users\jia52\AppData\Local\Temp\pip-install-2eb55qko\uwsgi\uwsgiconfig.p y", line 8, in <module> uwsgi_os = os.uname()[0] AttributeError: module 'os' has no attribute 'uname' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> uWSGI what should I do to solve this problem? I don't know where can I found answer. -
How to run single job of two jobs implemented on pull request in github actions?
I have two defined two jobs. I want to run only one job upon pull request and other job on push. I tried some solutions but did not work -
How to have value for which subprocess created in viewflow
I want to have my attribute in the subprocess for which that subprocess is created, but i don't know how exactly i can do that. -
How to do indexing in python dictionary using html template
def send_template(request): my_folders = Folders.objects.filter(parent=None).order_by('name') new_headers = {} for foldr in my_folders: en_count = FolderEntries.objects.filter(folder = foldr.id ).count() new_headers[foldr.id] = en_count return render(request, 'folders.html', 'new_headers':new_headers) new_headers contains data in such way:- {190: 1, 196: 0, 199: 0, 121: 0, 185: 1, 194: 1, 108: 3, 168: 4, 197: 0, 195: 0, 198: 0, 171: 1} Now i want to get new_headers in html template using indexing For example:- new_headers[190] How to do this..Anyone plz help i am sending this data to my html template:- {190: 1, 196: 0, 199: 0, 121: 0, 185: 1, 194: 1, 108: 3, 168: 4, 197: 0, 195: 0, 198: 0, 171: 1} Now i want to do indexing in this data. -
Hello! How I can get Json in new format like just text/value
`` [ { "name": "doc2", "directions": [ { "mar", "qwe" } ] }, { "name": "John", "directions": [ { "Surgery", "qwe" } ] } ] NOT like this [ { "name": "doc2", "directions": [ { "name": "mar" }, { "name": "qwe" } ] }, { "name": "John", "directions": [ { "name": "Surgery" }, { "name": "qwe" } ] } ] Models.py class Directions(models.Model): name = models.CharField(max_length=355) def __str__(self): return self.name class Doctors(models.Model): name = models.CharField(max_length=255) directions = models.ManyToManyField(Directions) def __str__(self): return self.name Serializer.py class DirectionsSerializer(serializers.ModelSerializer): class Meta: model = Directions fields = ('name',) class DoctorsSerializer(serializers.ModelSerializer): directions = DirectionsSerializer(many=True) class Meta: model = Doctors fields = ('name', 'directions') -
Django (and DRF) "ContentType matching query does not exist" on unmanaged model
I'm getting the error ContentType matching query does not exist. on an unmanaged (managed = False) model. I thought it would just pull from the database, so I'm not sure why it's checking the content types. My plan was to have a history app which pulls history data from tables created by the library django-simple-history. So I've got the app model (using the Poll app for example): class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', auto_now_add=True) history = HistoricalRecords() Then I've got the historical version of that model (from the database created by django-simple-history): class HistoricalPoll(models.Model): id = models.BigIntegerField() question = models.CharField(max_length=200) pub_date = models.DateTimeField() history_id = models.AutoField(primary_key=True) history_date = models.DateTimeField() history_change_reason = models.CharField(max_length=100, blank=True, null=True) history_type = models.CharField(max_length=1) history_user = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'polls_historicalpoll' And a serializer to for the history model: class HistoricalPollSerializer(serializers.ModelSerializer): class Meta: model = HistoricalPoll fields = '__all__' And a viewset: class HistoricalPollViewSet(viewsets.ModelViewSet): serializer_class = HistoricalPollSerializer permission_classes = [permissions.IsAuthenticated] queryset = HistoricalPoll.objects.all() And a URL: router.register(r"history", HistoricalPollViewSet) But when I access /history I only get an error: DoesNotExist at /history/ ContentType matching query does not exist. Why is it not simply just pulling data from the … -
Django, CORS "Access-Control-Allow-Origin" error
Can't figure out what's wrong with my Django DRF api endpoint. I'm getting a CORS error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. Problem is, I followed every step online to fix this. I've installed 'django-cors-headers' Added corsheaders app to INSTALLED_APPS above rest_framework and the app that includes api endpoint. Added cors middleware to the top of the middleware list in settings.py Added 'CORS_ALLOWED_ORIGINS = ('http://localhost:3000' # React app) (Also tried with CORS_ORIGIN_ALLOW = True) Quadruple-checked that API POST request includes a trailing slash. Nothing seems to fix it. Am I forgetting something? Thanks for any help. This is my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'core.apps.CoreConfig', ] CORS_ALLOWED_ORIGINS = ( 'http://localhost:3000', # for localhost (REACT Default) ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.CommonMiddleware', ] Not sure how revelant it is, but If I send POST request from insomnia, it works fine, but from React, it doesn't, this is my react request just in case: const postSomeData = async () => { const res = await axios.post( "http://127.0.0.1:8000/api/", { promptQuery: "pls just work … -
How to populate checkboxes in a table with values from a Django model
My html table has a column that contains a checkbox. The user can check or uncheck it. The value (boolean) is stored in the Django model Subscriber under Subscriber.participates. All objects of Subscriber are imported into the HTML using a Django view (context = {'subscribers' : Subscriber.objects.all(),}). When loading the table, the checkboxes must be set to the correct value. To that purpose I have written a javascript function, which is invoked in the <input> element. However, the checkboxes all remain unchecked, though I have verified through /admin/ in Django that some of the values in the dbase are indeed "TRUE". firstName and lastName load without any problem into the table. What did I do wrong? <head> <meta charset="UTF-8"> <title>Participants</title> <script> function checkBox() { if({{ x.participates }}){ document.getElementById("checkbox").checked = true; } else { document.getElementById("checkbox").checked = false; } } </script> </head> <body> <table> {% for x in subcribers %} <tr> <form action="updateSuscribers/{{ x.id }}" method="post"> {% csrf_token %} <td>{{ x.firstName }}</td> <td>{{ x.lastName }}</td> <td> <input id="checkbox" type="checkbox" name="participates" onload="checkBox()"> </td> </form> </tr> {% endfor %} </table> </body> -
I refer django 1.11 version but I install and practice django 4.2.1 version so i got to many errors so please guide me
I refer django 1.11 version but I install and practice django 4.2.1 version so i got to many errors so please guide me every command shows an error sometimes its very hard to diagnosis -
disconnection does not happen
I want to set up the disconnection. I have a page, Page 1, that is only accessible to an authenticated user. When i disconnect I can still access page 1. And i have anothers questions, How does Django know to execute the logout_user function ? (I have the same question for the login but as it works I didn't ask myself the question ^^). And why do we indicate a redirection in the return when in the html we already indicate the redirection ? appIdentification/views.py from django.contrib.auth import authenticate, login, logout def logout_user(request): logout(request) messages.success(request, ("You Were Logged Out!")) return redirect('home') appIdentification/urls.py from django.urls import path from . import views urlpatterns = [ path('/login', views.login_user, name="login"), path('', views.logout_user, name="logout"), ] mainApp/template/mainApp/page1.html <body> <h1> PAGE 1 </h1> {% if user.is_authenticated %} <a href="{% url 'login' %}"> Logout </a> {% endif %} </body> mainApp/views.py @login_required def page1(request): return render(request, 'mainApp/p1.html', {}) mainApp/urls.py from django.urls import path, include from . import views path('mainApp', include('django.contrib.auth.urls')), path('mainApp', include('appIdentification.urls')), path('home', views.home, name="home"), path('p1', views.page1, name="p1"), -
Django Rest Framework: upload image to a particular existing model's object
Hey I am trying to upload an image using Rest API[via Postman] to an object which already exists, and has all its field populated except for the image. I am using PUT method, to first get the object I want to upload the image to then trying to pass it through the serializer. The images are to be uploaded to my S3 bucket. The code for my views.py: @api_view(['PUT']) @permission_classes([IsAuthenticated]) def putproof(request): app=MasterTaskHolder.objects.filter(title=request.data['title'],user=request.user) serializer=ImageUploadSerializer(app,data=request.data,partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response("Posted") My serializer: class ImageUploadSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MasterTaskHolder fields = ( 'title','image' ) My model: class MasterTaskHolder(models.Model): status_code = [ ('C', 'Completed'), ('P', 'Pending'), ] title = models.CharField(max_length=50) point = models.IntegerField() category = models.CharField(max_length=50, null=True, blank=True) status = models.CharField(max_length=2, choices=status_code, default='P') user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, upload_to="imageproof/") def __str__(self): return (f'{self.user} - '+(f'{self.title}')) I am really new to Django and DRF, any help would be appreciated. Thank you. -
Multiple try except in a serializer Django
I have a Warehouse model like the following: class ShelfBin(models.Model): bin_id = models.IntegerField(default=0) bin_name = models.CharField(max_length=50, default=0) class UnitShelf(models.Model): shelf_id = models.IntegerField(default=0) shelf_name = models.CharField(max_length=50, default=0) bin = models.ManyToManyField(ShelfBin, blank=True) class AisleUnit(models.Model): unit_id = models.IntegerField(default=0) unit_name = models.CharField(max_length=50, default=0) shelf = models.ManyToManyField(UnitShelf, blank=True) class ZoneAisle(models.Model): aisle_id = models.IntegerField(default=0) aisle_name = models.CharField(max_length=50, default=0) unit = models.ManyToManyField(AisleUnit, blank=True) class WarehouseZone(models.Model): zone_id = models.IntegerField(default=0) zone_name = models.CharField(max_length=50, default=0) aisle = models.ManyToManyField(ZoneAisle, blank=True) class Warehouse(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=250, default=0) address = models.CharField(max_length=500, default=0) zones = models.ManyToManyField(WarehouseZone, blank=True) for this I have created a serializer like the following: class WarehouseSerializer(serializers.ModelSerializer): zones = WarehouseZonesSerializer(many=True) class Meta: model = Warehouse fields = "__all__" def create(self, validated_data): print("validated data warehouse", validated_data) zone_objects = validated_data.pop('zones', None) instance = Warehouse.objects.create(**validated_data) for item in zone_objects: aisle_objects = item.pop('aisle') wz_obj = WarehouseZone.objects.create(**item) for data in aisle_objects: unit_objects = data.pop('unit') za_obj = ZoneAisle.objects.create(**data) for u_data in unit_objects: shelf_objects = u_data.pop('shelf') au_obj = AisleUnit.objects.create(**u_data) for s_data in shelf_objects: bin_objects = s_data.pop('bin') us_obj = UnitShelf.objects.create(**s_data) for b_data in bin_objects: b_obj = ShelfBin.objects.create(**b_data) us_obj.bin.add(b_obj) au_obj.shelf.add(us_obj) za_obj.unit.add(au_obj) wz_obj.aisle.add(za_obj) instance.zones.add(wz_obj) return instance Now the problem is that sometimes warehouse can have zone, aisle, units, etc(all 5 sub-levels) but sometimes it can only be 1,2 … -
How does multiple user types logging in & out work in a live environment? [Django]
I have a web app that has two different user types, Nurses and Doctors, and they can both log in and out. I opened two tabs and logged in as a Nurse in one tab and as a Doctor in the other. However, when I log out of either one of those tabs, the other will be automatically logged out as well. I have read this link How can made multiple user login at same time in same browser in django project and understand why this happens. I know that I can work around it by logging in from different web browsers and by using Incognito mode. However, how do I code it such that in a live environment, users can actually logout without logging other users out?