Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"32 - Could not authenticate you." error in tweepy
I was working with tweepy with Django and the code was working fine. But, when I deployed the code on railway (similar to Heroku), the app showed these logs: File "/app/tweet_scrapper/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/venv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/venv/lib/python3.9/site-packages/django/apps/registry.py", line 124, in populate app_config.ready() File "/app/tweets/apps.py", line 10, in ready from . import jobs File "/app/tweets/jobs.py", line 85, in <module> scrap() File "/app/tweets/jobs.py", line 69, in scrap searched_tweets = api.search_tweets( File "/opt/venv/lib/python3.9/site-packages/tweepy/api.py", line 33, in wrapper return method(*args, **kwargs) File "/opt/venv/lib/python3.9/site-packages/tweepy/api.py", line 46, in wrapper return method(*args, **kwargs) File "/opt/venv/lib/python3.9/site-packages/tweepy/api.py", line 1309, in search_tweets return self.request( File "/opt/venv/lib/python3.9/site-packages/tweepy/api.py", line 263, in request raise Unauthorized(resp) tweepy.errors.Unauthorized: 401 Unauthorized 32 - Could not authenticate you. Traceback (most recent call last): File "/opt/venv/lib/python3.9/site-packages/gunicorn/arbiter.py", line 502, in spawn_worker worker.init_process() File "/opt/venv/lib/python3.9/site-packages/gunicorn/workers/base.py", line 114, in init_process self.wsgi = self.app.wsgi() File "/opt/venv/lib/python3.9/site-packages/gunicorn/app/base.py", line 66, in wsgi self.callable = self.load() File "/opt/venv/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/opt/venv/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/opt/venv/lib/python3.9/site-packages/gunicorn/util.py", line 356, in import_app __import__(module) File "/app/tweet_scrapper/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/venv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/venv/lib/python3.9/site-packages/django/__init__.py", line … -
Axios giving 401 (Unauthorized). I am trying to get userdata through react frontend passed to DRF Social Oauth2. Same working on POSTMAN
Below are the two files LoginScreen.JS which has a submit handler that submits the input. Here we import the axios instance from login.JS. I have also attached the same working example from PostMan. login.js const baseURL='http://127.0.0.1:8000/'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { 'Content-Type': 'application/json', accept: 'application/json' }, }); export default axiosInstance LoginScreen.js const submitHandler = (e) => { e.preventDefault() axiosInstance .post(`auth/token/`,{ username: email, password: password, grant_type: 'password', client_id: 'Vqvt1yp2HahF8KgwOS3BrWaCUX8ViDGCrn3VfJkz', client_secret: 'Vqvt1yp2HahF8KgwOS3BrWaCUX8ViDGCrn3VfJkz' }) .then((res) => { localStorage.setItem('access_token', res.data.access); localStorage.setItem('refresh_token', res.data.refresh); }); }; -
How to Create personal jwt token for user login through googl or facebook into app using django allauth
Hi I have created an app where I want to use social login through Django all auth package I can log in successfully to my app but how i can create a personal jwt token for the user who loggin through google Account -
Django Imagekit I/O operation on closed file
I'm using Imagekit to resize pictures on a website i'm developing with Django, I've used Imagekit before without any issues but I have a strange problem. I am using S3 for Media/Static files. When I upload an image in admin and refresh the template serving the images i get ValueError at / I/O operation on closed file error page. Then if I refresh the page it loads fine without a problem. I am using an ImageSpec field to resize images and using {{ image.thumbnail.url }} in my template. I am very much a beginner with Django so looking for some direction. Why will it work on a page reload and not when initially uploaded? Here are the relevant fields in my model. class Media(models.Model): image = models.ImageField(upload_to="media") thumbnail = ImageSpecField([Adjust(sharpness=1.1), ResizeToFill(800, 650)], source='image', format='JPEG', options={'quality': 100}) -
Cors problem in dockerized angular and django project
I have a problem that solves all day. I'm learning in a range of web development. Currently I'm learning docker. I dockerized my project in Angular using the nginx server. Same as my Django API where my Angular application connects to it. However, when angular uses the GET method the course error in the JS console. JS console Access to XMLHttpRequest at 'http://127.0.0.1:8000/api2/zdjecia/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Django console Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 31, 2022 - 14:12:10 Django version 3.2.16, using settings 'lobialogard.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [31/Oct/2022 14:14:14] "OPTIONS /api/aktualnosci/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:14] "OPTIONS /api3/archiwum/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:15] "OPTIONS /api/aktualnosci/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:15] "OPTIONS /ustawienia/strony/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:18] "OPTIONS /ustawienia/strony/ HTTP/1.1" 200 0 [31/Oct/2022 14:14:18] "OPTIONS /api/aktualnosci/ HTTP/1.1" 200 0 I unlocked all the methods and origins as below: My nginx.conf file server { listen 80; server_name localhost; location / { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; … -
URLValidator throws ValidationError exception in case of a correct url
I am validating a long url in my views.py original_url = request.POST.get('original_url') validator = URLValidator() try: validator(original_url) except ValidationError: return HttpResponse("Invalid URL") But even if the URL is syntactically correct, I see the ValidationError exception being executed. After placing print() statements in try block I also noticed that the code never gets into the try block but straightaway executes the exception. I have a finished code that is using this same approach but don't see any errors there. I am wondering what am I missing? -
How to create an instance from the 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} return … -
How to access to Django ORM DB in pytest?
I am writing a smoke test for a POST request to API Django using pytest. With a Post request, I write the value to the DB and check that it appears. The data from POST request appears in the database, but the test fails due to the error below. import requests from datetime import datetime from json_import.models import Sensor import pytest BASE_URL = "http://localhost:8000" POST_URL = "/api/write_values" @pytest.mark.django_db class TestAPI: def test_smoke(self): body = { "timestamp": f"{datetime.now()}", "sensor_values": [ { "sensor_id": "sensor1", "value": "1.1" } ] } response = requests.post(f'{BASE_URL}{POST_URL}', json=body) sensor1 = Sensor.objects.get(sensor_id='sensor1') sensor_value1 = sensor1.sensor_values.last() assert sensor_value1.sensor_value == 1.1 Received error E json_import.models.Sensor.DoesNotExist: Sensor matching query does not exist. /usr/local/lib/python3.9/site-packages/django/db/models/query.py:435: DoesNotExist Migrations are done, py test.ini is created. What could be the problem? I was looking for a solution to the problem in the documentation and on the forum. -
Django Python - Can`t install fixtures in test database
HiEveryone Got some problem why trying to load fixtures in Django test database. I made fixture of DB by exec command python manage.py dumpdata misxapp --format=yaml --indent=4 > misxapp/fixtures/misxapp.yaml In misxapp.tests.py I use StaticLiveServerTestCase class property "fixtures" fixtures = ['misxapp'] Then I run test python manage.py test misxapp.tests.TestAuthorization.test_login and get exception psycopg2.errors.UndefinedColumn: ERROR: column "date" in table "misxapp_insurancepolicy" doesn't exist. LINE 1: ..., "organization_id_id" = 34, "person_id_id" = 23, "date" = '... !!! BUT !!! column "date" exists both in models.py file and Postgresql database I assume that the problem is in the naming of the date field in Postgresql, but not sure at all. please tell me in which direction to dig, thanks!!! -
Website creates a new non-existent webpage after I visit website/class_id
My website creates a new non-existent website, after I visit my website/näytä_luokka/# (also, class_id). If I try to go to a page that is in the same urls.py file, I get an error because it tries to find a page website/näytä_luokka/luokat instead of going to website/luokat. This happens through navbar. If I try to go to a link that is in another urls.py, everything works fine. Switching from /luokat to other pages works also fine. I am using django to create website. So, here's a couple examples from my urls.py from django.urls import path from . import views urlpatterns = [ path('näytä_luokka/<luokka_id>', views.näytä_luokka, name="näytä-luokka"), path('luokat', views.kaikki_luokat, name="luokat"),' ] and .views def näytä_luokka(request, luokka_id): luokkalistaus = luokka.objects.get(pk=luokka_id) return render(request, 'tietokanta/näytä_luokat.html', {'luokkalistaus': luokkalistaus}) def kaikki_luokat(request): luokkalista = luokka.objects.all().order_by('nimi') return render(request, 'tietokanta/luokat.html', {'luokkalista': luokkalista}) ** the navbar.** </li> <li class="nav-item"> <a class="nav-link" href="luokat">Luokat</a> </li> I tried adding / after id number, but id didn't do anything. Thank you if you can help me figure this out. -
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.