Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django upload multiple images use form
I'm making a bulletin board. I want to post several images in one post However, no matter how hard I try to find a way to create multiple using the form.I want to upload several files at once. I created an image upload function, but it doesn't show on the web I don't know where it went wrong models.py class Writing(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=200) content = models.TextField() create_date = models.DateTimeField() modify_date = models.DateTimeField(null=True, blank=True) view_count = models.IntegerField(default=0) def __str__(self): return self.subject class WritingImage(models.Model): writing = models.ForeignKey(Writing, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/%Y/%m', blank=True, null=True) forms.py class WritingForm(forms.ModelForm): captcha = ReCaptchaField(label=('로봇확인')) class Meta: model = Writing fields = ['subject', 'content'] labels = { 'subject': '제목', 'content': '내용', } class WritingFullForm(WritingForm): images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta(WritingForm.Meta): fields = WritingForm.Meta.fields + ['images', ] views.py @login_required(login_url='account_login') def writing_create(request): """ 글작성 """ if request.method == 'POST': form = WritingFullForm(request.POST, request.FILES) files = request.FILES.getlist('images') if form.is_valid(): writing = form.save(commit=False) writing.author = request.user writing.create_date = timezone.now() writing.save() if files: for f in files: WritingImage.objects.create(writing=writing, image=f) return redirect('ourtube:index') else: form = WritingFullForm() context = {'form': form} return render(request, 'ourtube/writing_form.html', context) form.html <div class="form-group"> <label for="note-image">Images</label> <input type="file" name="images" class="form-control-file" id="note-image" multiple> </div> detail.html <h1>{{ writing.view_count … -
why i can't imprt django.db?
enter image description here I installed django on my virtualenv but still I can't import IT. -
ModuleNotFoundError: No module named 'CompanyWebsite' aws hosting
I am trying to use gunicorn during website hosting but keep getting this error. Everything seems fine according to me .Read many solutions but couldnot find the issue (venv) ubuntu@ip-172-31-45-195:~$ cd project (venv) ubuntu@ip-172-31-45-195:~/project$ cd Company-Website (venv) ubuntu@ip-172-31-45-195:~/project/Company-Website$ cd CompanyWebsite (venv) ubuntu@ip-172-31-45-195:~/project/Company-Website/CompanyWebsite$ ls __init__.py __pycache__ asgi.py settings.py urls.py wsgi.py (venv) ubuntu@ip-172-31-45-195:~/project/Company-Website/CompanyWebsite$ gunicorn wsgi When i run wsgi file i get this error [2022-07-19 13:57:40 +0000] [8638] [INFO] Starting gunicorn 20.1.0 [2022-07-19 13:57:40 +0000] [8638] [INFO] Listening at: http://127.0.0.1:8000 (8638) [2022-07-19 13:57:40 +0000] [8638] [INFO] Using worker: sync [2022-07-19 13:57:40 +0000] [8639] [INFO] Booting worker with pid: 8639 [2022-07-19 13:57:40 +0000] [8639] [ERROR] Exception in worker process . . . ModuleNotFoundError: No module named 'CompanyWebsite' My wsgi file is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CompanyWebsite.settings') application = get_wsgi_application() Please help me to solve this issue -
How to do a DELETE/UPDATE at the same time? Django rest ramework
I'm new with django rest framework and I have 4 fields in my database table (id, chip, creation date, deletion date), on the front-end there is a button to delete the chip, so far so good, but on the page I have, in addition to the abject (chip) to be deleted, it has 2 more fields (creation date and deletion date) when deleting the object, the deletion date field must have the time of deletion and not simply be empty. How to make this change when doing the deletion?` at the moment I just created the model and migrated it to the database. I haven't started yet, I just created a route to list (GET) all the data in the table. I ask for help to do the Delete/Update or whatever it may be. my model class Gateway(models.Model): id = models.AutoField( primary_key=True) gateway_chip = models.CharField(max_length=20, unique=True) creation_date = models.DateTimeField() deletion_date = models.DateTimeField() class Meta: db_table = 'GATEWAY' -
How to test a custom middleware in django?
class VersionCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): meta = request.META client_data = VersionChecks.get_meta_info(meta) client = client_data.get('client') backward_compatibility = {} last_compatible_pwa_version = backward_compatibility.get('last_supported_pwa_version', 823) if client == APP_TYPES.consumer_web: pwa_version = int(client_data.get('client_version', 0)) native_version = int(client_data.get('platform_version', 0)) if pwa_version < last_compatible_pwa_version: return JsonResponse(UNSUPPORTED_APP_VERSION, status=400) response = self.get_response(request) return response I have written this custom middleware, how can i unit test this? This is my test code class TestVersionCheckMiddleware(unittest.TestCase): @patch('misc.middlewares.version_check_middleware.VersionCheckMiddleware') def test_init(self, version_check_middleware_mock): vcm = VersionCheckMiddleware('response') assert vcm.get_response == 'response' def test_version_check_middleware(self): mock_request = Mock() mock_request.META = { "HTTP_X_APP_CLIENT": 21, "HTTP_X_APP_PLATFORM": 21, "HTTP_X_APP_PLATFORM_VERSION": 23, "HTTP_X_APP_VERSION": 32, "app_version": 323, } vcm_middleware_response = VersionCheckMiddleware() assert vcm_middleware_response.get_response == (UNSUPPORTED_APP_VERSION, 400) This test case does not actually calls the middleware, how can i properly test this middleware? Any resources about how can i solve this, please do share that as well -
How do I authorize a specific url to load the content of my site deployed on heroku from an iframe?
I deployed my site designed in Python Django on heroku. When I try to access this site through an iframe from an html file of my own design, I get the error: https://gkwhelps.herokuapp.com refused connection. This site contains the default header: X-Frame-Options: DENY , After looking on the Django documentation, I saw that this property only accepts two options DENY or SAMEORIGIN. I wonder if there is not a way to allow access to this site via an iframe from a domain name or the localhost. -
when building python Django project it exiting with an error
i am getting below error when building the project. I have installed pymssql using pip -m install pymssql and visual studio installer as well. tree = Parsing.p_module(s, pxd, full_module_name) building '_mssql' extension creating build creating build\temp.win-amd64-cpython-39 creating build\temp.win-amd64-cpython-39\Release creating build\temp.win-amd64-cpython-39\Release\src "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.32.31326\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IC:\Users\anallamilli\AppData\Local\Temp\pip-install-_ebszunz\pymssql_8c3eaa8f4e074feda79e1cd9e7617f9e\freetds\vs2015_64\include -IC:\Users\anallamilli\AppData\Local\Temp\pip-install-_ebszunz\pymssql_8c3eaa8f4e074feda79e1cd9e7617f9e\build\include "-Ic:\users\anallamilli\onedrive - fireangel\desktop\local build\admin_v2_pipeline\comp_admin_system\env1\include" -IC:\Users\anallamilli\AppData\Local\Programs\Python\Python39\include -IC:\Users\anallamilli\AppData\Local\Programs\Python\Python39\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.32.31326\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\cppwinrt" /Tcsrc\_mssql.c /Fobuild\temp.win-amd64-cpython-39\Release\src\_mssql.obj -DMSDBLIB _mssql.c src\_mssql.c(699): fatal error C1083: Cannot open include file: 'sqlfront.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.32.31326\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. WARNING: No metadata found in c:\users\anallamilli\onedrive - fireangel\desktop\local build\admin_v2_pipeline\comp_admin_system\env1\lib\site-packages Rolling back uninstall of pymssql Moving to c:\users\anallamilli\onedrive - fireangel\desktop\local build\admin_v2_pipeline\comp_admin_system\env1\lib\site-packages\pymssql-2.2.5.dist-info from C:\Users\anallamilli\OneDrive - FireAngel\Desktop\Local build\Admin_V2_Pipeline\COMP_Admin_System\env1\Lib\site-packages~ymssql-2.2.5.dist-info Moving to c:\users\anallamilli\onedrive - fireangel\desktop\local build\admin_v2_pipeline\comp_admin_system\env1\lib\site-packages\pymssql from C:\Users\anallamilli\OneDrive - FireAngel\Desktop\Local build\Admin_V2_Pipeline\COMP_Admin_System\env1\Lib\site-packages~ymssql error: legacy-install-failure Encountered error while trying to install package. pymssql note: This is an issue with the package mentioned above, not pip. hint: See above for output … -
What do I set the default value as when adding a field to a model?
I added the field user which is a foreign key to another model called User. This field was added to the model called Bid. However, when I tried to migrate the changes, I got the message: It is impossible to add a non-nullable field 'user' to bid without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. Last time, I set it to 'user' and got an error that stated: ValueError: invalid literal for int() with base 10: 'user'. What should I set the default value as? models.py: class Bid(models.Model): item = models.ForeignKey(Listing, on_delete=models.CASCADE) price = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE) -
Podcasting with Django
I am building a website with the Django framework; I want this website to load podcasts from Anchor.FM. I am looking for a way to load all my podcast series automatically but I don't know how to go about this using Django? -
Finding the highest amount of an instance in django models
I have two models that have a foreign key relationship to each other. One of the models is a Student and the other is Grade. The issue I'm having it I'm getting the values I want with model methods in the template. so what I'm trying to do is I want the Student with the highest grade score all the way to the lowest. How actually can I achieve this? -
QueryDict has list, but actualy show string
today I have encountered thing I do not really know why it happened. I POSTed request with form that had MultipleModelChoiceField, in frontend I selected multiple of them (id 2 and 3), then in debug in PyCharm I wanted to see my POST request and saw this [see image]. With form.POST.get("people") I got >>> "3" as a result. After sanitizing data with After I accessed form.cleaned_data, the result was good, but I don't quite understand why did it happen, can someone please, try to explain what happened and why? Thanks all! -
What path should I take erlang(elixir), node.js or django(python)
Please I am asking for and advice so that I can know what path to take because I am currently very confused as to which path to take. I want to build a project with very strong fault tolerance but must be very fast and offering real time result. I have been confused as to which path I should take amidst the 3 server side languages i.e. erlang, node.js or django. I have done some work in node.js and my hat off for it but the problem I have with node.js is when I make modification to the code, I have to restart the server thereby lossing session. That has made me sceptical of using nnode.js. I can't imagine all my users being logged out from the server when I make changes to my code. SO that makes me not use node.js Django on the other hand saves session that is running when I updates my code base, no session loss unlike node.js the only matter is when I restart the server any one logging into the server while it is restarting would not be able to enter but the session is still there. Also django's is learning curve was … -
How can i display svg (like an image) from a string in django template?
I want to display in a django template the content of a svg file retrieved from a database as a string. when I call the field of my model, django displays the content as a string, the svg is not interpreted as a schema. For example, my template displays <Element {http://www.w3.org/2000/svg}svg at 0x178ebe2dc80> or bla bla bla instead of a schema. I want to display a schema, not a string. How can I do that please? Thank you -
How to add token in response after registering user DRF Social OAuth2
I am using DRF Social OAuth2 for social authentication, it's giving me the token when I log in, but I want to return the token in response when I register a user with an email and password. How can I do that -
Django Websocket Send Text and bytes at sametime
I have client and server in my project. In the client part, the user will upload his own excel file and this file will come to my server for processing. My artificial intelligence python code will run on my server and it will make changes to excel. When every time it changes, I want to send the updated version to the client so that the client can see the change live. Example Let's say I have 10 functions on server side, each function changes some cells in excel(I can get the index of the changed cells). When each function is finished, I will send the changing indexes to the client and these changed places will be updated in the table in the client (C++, Qt). At first, I made the server with PHP, but calling my artificial intelligence python codes externally(shell_exec) was not a good method. That's why I want to do the server part with python. Is django the best way for me? What I've tried with Django: I wanted to send data continuously from server to client with StreamingHttpResponse object, but even though I used iter_content to recv the incoming data on the client, when all the code … -
How do I prevent my Django Database from being overwritten
Currently I have a Django application running on my personal website from PythonAnywhere.com. When I make updates to the site I login to PythonAnywhere and git pull to update my application. When I do this the data that was entered through the website since the last update gets lost from the database when I update. What can I do to overcome this? I am currently using the SqlLite version that comes preinstalled with the Django App. This likely could be part of the issue but need some help understanding how to overcome it. -
AUTH_USER_MODEL reference in settings.py Django
I have a installed an app called 'Login', who have a folder 'models' inside, with a custom_user model. The problem occurs when I tried to configure settings.py, specially auth_user_model. in installed apps I have the following: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'project_app.login' ] and below AUTH_USER_MODEL = 'login.models.CustomUser' But I have the following error: "Invalid model reference. String model references must be of the form 'app_label.ModelName'." I put the .models in AUTH_USER_MODEL, because I want to reference the app that the CustomUser is inside the folder "models" in Login. Also, I tried with declare like this: AUTH_USER_MODEL = 'login.CustomUser' but the error is this: 'AUTH_USER_MODEL refers to model 'login.CustomUser' that has not been installed' -
how install reportlab for django on dockerfile?
hi when i want install reportlab with pip on docker for django project, i have this error : Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. image of error description -
How can I use `phone number` and `otp` in "django-rest-framework-simplejwt" instead of `username` and `password` to generate token?
#urls.py I just want to know how to set custom fields, for e.g instead of 'username' and 'password' can i get 'phone_number' and otp from django.urls import path from . import views from . import api_views from django.conf.urls.static import static from django.conf import settings from rest_framework_simplejwt.views import (TokenObtainPairView,TokenRefreshView,) urlpatterns = [ # Api Urls path('api/',api_views.getRoutes,name="api"), path('api/register',api_views.registerPatient,name="signup"), path('api/patient/',api_views.getPatients,name="patients"), path('api/create/',api_views.CreatePatient,name="create"), path('api/patient/<str:pk>/',api_views.getPatient,name="patient"), path('api/update/<str:pk>/',api_views.updatePatient,name="update"), path('api/delete/<str:pk>/',api_views.deletePatient,name="delete"), path('api/login/',TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/doctor/',api_views.doctorRegister,name="doctorreg"), path('api/getroutes/', api_views.getRoutes, name='getroutes'), path('api/sotp/',api_views.send_otp,name="sotp"), path('api/votp/',api_views.verify_otp,name="votp"), path('api/signup/',api_views.registerPatient,name="signup"), ]``` -
Specify a .env file in Django in command line or vscode launch.json
At the moment I have a Django project running in VS Code. This currently uses a single .env file to connect to a SQL Server database. environments/.env DATABASE_URL=mssql://USER_NAME:PASSWORD@SERVER_NAME/DATABASE_NAME settings.py import environ env = environ.Env( # set casting, default value DEBUG=(bool, False) ) BASE_DIR = Path(__file__).resolve().parent.parent ENVIRONMENT_DIR = os.path.join(BASE_DIR, "environments") environ.Env.read_env(os.path.join(ENVIRONMENT_DIR, '.env')) env = environ.Env() ... DATABASES = { "default": env.db_url(), } } __.vscode/launch.json This is ran in VS Code with the following launch configuration: { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", ], "django": true }, ] } Question The question is, is it possible to have a multitude of different environments to connect to using different multiple environment files? Something like: dev.env test.env prod.env Then get VS Code to run a specific .env from the launch.json. Sources: https://django-environ.readthedocs.io/ https://django-environ.readthedocs.io/en/latest/tips.html#multiple-env-files https://djangostars.com/blog/configuring-django-settings-best-practices/ -
General questions about Django and DRF
I've made a project using Django and Bootstrap (I plan to use React for the frontend). Then I started building REST API with DRF and it seems that my DRF views are pretty similar (if not duplicative) to my original Django views such as DetailView, UpdateView and etc.Now I wonder if I can keep my old views or should I completely replace them with DRF ones? Or should I use DRF views for CRUD and keep particular Django views? And another qusetion: am I right that when working with Django and DRF Django becomes just an ORM provider also responsible for business logic, authentication and some other features? Thanks. -
How do I display all commented TV and MOVIE SCORES in descending order?
What we want to achieve. I want to display the score (stars) of a movie in descending order. Present condition The tmdb API is used to retrieve movie information. And the model movie and TV have only ID and stars(score). From here, only those with stars are returned to html. I want to ask a question. And if score is selected, how can I make it appear in descending score order? data = requests.get (f "https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US"). Now you can get the information of tv. def index(request): sort_by = request.POST.get('sort_by','') tv = TV.objects.order_by(sort_by) movie = Movie.objects.order_by(sort_by) # Get the results from the API if tv: data_tv = requests.get(f"https://api.themoviedb.org/3/tv/{re.GET.get('id')}?api_key={TMDB_API_KEY}&language=en-US") if movie: data_movie = requests.get(f"https://api.themoviedb.org/3/movie/{movie.GET.get('id')}?api_key={TMDB_API_KEY}&language=en-US") # Render the template return render(request, 'Movie/index.html', { "data_tv": data_tv.json(), "data_movie": data_movie.json(), }) class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_tv.objects.filter(tv_id=self.id) def average_stars(self): comments = self.get_comments() n_comments … -
How to receive/subscribe to mqtt request via django without external broker
I have owned a server based on djnago and i need to get mqtt messages from a device directly to my server without any external brokers. How to do this? I need only request response and there is no need of broadcasting. Since it is an iot application. What iam asking is is there any way to just collect a message and send back response using mqtt protocol ,or any method to create our own djnago based broker -
How to filter the django queryset based on the hours?
Serializer class MyModelSerializer(serailizers.ModelSerializer): hour = serializers.SerializerMethodField() def get_hour(self, obj): created_at = obj.created_at # datetime now = datetime.now() return (now - datetime).total_seconds() // 3600 class Meta: model = MyModel fields = "__all__" API In the api there will be a filter parameter hr. If it provided for e.g 4 then I should return only the matching entries which has hour 4(calculated in the above serializer). How can I do this ? @api_view(["GET"]) def get_list(request): qs = MyModel.objects.all() hr = request.GET.get("hr") if hr: qs = qs.filter(created_at__hour=hr) # get_hour value = hr this should be the comparison return MyModelSerializer(qs, many=True).data -
Why do I get an error when I try to add a new object?
I added a field that is a foreign key called user in a model but I initially received an error that said: It is impossible to add a non-nullable field 'user' to bid without specifying a default. So I made the default the string 'user'. However, instead I have been receiving the error: ValueError: invalid literal for int() with base 10: 'user' when I try to migrate the changes I have made (python3 manage.py migrate). And when I try to add a new bid, I get an error in the web page: OperationalError: no such column: auctions_listing.user_id How do I fix this? models.py: class Bid(models.Model): item = models.ForeignKey(Listing, on_delete=models.CASCADE) price = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE)