Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to install channels redis in django using pip without errors
I am trying to install channels redis module using pip but so far am still getting errors. I installed Microsoft c++ build tools as the error suggested but so far the error still persists when it comes to building wheel for hiredis. Here is the output error. error: subprocess-exited-with-error × Running setup.py install for hiredis did not run successfully. │ exit code: 1 ╰─> [25 lines of output] C:\Users\Teacher-5F84DF\AppData\Local\Temp\pip-install-cs726k2z\hiredis_fa16ee7f0b4e4df28a1a34d9640a827d\setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import sys, imp, os, glob, io c:\users\teacher-5f84df\appdata\local\programs\python\python310\lib\site-packages\setuptools\dist.py:697: UserWarning: Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead warnings.warn( running install running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\hiredis copying hiredis\version.py -> build\lib.win-amd64-3.10\hiredis copying hiredis\__init__.py -> build\lib.win-amd64-3.10\hiredis copying hiredis\hiredis.pyi -> build\lib.win-amd64-3.10\hiredis copying hiredis\py.typed -> build\lib.win-amd64-3.10\hiredis running build_ext building 'hiredis.hiredis' extension creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\src creating build\temp.win-amd64-3.10\Release\vendor creating build\temp.win-amd64-3.10\Release\vendor\hiredis C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ivendor -Ic:\users\teacher-5f84df\appdata\local\programs\python\python310\include -Ic:\users\teacher-5f84df\appdata\local\programs\python\python310\Include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\ATLMFC\include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include /Tcsrc\hiredis.c /Fobuild\temp.win-amd64-3.10\Release\src\hiredis.obj hiredis.c c:\users\teacher-5f84df\appdata\local\programs\python\python310\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': … -
How do I use Django/Python to create rows in a table?
I want to create a html table that has the number of rows and content set, according to what is in Django. I have written the following code: <h5>Model</h5> <a class="btn btn-sm btn-secondary" href="{% url 'create_model' %}?project={{ project.id }}" role="button">Add Model</a> <table class="table"> <thead> <tr> <th scope="col">Entry name</th> <th scope="col">Model</th> <th scope="col">Outcome</th> </tr> </thead> <tbody> <tr> <th scope="row">Entry Name</th> <td>2</td> <td>NaN</td> </tr> <tr> <th scope="row">Entry Name</th> <td>2</td> <td>NaN</td> </tr> <tr> <th scope="row">Entry Name</th> <td>3</td> <td>NaN</td> </tr> </tbody> </table> {% endblock content %} I can access 'Entry name;' through something like this: {% for entry in entries %} <tr> <td>{{entry.name}}</td> How do I set the number of rows I need according to what the database has stored for entry names? For example, if there are two entry names. I want to have double the number of rows, so that the table has the following form: -
Django data migration with contenttype keys
I need to make a Django data migration that creates some predefined initial values in tables. To create the predefined values I am using a fixture file that is called within the migration like so: def run_data_populating_fixtures(apps, schema_editor): call_command('loaddata', 'apps/app/fixtures/test.json') class Migration(migrations.Migration): dependencies = [ ('app', '0012'), ('contenttypes', '0001_initial'), ('core', '0001_initial') ] operations = [ migrations.RunPython(run_data_populating_fixtures, elidable=False) ] The table I am populating has a column content_type_id which is a foreign key to the django_content_type table. This becomes a problem because at the point when the data migration executes, the table doesn't have any of my apps' models registered. Basically in the fixture there is an explicit key specified as "content_type": 11, and it causes a FK violation. How can I run my data migration after django_content_type table has my models registered? I tried using natural keys instead of explicit ones as per migration article, like so "content_type": ["core", "mymodel"] but it doesn't seem to help, as it just produces an error that it couldn't find such content type. -
what is meaning of Django signed cookie?
Is value of signed cookie secure? I supposed that value of signed cookie is encrypting at response and decrypting at request. Here is no detail information about it But when I tried to get value of signed cookie it was visible: from django.http.response import JsonResponse as J j = J({}) j.set_signed_cookie("the_key", "the_value") j.cookies["the_key"].value > 'the_value:1newi4:nTgUngl_0y6YkqJd711GqMkAQFwXORbug6CdcL_Jo2Q' j.cookies["the_key"].coded_value >'the_value:1newi4:nTgUngl_0y6YkqJd711GqMkAQFwXORbug6CdcL_Jo2Q' What is the meaning of coded_value? the_value is clearly visible in both ways. Is it possible to encrypt cookie value? -
using Django template tags in response to ajax
I use Ajax to update a list of objects, let's say each time a button is clicked. But I want to use Django template tags to generate each item of the list. The problem is that I have to send a JsonResponse back to JavaScript, but there, I can't use these tags. I have to send object attributes as json. and I'm stuck with plain html in Ajax: ... success: function (json) { if (json.new_messages.length) { for (let m of json.new_messages) { $('#messages-list').append("<li>"+m.sender_name+" "+m.content+"</li>"); } } }, -
How to Rename your model to another model name in django
I have a model named Customer which is a 3rd table for user. It is related to many other models . Now due to my need I want to create a new model with the name Customer and delete the previous model . How can I do this, without ruining my migratinon . My current Customer model class Customer(models.Model):`enter code here` user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name="user_customer") customer_key = models.CharField( max_length=5, null=True, blank=True, unique=True, editable=False, ) -
Error! Unable to find binary python3.8 for runtime python3.8 on Vercel
When i was deploying django app on vercel i got this error Error! Unable to find binary python3.8 for runtime python3.8 Error! Check your logs at https://komputama-qj1unu7v1-ngapa.vercel.app/_logs or run vercel logs komputama-qj1unu7v1-ngapa.vercel.app And the log in the deployment status is [16:26:29.158] Retrieving list of deployment files... [16:26:31.764] Downloading 1726 deployment files... [16:26:38.432] Warning: Due to `builds` existing in your configuration file, the Build and Development Settings defined in your Project Settings will not apply. Learn More: https://vercel.link/unused-build-settings [16:26:38.619] Installing build runtime... [16:26:42.087] Build runtime installed: 3.467s [16:26:42.423] Looking up build cache... [16:26:42.665] Build Cache not found [16:26:42.856] Starting build [16:26:42.861] Build AMI version: Amazon Linux release 2 (Karoo) [16:26:42.862] Lambda runtime: python3.8 [16:26:42.862] WSGI application: cores.wsgi.application [16:26:42.862] ====> Selecting python version [16:26:42.874] Error: Unable to find binary python3.8 for runtime python3.8 [16:26:42.874] at Object.findPythonBinary (/vercel/7c1ee15da2687191/.build-utils/.builder/node_modules/@ardnt/vercel-python-wsgi/build-utils/python.js:23:9) [16:26:42.874] at Object.exports.build (/vercel/7c1ee15da2687191/.build-utils/.builder/node_modules/@ardnt/vercel-python-wsgi/index.js:34:34) [16:26:42.874] at async mut (/var/task/sandbox.js:197:17526) This is my 'vercel.json' { "build": { "env": { "SECRET_KEY": "django-insecure-ub4*yrbpi+6#v3%(2w^!@u&r%pq6q6le4vi)enqpi6edmou)%#", "DEBUG": "True", "DB_HOST": "ec2-34-197-84-74.compute-1.amazonaws.com", "DB_NAME": "dc3rdsgt6ufbqd", "DB_USER": "xjvzrnscnfbses", "DB_PORT": "5432", "DB_PASSWORD": "cedb50250cec0e8ecc080a361a20e41133b561a3a92ac6038eff49c9219fc9e7" } }, "builds": [{ "src": "cores/wsgi.py", "use": "@ardnt/vercel-python-wsgi", "config": { "maxLambdaSize": "15mb", "runtime": "python3.8" } }], "routes": [ { "src": "/(.*)", "dest": "cores/wsgi.py" } ] } I got stuck with this, so anyone … -
Django doesn't requests the data to login users
<form action="login" method="post" > {% csrf_token %} <div class="form-group mb-3"> <label class="label" for="name">username</label> <input type="text" id="username" class="form-control" required> </div> <div class="form-group mb-3"> <label class="label" for="password">password</label> <input type="password" id="password" class="form-control" required> </div> <div class="form-group"> <input type="submit" action="login"> </div> <div class="form-group d-md-flex"> <div class="w-50 text-left"> <label class="checkbox-wrap checkbox-primary mb-0">Remember Me <input type="checkbox" checked> <span class="checkmark"></span> </label> </div> <div class="w-50 text-md-right"> <a href="#">Forgot Password</a> </div> This is the form. def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("dashboard") else: messages.info(request, "User doesn't exist. Contact the teacher!") return redirect("index") else: return render(request, "login.html") This is the views function. from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.contrib.auth import authenticate, login Those are the imports. But this doesn't redirect user who has already registered, to the page specified. Not a problem of urls or the csrf_token. I think the problem is in the sending data part because the else function triggers and shows the massege user doesn't exist..... Please help. -
Django runserver not woking (it's showing indentation error)
I tried to run my server but it did not work, it ended showing this instead. please help me File "C:\Users\ivbec\Envs\tutorial\lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "C:\Users\ivbec\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\ivbec\python\djangoprojects\tutorial\myproject\myapp\urls.py", line 2, in <module> from . import views File "C:\Users\ivbec\python\djangoprojects\tutorial\myproject\myapp\views.py", line 5 def index(request): IndentationError: unexpected indent -
How can i route request to specific views according to parameters in Django?
I created an API with Django and i am trying to route requests to different views for optimization purposes. Here is what i'm trying to do: if the GET request is 127.0.0.1:8000/api/sales/?key=<KEY>&some_query=<some_value>&... that query should be handled by a view called sales. If the GET request contains a specific parameter called sale_value the request should be routed to another view called large_sales, for example 127.0.0.1:8000/api/sales/?key=<KEY>&sale_value=<INT>... should be handled from the large_sales view. Here is what i tried: urlpatterns = [ path('sales/', views.sales, name="sales"), path('sales/sale_value<int:num>', views.large_sales, name="large_sales"), ] This will route all the requests to sales. How can i do this? Maybe with regex? -
Djnago ninja | Trying to send file | no validator found for <class 'django.http.response.HttpResponse'>, see `arbitrary_types_allowed` in Config
good people, I'm trying to implement a file download functionality. And the code is pretty straightforward: @api.get("/summary/", response=HttpResponse) def report_summary( request: NinjaRequest, start_date: str, end_date: str ) -> HttpResponse: ... response = HttpResponse( output, # output is the file content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) response["Content-Disposition"] = f"attachment; filename={fname}" # fname is the name of the file return response But it gives me an error saying during bootup: RuntimeError: no validator found for <class 'django.http.response.HttpResponse'>, see `arbitrary_types_allowed` in Config I don't want to set arbitrary_types_allowed. Now how can I resolve this issue? -
Why django ManytoManyFied don't save some models?
Below is my models.py. class Report(models.Model): company_name = models.CharField(max_length = 40, default = "-") favorite = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Fav', related_name='favorite_reports') def __str__(self): return self.company_name class Fav(models.Model) : report = models.ForeignKey(Report, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='favs_users') class Meta: unique_together = ('report', 'user') def __str__(self) : return '%s likes %s'%(self.user.username, self.report.company_name[:10]) Below is views.py def post(self, request, pk) : t = Report.objects.get(id = pk) fav = Fav(user=request.user, report=t) try: fav.save() # In case of duplicate key print(request.user.favorite_reports) #home.Report.None print('t =', t.favorite) # t = auth.User.None print('fav =',fav.report, fav.user) # fav = untitle hello1 print('uesr =',request.user, request.user.favorite_reports,request.user.favs_users) #uesr = hello1 home.Report.None home.Fav.None except IntegrityError as e: pass return redirect('home:homepage') I want show different button color to user whether user fav some report or not. So I checked request.user.favorite_reports and request.user.favs_users after I save Fav but it return home.Report.None home.Fav.None But When I print fav.report, fav.user It returns well. Why this happened? How can I check user Fav some report in template? like {% if report.company_name in user.favorite_reports %} But It dosen't works. -
Django URLCONF and reverse
I am trying to understand how django links the main urls.py with the url patterns of another application-Here in my case I have 2 apps: loginpage and signup. I defined in the main urls.py this: urlpatterns = [ path('admin/', admin.site.urls), path('',include('loginpage.urls')), path('signup/',include('signup.urls')),] and this in loginpage.urls: app_name='loginpage' urlpatterns = [ path('',views.login_page_fetch,name='login_page_fetch'), path('Verification/',views.check_user,name='check_user') ] I created a function in loginpage/views that get a template and fetch it: def login_page_fetch(request): return render(request,'loginpage/login.html') Now in my signup/views I created a function that created a user etc.. it will have in the end to redirect him to the login page: def create_user(request): user=User() user.first_name=request.POST.get('firstname') user.last_name=request.POST.get('familyname') user.email_address=request.POST.get('email') user.password=request.POST.get('psw') user.save() return HttpResponseRedirect(reverse('loginpage:login_page_fetch')) *//* I cannot understand starting from here // how django finds the login_page_fetch function-does he start looking in the main urls.py file to find a path where its mapped to loginpage.urls? -
NOT NULL constraint failed: forum_question.user_id (django)
I'm trying to save an object using cbv's im new to using it, and I'm trying to save an object using create view but is getting this error: "NOT NULL constraint failed: forum_question.user_id" I would appreciate beginner friendly explanation on how to fix this and maybe tips as well, thank you! models.py: class Question(VoteModel, models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=30) detail = models.TextField() tags = models.TextField(default='') add_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title forms.py: class QuestionForm(ModelForm): class Meta: model = Question fields = ['title', 'detail', 'tags'] views.py: class AskForm(CreateView): def post(self): user = self.request.user model = Question form_class = QuestionForm template_name = 'forum/ask-question.html' if form_class.is_valid(): form_class.save() -
python image scrapper become base64
I have scrapper tools, but my code are always scrap base64 instead of real urls,here is my code: import requests from bs4 import BeautifulSoup baseurl = "https://www.google.com/search?q=beli+anjing&sxsrf=APq-WBt4jLZxrfwaRP4YeYUhlfB-EWkTlw:1649653964236&source=lnms&tbm=shop&sa=X&ved=2ahUKEwjEnan0n4v3AhUNRmwGHTIVDlQQ_AUoAnoECAEQBA&biw=1365&bih=937&dpr=1" headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0"} r = requests.get(url=baseurl, headers=headers) soup = BeautifulSoup(r.content, 'lxml') for product_images in soup.findAll('div', attrs={'class': 'ArOc1c'}): print (product_images.img['src']) The result is something like: data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== And here is the html element that i wanna to scrap: <img id="10857343619710684967" src="https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcTP0ECipmHbw3MkChu6xHYkHA3AzxaiNoUnqxaW35bfDkFugfhO23iwklpDjhYlUFI-RIyLu95TkcpNCBGxBeKPIarPilIv6a697PoK-RM&amp;usqp=CAE" alt="" role="presentation" data-atf="4" data-frt="0"> I want the src value, but when i scrap, it always get base64 instead of the real urls like above. result that i want: https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcTP0ECipmHbw3MkChu6xHYkHA3AzxaiNoUnqxaW35bfDkFugfhO23iwklpDjhYlUFI-RIyLu95TkcpNCBGxBeKPIarPilIv6a697PoK-RM&amp;usqp=CAE -
TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username'
i dont want to have username field in django and removed it but now when i want to create a superuser got an error for missing username field!! error: TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' my user model class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] -
Unpack the list and put as variable
I have source code like this chain accept the multple number of lists. list1 = [1,2,3] list2 = [1,2,3] list3 = [1,2,3] chain(list1,list2,list3) However I want to treat list1 list2 list3 as one list and put this in chain total = [list1,list2,list2] chain(total) # it doesn't work , ochain doesn't accept the list. Is there any good way to do this? -
Apache virtual hosts on subdirectories
I am trying to setup Apache to serve multiple apps on one IP-Address over subdirectories. Lets say, I would like to access App1 over http://aaa.bbb.ccc.ddd/app1 and App2 over http://aaa.bbb.ccc.ddd/app2. Both, App1 and App2, are independent django projects. I ensured, that both apps are working fine by serving only one of them over Apache. I added the following lines to the httpd.conf file of Apache: # App1 <VirtualHost *:80> DocumentRoot "D:/Projects/App1/App1" ServerName App1 <Directory "D:/Projects/App1/App1"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias /app1 "D:/Projects/App1/App1/wsgi.py" </VirtualHost> # App2 <VirtualHost *:80> DocumentRoot "D:/Projects/App2/App2" ServerName App2 <Directory "D:/Projects/App2/App2"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias /app2 "D:/Projects/App2/App2/wsgi.py" </VirtualHost> Working like this results into an error saying "Forbidden, You don't have permission to access this resource." when I call http://aaa.bbb.ccc.ddd/app2 from another machine. Similar to this, if I put the App2 virtual host in front of the App1 virtual host, I can not access http://aaa.bbb.ccc.ddd/app1 anymore. So it is either App1 or App2 that is accessible, but never both of them. First question: Is my idea of serving to webpages over sub-URL's even possible? If not, what would be the alternative? Using different ports for different applications? If it is a "valid" approach, … -
extract signature from SignatureField in Django
here i am using python3 and Django 3.0 Here am i saving the signature into my database and now i need to display this signature in my pdf file But i am not able to display it in the pdf file here is my views.py def jobspecific_view_1(request, pk): form = CustomerSignatureForm(request.POST or None) if form.is_valid(): customer_signature = form.cleaned_data.get('customer_signature') if customer_signature!=None: signature_picture = draw_signature(customer_signature) output = io.BytesIO() signature_picture.save(output, "PNG") contents = base64.b64encode(bytes('output', 'utf-8')) customer_data = contents output.close() job = AddJob.objects.get(id=pk) job.signature = customer_data job.save() ...... ...... here is my views.py for generating the pdf def render_to_pdf(template_src, context_dict, pdf_title): template = get_template(template_src) context = Context(context_dict) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = "attachment; filename={0}".format( unidecode( pdf_title.replace( ',', '').replace( ';', '').replace(' ', '_'))) logger.debug('Content-Disposition: {0}'.format(response['Content-Disposition'])) return response logger.error(pdf.err) return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html)) def generate_pdf_view(request, pk): client = request.user.client job_id = AddJob.objects.filter(id=pk) viewed_job = get_object_or_404(AddJob, id=pk, created_by__client=client) job_data={} for val in job_id: job_data['job_id'] = pk job_data['title'] = val.title job_data['job_number'] = val.job_number job_data['customer_signature_1'] = val.customer_signature_1 ...... ...... pdf_title = u'{0}_{1}_{2}.pdf'.format( job_data['title'], job_date.strftime('%d_%m_%Y'), job_data['job_type']) return render_to_pdf('jobs/jobpdf.html', { 'pagesize':'A4', 'job_data': job_data, 'viewed_job': viewed_job, 'request': request, }, pdf_title) Here is my forms.py … -
Django floatformat and intcomma not formatting the string right
I have been trying to use floatformat and intcomma to format a string with only 1 decimal place and with the dot divider for thousands So I'd like to get 1 -> 1,0 4000 -> 4.000,0 4567,56 -> 4.567,6 By using intcomma only I get 4.567,56 By using floatformat and intcomma I get 4,567,56 I have tried in the settings to use USE_I18N = True USE_L10N = True DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' but nothing changed, how does this work? -
Cannot properly save to a db with OneToOne relationship
The flow of what I want to do is the following: I have two tables, namely Event and Result. The Event table is connected with ForeignKey with a user and the Result table is connected with OneToOne relationship with Event. In my views.py I have one POST and one GET. In POST, I take some data and save it in the table Event. In GET, I solve an optimization problem and I want to save the solution into Result. The models.py is as follows: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) class Result(models.Model): event_id_result = models.OneToOneField(Event, on_delete=models.CASCADE, null=True) HVAC_flex = ArrayField(models.FloatField(blank=True, null=True)) DHW_flex = ArrayField(models.FloatField(blank=True, null=True)) lights_flex = ArrayField(models.FloatField(blank=True, null=True)) The serializers.py is as follows: from rest_framework import serializers from vpp_optimization.models import Event, Result class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('__all__') class ResultSerializer(serializers.ModelSerializer): HVAC_flex = serializers.ListField(child=serializers.FloatField()) DHW_flex = serializers.ListField(child=serializers.FloatField()) lights_flex = serializers.ListField(child=serializers.FloatField()) class Meta: model = Result fields = ('__all__') The views.py is as follows: from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework … -
nameError: name 'request is not defined
I'm trying to build an absolute url with reverse but I get the above error. Code: def get_endpoint(payload): url = request.build_absolute_uri(reverse("app-start-conversation")) data = json.dumps(payload) response = requests.post(url, data, headers=head) Urls.py: path( "api/v2/app/startconversations", views.StartConversation.as_view(), name="app-start-conversation, ) I get the error nameError: name 'request is not defined How do I import request? The reason I need the full url is because with reverse alone, when I run the app locally I get the following error and I do not want to hardcode 120.0.0.1:8000/ to the url. requests.exceptions.MissingSchema: Invalid URL '/api/v2/app/startconversations': No schema supplied. Perhaps you meant http:///api/v2/app/startconversations? -
Importing django modules without settings being configured
Consider following simple scenario. Given File common.py from data import MyModel # This is a Model inheriting django.db.models.Model def foo(bar: MyModel): print(bar) def other_func(): pass And given file main.py, using one of the functions in common, but not the other one that depends on django. import common from django.conf import settings if __name__ == "__main__": config_file = sys.argv[1] # This would be argparser in real life scenario settings.configure(....config_file...) common.other_func() This format is how i believe most main functions would look like since settings often depend on environment variable, config files or command line arguments. I'm not able to run this code because any time one simply imports a django model, it attempts to load settings and access the database. With following error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Next attempt, move the settings.configure above the imports inside main.py, from django.conf import settings settings.configure(.....) import common This works, but it infects the entire code base, making it impossible to import common from any other modules and in unit tests. Unless every single potential entrypoint is guaranteed to also call settings.configure first. Last … -
Can't get form class object in template view
I want to get the form object from self.Form This is my form class ActionLogSearchForm(forms.Form): key_words = forms.CharField(required=False) and I set form as form_class, however I can't fetch the form data in view class ActionLogListView(LoginRequiredMixin, ListSearchView): template_name = "message_logs/action_log.html" form_class = ActionLogSearchForm def get_queryset(self): res = [] form = self.form ## somehow form is None print(form.cleaned_data) # error occurs here. 'NoneType' object has no attribute 'cleaned_data' I think this is the simplest set, but how can I make it work? -
Can't import a module in Django project
This is my django project folder: mysite ├── mypage │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── mysite │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── utils ├── __init__.py ├── __pycache__ │ └── __init__.cpython-38.pyc └── util.py This is the error message that I get when I run the server. Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/gigidagostino/Desktop/django_experment/venv/lib/python3.8/site-packages/django/core/checks/urls.py", …