Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Doing a POST with both data and file to multiple models
I'm trying to send some data and files when creating a new post in my tables. I want to be able to send both the data for the fields and file/files at the same time. My models: class Tool(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_("Name"), max_length=70) description = models.TextField(_("Description"), blank=True) department = models.ManyToManyField( "models.Department", verbose_name=_("department"), blank=True) tag = models.ManyToManyField( "models.Tag", verbose_name=_("tag"), blank=True) byUser = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("createdby"), related_name="byuser", blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): """returning a string representation of Tool""" return self.name class ImageTool(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, blank=True) tool = models.ForeignKey( Tool, on_delete=models.CASCADE, related_name='images') image = models.ImageField( _("Image"), upload_to=tool_image_file_path, blank=True, null=True) byUser = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("createdby"), related_name="byuser", blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): """Returning a string representation of the image""" return '%s %s' % (self.tool, self.name) class Department(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_("Name"), max_length=70) description = models.TextField(_("Description"), blank=True) history = HistoricalRecords() def __str__(self): return self.name class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_("Name"), max_length=70) description = models.TextField(_("Description"), blank=True) def __str__(self): """Return string representation of tag""" return self.name This is my unittest right now. def test_upload_image_when_creating_tool(self): """ Creating a tool and upload image at the same time """ uuidTool = '2f44ab21-4e05-4e0a-ade1-05cdbdbf1cab' … -
django-allauth not saving google extra data
here how my settings.py is # other settings SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': [ 'email', 'public_profile', 'user_friends', 'user_gender', 'user_birthday', 'user_location', 'user_link', 'user_age_range', ], # 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, # 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'first_name', 'last_name', 'middle_name', 'name', 'short_name', 'name_format', 'gender', 'birthday', 'age_range', 'friends', 'location', 'picture', 'link', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': False, # 'LOCALE_FUNC': 'path.to.callable', 'VERSION': 'v7.0', }, 'google': { 'SCOPE': [ # 'profile', # 'email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/user.emails.read', 'https://www.googleapis.com/auth/user.phonenumbers.read', 'https://www.googleapis.com/auth/user.birthday.read', 'https://www.googleapis.com/auth/profile.agerange.read', 'https://www.googleapis.com/auth/user.addresses.read', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } it's working fine with facebook and i get what i want there, but with google everything works will while signing (asks for permissions.. everything goes will) it authenticates the user and save it on db, but on extra data field i just get { "id": "...", "email": "...", "verified_email": true, "name": "..", "given_name": "..", "picture": "..", "locale": "en" } so what happens to birthday, gender, addresses, agerange and other fields. -
Where do i find senior django developers [closed]
I’m looking for senior django-react fullstack developers for a project. Pays well. Please dm or answer this post -
post form changed to get in view
I am using a createuser html page in my django project with a form that sets method to 'post'. but when recieving the call in the corresponding view it has changed to 'get' as can be seen in my print(request.method). Why? createuser.html: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> urls.py: path('createuser',views.createuser,name='createuser'), views.py: def createuser(request): print('method: ',request.method) if request.method=='POST': print('in post') form=SingupForm(request.POST) if form.is_valid(): form.save() username=form.cleaned_data.get('username') raw_password=form.cleaned_data.get('password') user=authenticate(username=username,password=raw_password) login(request,user) return redirect('edit.html') else: form=SignupForm() return render(request,'createuser.html',{'form':form}) else: print('no post..') return render(request,'edit2.html') -
When running pip install channels I get the following this error
ERROR: Command errored out with exit status 1: command: 'E:\Users\S.Mary\Documents\WebProject1\chatty_env\Scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'c:\users\s3c67~1.mar\appdata\local\temp\pip-install-spnlrp\async-timeout\setup.py'"'"'; file='"'"'c:\users\s3c67~1.mar\appdata\local\temp\pip-install-spnlrp\async-timeout\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'c:\users\s3c67~1.mar\appdata\local\temp\pip-pip-egg-info-yzixua' cwd: c:\users\s3c67~1.mar\appdata\local\temp\pip-install-spnlrp\async-timeout Complete output (5 lines): Traceback (most recent call last): File "", line 1, in File "c:\users\s3c67~1.mar\appdata\local\temp\pip-install-spnlrp\async-timeout\setup.py", line 1, in import pathlib ImportError: No module named pathlib ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Nginx Permission Denied but has permission (nginx, gunicorn, django)
I have tried to get rid of the error message for over 6 hours, but I can't still figure it out. At First, I had my Django+React project directory at /home/pi/pidjango and I got a 403 Forbidden(css, js) Error message from Nginx, so I searched for a long time and I moved my project (pidjango) to /home/pi/.local/share and it seemed to be fine. Then I got a 502 Bad Gateway Error, and also fixed that (It was a problem from nginx) and I got 403 error again. It is the error about nginx not getting static files(css, js) and I gave chmod 755 (-rwxr-xr-x) and it still doesn't work. Can anybody solve this? Thank you. I tried this tutorial(but except postgres) $ sudo tail -F /var/log/nginx/error.log *3 open() "/home/pi/.local/share/pidjango/static/css/main.js" failed (13: Permission denied), client: 127.0.0.1, server: localhost, request: "GET /static/frontend/main.js HTTP/1.1", host:"127.0.0.1", referrer: "http://127.0.0.1" *3 open() "/home/pi/.local/share/pidjango/static/css/index.css" failed (13: Permission denied), client: 127.0.0.1, server: localhost, request: "GET /static/frontend/index.css HTTP/1.1", host:"127.0.0.1", referrer: "http://127.0.0.1" *3 open() "/home/pi/.local/share/pidjango/static/css/main.js" failed (13: Permission denied), client: 127.0.0.1, server: localhost, request: "GET /static/frontend/main.js HTTP/1.1", host:"127.0.0.1", referrer: "http://127.0.0.1" # nginx (sites-enabled) server { listen 80; server_name localhost 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location … -
Django View Only Returns Data for one part of QuerySet
I am trying to send the following thing to the front end: Objects (venues in this case) that have been "liked" by somebody the user follows within a particular set of geocoordinates on a Google Map The way my view is currently set up seems to only be sending back the id of the person the user follows but not any of the cafes they have liked (I am testing in a space where this definitely exists). I'm not sure how to fix the problem. Views.py def get_friends(request): template_name = 'testingland/electra.html' neLat = request.GET.get('neLat', None) neLng = request.GET.get('neLng', None) swLat = request.GET.get('swLat', None) swLng = request.GET.get('swLng', None) ne = (neLat, neLng) sw = (swLat, swLng) xmin = float(sw[1]) ymin = float(sw[0]) xmax = float(ne[1]) ymax = float(ne[0]) bbox = (xmin, ymin, xmax, ymax) geom = Polygon.from_bbox(bbox) friends = UserConnections.objects.filter( follower=request.user ) cafes = mapCafes.objects.filter( geolocation__coveredby=geom, uservenue__user_list__user__pk__in=friends ).distinct() friend_list = [[friend.followed.username] for friend in friends] friend_cafe_list = [[cafe.cafe_name, cafe.cafe_address, cafe.geolocation.y, cafe.geolocation.x] for cafe in cafes] return JsonResponse([ { 'friends': friend_list, 'cafes': friend_cafe_list } ], safe=False) Models.py class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) … -
New to django, my terminal thinks that there is a syntax error with "path"
path('details/<int:pk>/', ArticleDetailView.as_view(), name="article_details"), my terminal thinks that there is syntax error here, specifically an arrow that points to the 'h' in 'path' i am running ubuntu 18.04 on a jetson nano, and this is in urls.py. terminal page after python3 manage.py runserver -
How to properly add a m2m 'through' field in django models? Now I am getting this error: 'M2M field' object has no attribute '_m2m_reverse_name_cache'
Hey guys I am trying to add a m2m through field to have assistants to my 'Department' model to call like department.assistants.all(), but while doing so, I am getting this error AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'. I also tried migrating everything to a new db to test. This is my model: class Department(models.Model): id = models.BigAutoField(primary_key=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) assistants = models.ManyToManyField('Department', through='Assistants', related_name='dep_assistants', symmetrical=False) class Assistants(models.Model): id = models.BigAutoField(primary_key=True) department = models.ForeignKey(Department, related_name='of_department', on_delete=models.CASCADE) assistant = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='dt_assistant', verbose_name="Department Assistant", on_delete=models.CASCADE) added = models.DateTimeField(auto_now_add=True) I am pretty new to this concept. Can someone tell me what I did wrong here? Thanks -
http://127.0.0.1:8000/admin | How to resolve this type errror issue?
https://i.stack.imgur.com/pybod.jpg This type error is coming as output when i am typing http://127.0.0.1:8000/admin. Can anyone help me ? Plz...Need urgent help -
In Django ProgrammingError at /profile/edit/1/ earlier I used sqlite3 database it was fine but when I changed to postgresql it caused this problem
ProgrammingError at /profile/edit/1/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... Internal Server Error: /profile/edit/1/ Traceback (most recent call last): File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\jobapp\permission.py", line 21, in wrap return function(request, *args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\account\views.py", line 208, in employee_edit_profile user = get_object_or_404(User, id=id) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\shortcuts.py", line 76, in get_object_or_404 return queryset.get(*args, **kwargs) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 431, in get num = len(clone) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\models\sql\compiler.py", line 1169, in execute_sql cursor.execute(sql, params) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Joych\Downloads\Backup JobB\Job-B\Job-Portal-Django-master\xb\lib\site-packages\django\db\backends\utils.py", … -
I want to save my users name,email,password on a separate table instead django-auth table
Please give some suggestions on how to create my models to achieve the above requirements. -
How to make the 'return' from a django model conditional to the value of a global variable?
I am a novice in both Python and Django, and I am struggling to find the way to make a 'return' from a Django model conditional upon the value of a global variable. More specifically, I am designing an app to run an interview with the user / visitor. In the interview the questions to the user can be in past or present tense. This depends on an introduction view from which I get the choice from the user, i.e. either 'past' or 'now'. My model is class Question(models.Model): key = models.CharField(max_length=50) value = models.CharField(max_length=50) question_text_past = models.CharField(max_length=2000) question_text_now = models.CharField(max_length=2000) def __str__(self): global TENSE if TENSE == 'past': return self.question_text_past else: return self.question_text_now However, no matter what I've tried (while testing the code within the shell), my model does not reflect the changes in the value of TENSE. The model returns a "not defined" error. I've also tried to put TENSE into a module globals.py and import this into my models.py with no success. I might be missing something simple but fundamental about Django, so I appreciate any help. -
Get the total days from datepicker
I'm using Django to build an app simulating a car rental. I have been trying to get the starDate - endDate to get the totalDays and multiple by the car.price to get the car.total When I have the the total, then I can submit the form to book the rental Here's a little bit of what I have for now: <p id="price">${{ car.price }} per/day</p> <p id="total">>Total ${{ car.total=car.price*totaldays }}</p> //car.total=car.price*totaldays here is to visualize what I need <div> <form action="{% url 'add_booking' car.id %}" method="post"> {% csrf_token %} {{ booking_form.as_p }} <input type="submit" class="btn" value="Add booking"> <table class="striped"> </div> <script> var start_dateEl = document.getElementById('id_start_date'); var firstDate = M.Datepicker.init(start_dateEl, { format: 'yyyy-mm-dd', defaultDate: new Date(), minDate: new Date(), yearRange: 1, setDefaultDate: true, autoClose: true, onSelect: getStartDate => { startDate = firstDate.date console.log(startDate) return startDate }, }); var end_dateEl = document.getElementById('id_end_date'); var today = new Date(); var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000)); var topMaxDate = new Date().setDate(today.getDate() + 90); var lastDate = M.Datepicker.init(end_dateEl, { format: 'yyyy-mm-dd', defaultDate: tomorrow, minDate: new Date(), maxDate: new Date(topMaxDate), setDefaultDate: true, autoClose: true, onSelect: getEndDate => { endDate = lastDate.date console.log(endDate) }, }); const oneDay = 24 * 60 … -
Is this the correct gist of how to use Django Simple JWT?
The client will be Android Use username and password via POST to /thetokenurl to get access and refresh token, store access and refresh token in local storage Use token in auth header for any API call to protected endpoint Whenever frontend needs API call, you always have to do if/else work to check if the response say something about token being expired, and if its expired, then use the refresh token from local storage to get a new access token, and then store new access token in local storage and then make the API call to whatever you want. -
How to change the selectable options in ManyToMany field?
I'm developing an application where I have a User creating a Document with some general content. I set up the model so the user can share that document with other users through a ManyToMany field shown below. The problem I have is the ManyToMany field shows all the users on my site as possible collaborators - whereas I want to only show them their team members. How would I go about doing that? My Models: class Document(models.Model): ... collaborators = models.ManyToManyField(User, related_name="doc_collaborators") class User(models.Model): ... team = models.CharField('team', max_length=50) -
Field-level validation for DRF HiddenField in update
What is the correct way to do field-level validation on DRF serializers.HiddenField() ? What I tried (Assuming field name is x): Adding a validate_x() method to the serializer class. This method is not being called in partial update action (HTTP PATCH). Trying to validate it in validate(self, data) method. It does not exist in data dictionary. What is the correct way to add custom validation for this in partial update? I'm using DRF v3.12.4 Note: I want the field to be hidden from request body definition and still be able to validate and include the field in the serializer. -
why the chartjs file doesn't get the rendred list from views.py?
well i have been trying to render a list of number to my js file to use on a chart bar but i failed many time this is the chart js file: // comboBarLineChart var ctx_combo_bar = document.getElementById("comboBarLineChart").getContext('2d'); var comboBarLineChart = new Chart(ctx_combo_bar, { type: 'bar', data: { labels: ["a", "b", "c", "d", "e", "f", "j"], datasets: [{ type: 'bar', label: 'Followers', backgroundColor: '#FF6B8A', data: "{{ lf }}", borderColor: 'white', borderWidth: 0 }, { type: 'bar', label: 'Likes', backgroundColor: '#059BFF', data: "{{ lf }}", }], borderWidth: 1 }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); and whenever i remove the quotes from data: "{{ lf }}" data: "{{ ll }}" i get the following syntax error : and here is my views.py function: context={} file_directory = 'media/fl.csv' readfile(file_directory) dashboard = [] dashboard1 = [] for x in data['likes']: dashboard.append(x) my_dashboard = dict(Counter(dashboard)) print(my_dashboard) values = my_dashboard.keys() print(values) listlikes = [] for x in values: listlikes.append(x) print(listlikes) for x in data['followers']: dashboard1.append(x) my_dashboard1 = dict(Counter(dashboard1)) # {'A121': 282, 'A122': 232, 'A124': 154, 'A123': 332} values1 = my_dashboard1.keys() print(values1) listfollowers = [] for x in values1: listfollowers.append(x) print(listfollowers) context = { 'lf': listfollowers, 'll': listlikes, … -
Django Rest Framework Nested Different Serializer Saving Problem
I have Category and Product Models. I have created 2 serializers for each model. When i want to add a new product i send this json: {"name":"name","price":1,"category":{"id":1}} but django gives error and says that i need to specify category name too. I have already given id so why do i have to give category name too (category that has id 1 already exists. I am trying to add new product to this category )?. If i make name field of category not required django doesn't give error. But when i want to add new category it doesn't give error if i don't specify name field in json. I want django to give "name required" error when i try to add new category but i don't want it to give error when i try to add new product. If i make category read_only it doesn't update category_id of product when i want to update a product. class Product(models.Model): name=models.CharField(max_length=32) price=models.FloatField() category=models.ForeignKey("Category",on_delete=models.CASCADE) class Category(models.Model): name=models.CharField(max_length=32) class CategorySerializer(ModelSerializer): class Meta: model=Category fields="__all__" class ProductSerializer(ModelSerializer): class Meta: model=Product fields="__all__" category=CategorySerializer() -
django - how can I add more to my URL in my views.py?
I have a url, http://127.0.0.1:8000/lesson/riff-lab/1305/pentab-wow/ When a user navigates to the above url, I want to change it to http://127.0.0.1:8000/lesson/riff-lab/1305/pentab-wow/?d:a3ugm6eyko59qhr/pentab-Track_1.js The appended part is needed in order to load something that I want to load, but the specifics are not important for this question. Here's what I have tried. def my_view(request, pk): context = {} page = Page.objects.get(pk=pk) request.GET._mutable = True request.GET['?d:%s/%s' % (page.dropbox_key, page.dropbox_js_file_name)] = "" return render(request, template, context) Also def my_view(request, pk): context = {} page = Page.objects.get(pk=pk) request.GET = request.GET.copy() request.GET['?d:%s/%s' % (page.dropbox_key, page.dropbox_js_file_name)] = "" return render(request, template, context) These do not change the url. Can anyone help? Thanks in advance. -
Django on Docker is starting up but browser gives empty response
For a simple app with Django, Python3, Docker on mac Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN python3 -m pip install -r requirements.txt CMD python3 manage.py runserver COPY . /code/ docker-compose.yml version: "3.9" services: # DB db: image: mysql restart: always environment: MYSQL_ROOT_PASSWORD: '****' MYSQL_USER: '****' MYSQL_PASSWORD: '****' MYSQL_DATABASE: 'mydb' ports: - "3307:3306" expose: # Opens port 3306 on the container - '3307' volumes: - $HOME/proj/sql/mydbdata.sql:/mydbdata.sql # Web app web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Looks like the Docker is starting but from my browser, i get this response localhost didn’t send any data. ERR_EMPTY_RESPONSE what is that I am missing. Please help -
PrimeReact FileUpload with Django and axios with redux
I have my PrimeReact FileUpload component like this. FileUpload component is inside Formik <FileUpload mode="basic" name="baptism_certificate" accept="image/*" maxFileSize={1000000} customUpload uploadHandler={onBasicUploadAuto} chooseLabel="Browse" /> This is my onBasicUploadAuto method const onBasicUploadAuto = ({ files }) => { const [file] = files; console.log(file); const fileReader = new FileReader(); fileReader.onload = (e) => { dispatch(uploadParishionerBaptismCertificate(parishioner.id, e.target.result)); }; fileReader.readAsDataURL(file); }; This is my uploadParishionerBaptismCertificate method export const uploadParishionerBaptismCertificate = (id:string, baptism_certificate:any) => async (dispatch:(func:any)=>void) => { dispatch(uploadParishionerBaptismCertificateStart()); try { const formData = new FormData(); formData.append('baptism_certificate', baptism_certificate); const path = `parishioners/${id}/upload-baptism-certificate/`; const response = await axios.post(path, formData, { headers: { 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' } }); console.log(response.data); dispatch(uploadParishionerBaptismCertificateSuccess(response.data.baptism_certificate)); } catch (error) { let customError = ''; Object.keys(error).forEach((key) => { console.log(key, error[key]); customError += `${key.toString()}: ${error[key].join(',').toString()}\n`; }); dispatch(editParishionerFail(customError)); } }; When I upload image I'm getting below response from django baptism_certificate > ["The submitted data was not a file. Check the encoding type on the form."] What am I doing wrong ? How can I upload a file with PrimeReact FileUpload component ? -
Possibly to nullify if not in django choices
Let's say I have the following django field: class MyModel(models.Model): MONTH_CHOICES = [(str(i), calendar.month_name[i]) for i in range(1,13)] month = models.CharField(max_length=9, choices=MONTH_CHOICES, default='1') Let's say someone enters in 40, instead of it raising an error, I want it to just save it as None / NULL. Is there a way to do this, perhaps on the save method in a generic way? -
How to check the checkbox state then show/hide the next input field in Django template
Dears, My GOAL is to use the {{ form.is_scholorship }} this field ,which is type of models.BooleanField in the models.py, to determine whether next field {{ form.scholorship_amount }} shows. I am not sure how to take form.is_scholorship as tag and pass to javascript function to set next field show/hide or do more actions with this variable. Here is my code. In the template: <div class="form-group col-md-6"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.is_scholorship.errors }} <label class="form-label">獎學金</label> {{ form.is_scholorship }} <button type="button" onclick="test()"> 測試 </button> </div> </div> <div class="form-group col-md-6"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.scholorship_amount.errors }} <label class="form-label">獎學金金額</label> {{ form.scholorship_amount }} </div> </div> In the models.py: class Case(models.Model): . . . is_scholorship=models.BooleanField(verbose_name="獎學金",default=False) scholorship_amount=models.IntegerField(verbose_name="獎學金金額",blank=True,default=0,null=True) Also, I want to check whether onclick() works. I did the code <script> function test(){ console.log("test"); //var a= "{{ form.is_scholorship }}"; //alert("a:",a); } $('#id_is_scholorship').click(function(){ alert("test"); }); </script> <button type="button" onclick="test()"> 測試 </button> But it showed an error about Uncaught ReferenceError: test is not defined So does Django not to use javascript like this way? Hope someone can help me to figure out handling Django variable in javascript. Thank you for your time. -
How load foreingkey in admin site Django
I'm trying to change the way to load models on the admin page, especially foreign keys, because I have a delay to load them, the option for this was to exclude the field, but I want to have another option, thanks # model.service.py class Service(BaseModel): # Service data client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True) Any = models.CharField()... # service_form.py class ServiceForm(forms.ModelForm): class Meta: model = models.Service exclude = ["client"] # admin.py class serviceAdmin(admin.ModelAdmin): model = models.service admin.site.register(models.service, ServiceAdmin) this way I exclude the field for loading, but is there a way to do it that doesn't take so long to load?