Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Configure IFC.js with webpack
I am running a django application and I want to use frontend stack for which I need a bundler. I am new to bundlers, but I decided to go with webpack and I am trying to configure IFC.js (https://ifcjs.github.io/info/docs/Hello%20world), following the hello world tutorial but using webpack. Right now I am running into the error: Field 'browser' doesn't contain a valid alias configuration but I am also unsure about the general configuration of my webpack. My config-file: const path = require("path") module.exports = { mode: "development", entry: { app: "/src/index.ifc.js" }, watch: true, devtool: "source-map", output: { filename: "[name].bundle.js", path: path.resolve(__dirname, "dist") }, module: { rules: [ { test: /\.ifc.js$/, exclude: /node_modules/, } ] }, resolve: { extensions: [ ".ifc.js" ] } I think what this means is that all files with the suffix .ifc.js will be compiled when running webpack. I can get it to work using a simple alert statement in the index.ifc.js file. It compiles it to the dist-directory and the JS-code executes. But when I copy the code from the hello-world tutorial I get: Field 'browser' doesn't contain a valid alias configuration /Users/myuser/projectfolder/myproject/myapp/static/node_modules/web-ifc-three/IFCLoader doesn't exist The code I am using copied from the tutorial: import { … -
Django how to Post Form to an Api [closed]
I need the user to fill a form with their information so that I can make a call to an external Api for customer compliance verification. Below is the example request import requests url = "https://spxon.getid.dev//api/v1/application/:id" payload={} headers = {} response = requests.request("GET", url, headers=headers, data=payload) print(response.text) How can I get user input for the form and pass into payload {} ? Thanks in advance -
Data don't automatically updated that I uploaded from django admin
In development , I uploaded some data from django admin to a table. But when I refresh a page that uses that table then the new added data don't appears . It appears only when i rerun the manage.py runserver command. How can i fix this? I am expecting that the new data from the table should appear after added through django-admin. -
Get a value before submitting a form in Django
class StudentRegistrationForm(forms.Form): end_year = forms.IntegerField(widget = forms.TextInput( attrs={ 'id': 'end-year' } )) grade_letter = forms.ChoiceField( choices= get_grades(get_year()) ) To get the list of grade_letters for choice I need to know the end_year value. How can I get the value of end_year field before the submit (when the user wants to choose grade_letter)? -
I am getting error Expecting value: line 1 column 1 (char 0) when trying to DeSerialization and Insert Data Django REST Framework
I am getting error Expecting value: line 1 column 1 (char 0) when trying to DeSerialization and Insert Data Django REST Framework. Models.py from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models # Create your models here. class Products(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) rating = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(10.0)]) image = models.FileField(default="") total_participant = models.IntegerField() participant_price = models.DecimalField(max_digits=10, decimal_places=2) is_delete = models.BooleanField(default=False) I am getting error Expecting value: line 1 column 1 (char 0) when trying to DeSerialization and Insert Data Django REST Framework. Serializer file serializers.py from rest_framework import serializers from .models import * class ProductsSerializer(serializers.Serializer): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) rating = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(10.0)]) image = models.FileField(default="") total_participant = models.IntegerField() participant_price = models.DecimalField(max_digits=10, decimal_places=2) is_delete = models.BooleanField(default=False) def create(self, validate_data): return Products.objects.create(**validate_data) I am getting error Expecting value: line 1 column 1 (char 0) when trying to DeSerialization and Insert Data Django REST Framework. simple python app where i insert the data myapp.py import requests import json UrL= "http://127.0.0.1:8000/pcreate/" data = { 'name' : 'Umer', 'price': '3000', 'created_at' : 'True', 'updated_at' : 'True', 'rating' : '3.4', 'image' : '', 'total_participant' : '4', 'participant_price' … -
navbar dosenot come up and it under the content
i have a proplem with my navbar the content comes up on my navbar so can any one help me to fix it i useing django include to get the navbar so can any one help me plese the image some text pec there a err while post the q some text pec there a err while post the q some text pec there a err while post the q some text pec there a err while post the q ................................................. this is my code {% block content %} <!DOCTYPE html> <!-- Created By CodingNepal - www.codingnepalweb.com --> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <script src="https://kit.fontawesome.com/a076d05399.js"></script> </head> {% if user.is_authenticated %} <div class="wrapper"> <nav> <input type="checkbox" id="show-search"> <input type="checkbox" id="show-menu"> <label for="show-menu" class="menu-icon"><i class="fas fa-bars"></i></label> <div class="content"> <li class="logo"><a class="alog" href="#">Website</a></li> <ul class="links"> <li><a href="{% url 'frontpage' %}">Home</a></li> <li><a href="{% url 'lunchers' %}">lunchers</a></li> <li><a href="{% url 'resourepacks' %}">resourepacks</a></li> <li><a href="{% url 'aboutus' %}">aboutus</a></li> <li> <a href="#" class="desktop-link">More</a> <input type="checkbox" id="show-services"> <label for="show-services">More</label> <ul> <li><a href="{% url 'add_post' %}">Create Post</a></li> <li><a href="#">Drop Menu 2</a></li> <li><a href="#">Drop Menu 3</a></li> </li> </div> <a style="padding-top: -50px;" class="aimpro" href="{% url 'profile' user.profile.id %}"><img style="padding-top: -10px;" src="{{ user.profile.avatar.url }}" alt="Avatar" class="avatar"></a> <label … -
gdstorage config is throwing error; Django
MySettings from decouple import config GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE = config("GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE_CONTENTS") I'm trying to setup gdstorage for my django project but was not given a json file according to the instruction in the docs so i copied the keys and placed it in my environmental variable yet it's still throwing this error. MyErrorMessage gd_storage = GoogleDriveStorage() File "C:\Users\username\.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\gdstorage\storage.py", line 160, in __init__ credentials = Credentials.from_service_account_file( File "C:\Users\username.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\google\oauth2\service_account.py", line 238, in from_service_account_file info, signer = _service_account_info.from_filename( File "C:\Users\username.virtualenvs\vicsite-3EqYD9rF\lib\site-packages\google\auth\_service_account_info.py", line 72, in from_filename with io.open(filename, "r", encoding="utf-8") as json_file: FileNotFoundError: [Errno 2] No such file or directory: '78a23bb0124ac97ec7404104ae37dccffe33846a' -
how to add a map to admin page django
i want to get coordinates using map on admin page(latitude and longitude) i added in models field from django.contrib.gis.db import models as gis point = gis.PointField(null=True, blank=True, srid=4326, verbose_name='location') but i'm getting an error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. I realized that I need to add GDAL_LIBRARY_PATH to settings, but I don't know what to put there or if there is another way to add a map to the admin page? -
django https for another host except localhost
I'm trying to install SSL certificate for local server. I found this tutorial and try to do step by step. Everything is working fine for 127.0.0.1:8000, but not for my another host. settings.py ALLOWED_HOSTS = ['127.0.0.1', '192.168.4.241'] What I tried: mkcert -cert-file cert.pem -key-file key.pem localhost 127.0.0.1 192.168.4.241 python manage.py runserver_plus 192.168.4.241:8000 --cert-file cert.pem --key-file key.pem Error: OSError: [WinError 10049] The requested address is not valid in its context How can I fix this? -
Inherinting Django SetUpTestData method called for each child
Inheriting a mother class make its classmethod setUpTestData called for each child class. This is what I excepted but not what I want. Here is a minimalist example from django.test import TestCase class ParentClass(TestCase): @classmethod def setUpTestData(cls): cls.parent_attr = "parent value" print("ParentClass.setUpTestData called") # this is called twice class TestChild1(ParentClass): @classmethod def setUpTestData(cls): super(TestChild1, cls).setUpTestData() cls.child_attr = "child value 1" def test_child(self): self.assertEqual(self.parent_attr, "parent value") self.assertEqual(self.child_attr, "child value 1") class TestChild2(ParentClass): @classmethod def setUpTestData(cls): super(TestChild2, cls).setUpTestData() cls.child_attr = "child value 2" def test_child(self): self.assertEqual(self.parent_attr, "parent value") self.assertEqual(self.child_attr, "child value 2") $ python manage.py test accounts.tests.test_test Creating test database for alias 'default'... System check identified no issues (0 silenced). ParentClass.setUpTestData called .ParentClass.setUpTestData called . ---------------------------------------------------------------------- Ran 2 tests in 0.006s OK Destroying test database for alias 'default'... I want to be able to make many child class where each child class would apply tiny modification to the common 'inherited' database. However I do not want to run many time the parent classmethod as it is very slow. How can I ensure parent database is generated only once and that every child class works on a copy of parent database instead of regenerating the entire database. -
Django how to print datetimefield with timezone
I'm trying to print my datetime fields with the time zone i.e like this 2022-03-28T00:00:00+05:30 My serializer like this class ChallengeReadSerializer(serializers.ModelSerializer): start_date = serializers.DateTimeField(format='iso-8601') class Meta: model = models.Challenge fields = [ "start_date", ] Prints this 2022-03-23T03:16:00Z When I modify the serializer like this class ChallengeReadSerializer(serializers.ModelSerializer): start_date = serializers.SerializerMethodField() class Meta: model = models.Challenge fields = [ "start_date", ] def get_start_date(self, obj): return obj.start_date.isoformat() It prints 2022-03-28T00:00:00+05:30, which is what I want. I don't understand how this is happening, and couldn't find any information except it being two formats, how does the .isoformat() print timezone and (format='iso-8601') not print TZ -
django pwa not working for another hosts except localhost
I have install django-pwa and everything is working fine on localhost (127.0.0.1). But I can't see a install app button on the other host. How can I fix that? settings.py ALLOWED_HOSTS = ['127.0.0.1', '192.168.4.241'] PWA_APP_NAME = 'QLNB' PWA_APP_DESCRIPTION = 'QLNB' PWA_APP_THEME_COLOR = '#016e38' PWA_APP_BACKGROUND_COLOR = '#f0ece2' PWA_APP_START_URL = '/' PWA_APP_DEBUG_MODE = False PWA_APP_ICONS = [ { 'src': '/static/images/TDF.png', 'sizes': '160x160' } ] PWA_SERVICE_WORKER_PATH = BASE_DIR / 'static/scripts/serviceworker.js' base.html {% load static %} {% load pwa %} <!doctype html> <html lang="cs" class="w-100 h-100 m-0 p-0 overflow-auto"> <head> {% progressive_web_app_meta %} -
Django Templates check if string is "\t"
I am extending a selection form for csv delimiters and wanted to add the option for the tab character. <option value="&#9;" {% if settings.csvImportDelimiter == '&#9;' %} selected {% endif %}>Tab</option> The part that is not working is {% if settings.csvImportDelimiter == '&#9;' %}. I tried putting '\t' instead of ' ' without success. Is there a different syntax to this? I looked at the both Jinja and Django template docs but did not find anything on these control symbols. -
Django cache isolation when running tests in parallel
When I run tests in parallel, I get random failures because one test interferes with the cache of another test. I can work around the problem with @override_settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "[random_string]", } }, ) Actually to make that smaller I created a @isolate_cache decorator that is a wrapper around override_settings. But still I need to go and decorate a large number of test cases. This is error prone, because, as I said, the failures are random. I might run the test suite 100 times without error and think that everything is OK, but I still might have forgotten to decorate a test case, and at some point it will fail randomly. I've also thought about creating my own TestCase subclass and use only that for all my test cases. This presents a similar problem: at some point someone would inherit from django.test.TestCase out of habit, and it might not fail for a long time. Besides, some of my tests inherit from rest_framework.test.APITestCase (or other classes), so there isn't a single test case subclass. Is there any way to tell Django to run each test case in an isolated section of the cache once and for all? -
Django: How to create some variable in model based on the foreign key data?
I am new to Django and right now I am working on my first project: sits reservation system for some cinema. For this I have created 3 models: Movie, Hall and Event. Hall generates sits map as array. class Hall(models.Model): HALL_NAME = ( ('A', 'Hall A'), ('B', 'Hall B'), ('C', 'Hall C') ) hall_name = models.CharField(choices=HALL_NAME, max_length=30) hall_structure = models.CharField(max_length=10000, default=generate_sits(hall_name)) @property def get_sits(self): if self.hall_name == 'A': return generate_sits('A') if self.hall_name == 'Hall B': return generate_sits('B') if self.hall_name == 'Hall C': return generate_sits('C') else: return "lol" def __str__(self): return f'{self.hall_name}' After that i would like to create a variable for Event model, which takes the array structure of the sits, turns it into dictionary (Example ['A1': 'empty', 'A2': 'empty', ...] ). I want this variable to be overwritten in the future, when someone should book a sit on the vebsite (['A1': 'reserved']). Here is my Event model: class Event(models.Model): EVENT_DAYS = ( ('mon', 'Monday'), ('tu', 'Tuesday'), ('we', 'Wednesday'), ('th', 'Thursday'), ('fr', 'Friday'), ) EVENT_TIME_SLOT = ( ('10', '10:00'), ('13', '13:30'), ('17', '17:00'), ('20', '20:30'), ('00', '00:00'), ) EVENT_TYPE = ( ('2d', '2D'), ('3d', '3D'), ) end_default = "for this Event was assigned yet" days_default = "No day " time_default … -
What is the best way to send and fetch data periodically from Django backend to React frontend?
I'm making a web visualization app that needs to display data in real-time. I have a Python SDK that only requests data (using request library from python) directly from our database using the API provided and returns a response in JSON format. I'm using Django version 3.2 and have created a Django app and a React app version 17.0.2 in the same directory. What I did was get the data in my views.py using the Python SDK and then using the Django Rest Framework, created an API from it without using serialization. Then in the front-end (React), I fetched the data in the DRF API using Axios. So far, it's working just fine. However, I noticed that I need to restart my local Django server and refresh the page first before the latest/updated data gets reflected in my visualization. What I need is for the back-end to send the latest data to the front-end in real-time or for the front-end to request/fetch the latest data periodically from the back-end - whichever is better in terms of performance. I'm new to using DRF in the backend and Django+React as the front-end. Someone suggested looking into promises in Python but I'm not … -
How to give access to different object of a model to different users in django
I am doing an online classroom project in Django where I created a model named course which is accessible by teachers. Now I am trying to add students in a particular class by inviting students or students can enroll using "clasroom_id"(a unique field I used in the model). I added the models and views of the course object below. models.py class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.course_name def is_valid(self): pass views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) def view_courses(request, *args, **kwargs): students = course.objects.filter(created_by=request.user) dict = {'course':students} return render(request, 'teacherhome.html',dict) -
How to prevent django migrations from running?
My team frequently uses the production DB for testing new changes and on more than one occasion migrations have been created and applied before being code reviewed, creating issues in production. There are so many things wrong with this situation, but I'm hoping to at least protect our prod DB by blocking migrations based on the state of an environment variable. Is this possible? -
How to know which django middlewares are asynchronous enabled and which are not?
To see what middleware Django has to adapt, you can turn on debug logging for the django. request logger and look for log messages about “Synchronous middleware … adapted” . I have been trying to do just the same but without any luck. This is my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG', }, 'loggers': { 'django.request': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, } Even though I have set up the LOGGING variable, I am not getting the output like mentioned in the documentation. Starting server at tcp:port=8000:interface=127.0.0.1 HTTP/2 support not enabled (install the http2 and tls Twisted extras) Configuring endpoint tcp:port=8000:interface=127.0.0.1 Listening on TCP address 127.0.0.1:8000 HTTP b'GET' request for ['127.0.0.1', 42684] HTTP 200 response started for ['127.0.0.1', 42684] HTTP close for ['127.0.0.1', 42684] HTTP response complete for ['127.0.0.1', 42684] 127.0.0.1:42684 - - [22/Mar/2022:12:11:47] "GET /admin/" 200 3550 HTTP b'GET' request for ['127.0.0.1', 42684] HTTP 200 response started for ['127.0.0.1', 42684] HTTP close for ['127.0.0.1', 42684] HTTP response complete for ['127.0.0.1', 42684] 127.0.0.1:42684 - - [22/Mar/2022:12:11:48] "GET /admin/core/user/" 200 9028 HTTP b'GET' request for ['127.0.0.1', 42684] HTTP 200 response started … -
Django error no such table: auth_group when running makemigrations
When i run python manage.py makemigrations it throws an error: File "/home/smoke/miniconda3/envs/testing/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/smoke/Documents/wsl_dev/testing/genelookup/apps/authentication/urls.py", line 7, in <module> from .views import login_view, register_user File "/home/smoke/Documents/wsl_dev/testing/genelookup/apps/authentication/views.py", line 14, in <module> compute, created = Group.objects.get_or_create(name='compute') File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 588, in get_or_create return self.get(**kwargs), False File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get num = len(clone) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/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 "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1202, in execute_sql cursor.execute(sql, params) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in … -
how to create a Dropdown in Django
how to create two Dropdown fields in Django. first is state, & second is city View.py file: def dropdown(request,state_slug): context={} stateO=State.objects.order_by('name') context['state']=stateO sO=State.objects.get(state_slug=state_slug) cityO=City.objects.filter(State=sO).order_by('name') context['city']=cityO context['my_state']=sO return render(request,'drop.html',context) Url.py: class State(models.Model): name = models.CharField(max_length=96) state_slug = models.SlugField(max_length=96, blank=True) def save(self, *args, **kwargs): # Saving The Modefied Changes if not self.state_slug: self.state_slug = slugify(self.name) super(State, self).save(*args, **kwargs) def __str__(self): # Dundar Method return self.name class City(models.Model): State = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return self.name html file: <body> <select> {% for i in state %} <option value="{% url 'dropdown' i.state_slug %}}">{{i}}</option> {% endfor %} </select> <select> {% for j in city %} <option value="{{ j }}">{{ j }}</option> {% endfor %} </select> </body> filter the citys name on the base of state name. without using Ajex. -
Creating Oauth callback function in python. I there is a webserver should sends me Token and I want to react to the token if it's correct by call back
I want to make the same function but in Python Django how can I do that because I want to make authentication for login using Oauth 2.0 public function callback(Request $request){ $response = Http::post('https://oauth.zid.sa' . '/oauth/token', [ 'grant_type' =>'authorization_code', 'client_id' => 48, 'client_secret' => 'LsswUNyWTjyKT9AsXnpsv3FnG4glSNZQ5SM3YRnD', 'redirect_uri' => 'http://client.test/oauth/callback', 'code' => $request->code // grant code]);} -
upload image in forms Django
I am trying to upload image from form but whenever I submit everything got saved in database other than image field.But when I try to do samething from admin panel it works. models.py class Post(models.Model): title = models.CharField(("Title"), max_length=100) title_image = models.ImageField( ("Title Image"), upload_to='static/Images/TitleImages/', max_length=None, blank = True,null = True) Forms.py class AddPostForm(ModelForm): class Meta: model = Post fields = ['title','title_image'] Views.py class AddPostView(LoginRequiredMixin,CreateView): model = Post template_name = 'MainSite/add_post.html' fields = '__all__' def dispatch(self, request, *args, **kwargs): if request.user.is_anonymous: messages.error(request,"You need to login to access this page") return redirect('/') elif request.user.is_superuser: if request.method == "POST": form = AddPostForm(request.POST) if form.is_valid(): form.save() messages.success(request,"POST added successfully") return redirect('/') else: print("error") else: print("method is not post") form = AddPostForm() return render(request,'MainSite/add_post.html',{'form':form}) else : messages.error(request,"You need to have superuser permission to access this page") return redirect('/') addpost.html <form action= "" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form|crispy}} <button class="btn btn-primary profile-button" style = "width:150px;"type="submit" >Add Post</button></div> </form> my model have 2 things title and title_image but whenever I submit only title is saved and when I do through admin panel it works. I dont know what I am doing wrong here any advice will be helpful. Thanks in advance -
DJango unable to upload image on update
So basically django is unable to upload file after calling update function. It does work with create function. The path is getting updated in the database but the file isn't copying in the /media/ I'm not using the form for image (only for blog content), rather using froala editor. views.py def blog_update(request, pk): context = {} if not (request.user.is_authenticated): return redirect('/') else: try: blog_obj = Blog.objects.get(id = pk) if blog_obj.user != request.user: return redirect('/') initial_dict = {'content': blog_obj.content} form = BlogForms(initial = initial_dict) if request.method == 'POST': form = BlogForms(request.POST) image = request.FILES['image'] title = request.POST.get('title') gist = request.POST.get('gist') user = request.user if form.is_valid(): content = form.cleaned_data['content'] blog_obj = Blog.objects.filter(id = pk).update( user = user , title = title, gist = gist, content = content, image = image ) messages.success(request, f"Blog updated successfully!") return redirect('/my-blogs/') context['blog_obj'] = blog_obj context['form'] = form except Exception as e: print(e) return render(request, 'update-blog.html', context) forms.py class BlogForms(forms.ModelForm): class Meta: model = Blog fields = ['content'] I tried to print the path for existing file as well as the new selected file and it shows correct. Somehow the update function isn't copying the file to the media dir. I'm new to this, any help is … -
Django ChoiceField with custom forms
I am relatively new to Django and have been following up some tutorials on how to create registration forms with Django. **This is the html form code** <form action="{% url 'register' %}" method="post"> {% csrf_token %} <div class="form-row"> <div class="col form-group"> <label>First name</label> {{ form.first_name }} </div> <!-- form-group end.// --> <div class="col form-group"> <label>Last name</label> {{ form.last_name }} </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="col form-group"> <label>Email</label> {{ form.email }} </div> <!-- form-group end.// --> <div class="form-group col-md-6"> <label>Directorate</label> <select name="directorate" class="form-control" required> <option value="" disabled selected>Select</option> {% for i in form.directorate %} <option value=""></option> {% endfor %} </select> </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="form-group col-md-6"> <label>Create password</label> {{ form.password }} </div> <!-- form-group end.// --> <div class="form-group col-md-6"> <label>Repeat password</label> {{ form.confirm_password }} </div> <!-- form-group end.// --> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block"> Register </button> </div> <!-- form-group// --> </form> **This is models.py code** class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) directorate = models.CharField(max_length=100) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) …