Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to bind input fields from model forms into vue
Usually you can grab input fields you manually created through v-model like these: <input class="form-control mb-2" name="username" v-model="username" type="text" placeholder="username" autocomplete="off"> <input class="form-control" type="password" v-model="password" placeholder="password"> However, how can I grab and place v-model on fields that are auto-generated by Django through model forms? <form method="post"> {% csrf_token %} {{ user_form }} <button class="btn btn-primary mt-3">Register</button> </form> -
django-auth-ldap INVALID_CREDENTIALS when authenticating
I am attempting to utilize the django-auth-ldap library however I am unable to connect to the server successfully. When I navigate to the django login screen and use an account associated with our active directory server I get the following error in the logs Caught LDAPError while authenticating user@domain.com: INVALID_CREDENTIALS({'msgtype': 97, 'msgid': 1, 'result': 49, 'desc': 'Invalid credentials', 'ctrls': [], 'info': '80090308: LdapErr: DSID-0C090446, comment: AcceptSecurityContext error, data 52e, v2580'},) I have my settings.py file setup as follows. import ldap, logging from django_auth_ldap.config import LDAPSearch, GroupOfNamesType AUTHENTICATION_BACKENDS = [ "django_auth_ldap.backend.LDAPBackend", "django.contrib.auth.backends.ModelBackend", ] AUTH_LDAP_SERVER_URI = "ldap://serverIP" AUTH_LDAP_AUTHORIZE_ALL_USERS=True AUTH_LDAP_BIND_DN = "cn=service user,OU=ServiceAccounts,dc=domain,dc=com" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_SEARCH = LDAPSearch( "dc=domain,dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user))" ) # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_CACHE_TIMEOUT = 1 When I test the following ldapsearch command everything works as expected ldapsearch -H ldap://serverIP -D user@domain.com -b "dc=domain,dc=com" -W "(samAccountName=serviceUser)" and from this output I can see that the serviceUser has the following DN CN=service user,OU=ServiceAccounts,DC=DOMAIN,DC=COM -
Django: annotate() + distinct(fields) is not implemented
I have following models: class Village(models.Model): packages_required = models.IntegerField() . . class PackageSent(models.Model): village = models.ForeignKey('myapp.Village') package_count = models.IntegerField() sending_user = models.ForeignKey('myapp.Users') sending_account_user = models.ForeignKey('myapp.Users') . . And I need to select all Villages along with their PackageSent models. I built the following query: Village.objects.filter( filter_logic ).order_by( order_by_logic ).annotate( packages_missing=F("packages_required") - Sum("packagesent__package_count"), users_involved=Count("packagesent__sending_account_user", distinct=True) ).prefetch_related( models.Prefetch( "packagesent_set", queryset=PackageSent.objects.filter( filter_logic ).annotate( total_account_sent=Sum("package_count"), sending_users=ArrayAgg("sender_user_id") ).distinct( "sending_account_user_id" ), to_attr="packages_sent" ) ) However this query raises annotate() + distinct(fields) is not implemented error. The query I need for PackageSent model in MySQL syntax: SELECT *, SUM(package_count) AS `total_account_sent`, GROUP_CONCAT(sending_user) AS `sending_users` FROM `myapp_packagesent` ps LEFT JOIN `myapp_village` v ON v.id = ps.village_id GROUP BY `sending_account_user`, `village_id` ORDER BY `total_account_sent` DESC I would like to do this in a template: {% for village in object_list %} . . . {% for package_sent in village.packages_sent %} . . . {% endfor %} {% endfor %} How can I achieve the results I want? Technologies used: Django 3.0 PostgreSQL -
ConnectionAbortedError in Django
Whenever this view is executed my server showed up with some error which I don't know why! the view which I was executing is @api_view(['POST']) def Signin(request): if request.method == 'POST': username = request.POST.get('username') passw = request.POST.get('password') email = request.POST.get('email') fullname = request.POST.get('fullname') college = request.POST.get('college_name') city = request.POST.get('city') country = request.POST.get('country') User.objects.create_user( username=username, password=passw, email=email) Userinfo.objects.create( user_name=username, full_name=fullname, user_email=email, college_name=college, city=city, country=country , varified_user=False) return Response({'status': 'created'}) And what i know after checking my database is my code is executing till user_name=username, full_name=fullname, user_email=email, college_name=college, city=city, country=country , varified_user=False) because I can see the data which I was inserting, now i don't know what error can cause by return Response({'status': 'created'}). The message in my terminal is Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 29, 2020 - 21:19:18 Django version 3.1, using settings 'backend.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [29/Sep/2020 21:19:31] "POST /api/usercheck/ HTTP/1.1" 200 18 [29/Sep/2020 21:19:34] "POST /api/usercheck/ HTTP/1.1" 200 18 [29/Sep/2020 21:19:35] "POST /api/usercheck/ HTTP/1.1" 200 21 [29/Sep/2020 21:19:58] "POST /signin/ HTTP/1.1" 200 3318 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 65332) Traceback (most recent call last): File "C:\Python38\lib\socketserver.py", … -
[Django rest_framework]Problems in using redis as Django DRF cache
I'm trying to open the redis cache for the rest framework. My configuration seems to be correct. When I run, it reports an error. As shown below: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\settings.py", line 177, in import_from_string return import_string(val) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework_extensions\utils.py", line 6, in <module> from rest_framework_extensions.key_constructor.constructors import ( File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework_extensions\key_constructor\constructors.py", line 4, in <module> from rest_framework_extensions.key_constructor import bits File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework_extensions\key_constructor\bits.py", line 3, in <module> from django.db.models.sql.datastructures import EmptyResultSet ImportError: cannot import name 'EmptyResultSet' from 'django.db.models.sql.datastructures' (C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\datastructures.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\HUANG\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 392, … -
Wagtail V2 API force HTTPS for the html_url and detail_url
I am currently developing a portfolio website that has a Django + Wagtail backend to manage the content in a React frontend that talks to each other through Wagtail V2 API and Django-Rest-Framework. I am currently running into an issue where I am able to get the pages from the API, but when my frontend tries to load individual page details the Wagtail v2 API is sending the detail_url as a http url where my nginx setup requires https. I have looked all over the wagtail documentation and stackoverflow for the answer to forcing the detail_url to be a https url but I cannot find the answer or documentation anywhere, nor do I know where to start. What part is causing the http? Is it Django, Wagtail or Rest-Framework? And how do I get it to be https This is what my JSON code looks like from the backend { "meta": { "total_count": 2 }, "items": [ { "id": 3, "meta": { "type": "pages.HomePage", "detail_url": "http://dylan.primic.com/api/v2/pages/3/", "html_url": "http://dylan.primic.com/", "slug": "home", "first_published_at": "2020-09-29T14:58:50.272668Z" }, "title": "Home" }, { "id": 4, "meta": { "type": "pages.AboutPage", "detail_url": "http://dylan.primic.com/api/v2/pages/4/", "html_url": "http://dylan.primic.com/about-me/", "slug": "about-me", "first_published_at": "2020-09-29T15:00:10.624868Z" }, "title": "About Me" } ]} Any help will … -
ManyToManyField with model_to_dict(self)
Not sure if the title is the correct one, sorry for the inconvenience. I'm having a problem on sending a ManyToManyField from a model to a dictionary using the model_to_dict() Below is my code models.py from django.db import models from django.forms import model_to_dict from app_1.models import * class Stuff(models.Model): thing_1 = models.CharField(max_length=100, null=True, blank=True) thing_2 = models.ManyToManyField(OtherStuff, blank=True, related_name="thing") def toJSON(self): item = model_to_dict(self) item['thing'] = self.thing.toJSON() return item When I run a query and load my Stuff model, I get the following error: from app_2.models import * s = Stuff.objects.get(pk=1) # here is where I send my model to a dictionary s.toJSON() Traceback (most recent call last): File "<input>", line 1, in <module> File "P:\test\app\app_2\stuff\models.py", line 10, in toJSON return item AttributeError: 'ManyRelatedManager' object has no attribute 'toJSON' I've come across multiple ways of sending a ManyToManyField to a dictionary, however, none of them use the model_to_dict(). I'd like to use this method due to it's simplicity of usage. -
page is loading very slow
Hi there I have a page and it is loading very slow. I had a very similiar question but this time I guess it requires another solution. I use django for my website and it has some jquerry in the template however I guess that the issue can be on the views. I will post my views and if it is neccessary my templates. Thank you in advance. views.py from django.shortcuts import render import openpyxl def index(request): wb=openpyxl.load_workbook('ders.xlsx') ws=wb.active context_lectures=[] context_lecture=[] context_select=[] for i in range(ws.max_row): day=ws.cell(row=i+1,column=6).value a=0 for j in range(len(day)): if day[j].isupper() and j!=0 and a!=j: day=day[:j]+' - '+day[j:] a=j+3 hour=ws.cell(row=i+1,column=7).value b=0 for k in range(len(hour)): if k%9==0 and k!=0: hour=hour[:k+b]+' - '+hour[k+b:] b+=3 lectures=ws.cell(row=i+1,column=2).value[:4] lecture=ws.cell(row=i+1,column=2).value select=ws.cell(row=i+1,column=1).value+' | '+ws.cell(row=i+1,column=2).value+' | '+ws.cell(row=i+1,column=3).value+' | '+ws.cell(row=i+1,column=4).value+' | '+day+' | '+hour if lectures in context_lectures: pass else: context_lectures.append(lectures) if lecture in context_lecture: pass else: context_lecture.append(lecture) if select in context_select: pass else: context_select.append(select) return render(request,'index.html',{'context_lectures': context_lectures,'context_lecture':context_lecture,'context_select':context_select}) and I would also ask where should I deploy my xlsx file. I didn't found a solution so I deployed it on the main project folder where manage.py is. -
Twilio with Django
I am trying to use Twilio with Django. I have followed this tutorial and it works properly. I am now trying to apply that within my own project. I've taken a copy of package.json into my project's root directory and I've run npm install to set up the node_modules directory. I have also copied the get_token and call views as is. Something is going wrong in the JS because I can see the get_token call but not the call call (if you know what I mean). My call button is an exact copy of the example project and when I click it I get the following error: Received an error from MediaStream: Object { info: {…} } twilio.min.js:99:91242 error http://127.0.0.1:8000/static/twilio.min.js:99 onerror http://127.0.0.1:8000/static/twilio.min.js:99 _initializeMediaStream http://127.0.0.1:8000/static/twilio.min.js:99 makeOutgoingCall http://127.0.0.1:8000/static/twilio.min.js:99 connect http://127.0.0.1:8000/static/twilio.min.js:99 accept http://127.0.0.1:8000/static/twilio.min.js:99 (Async: promise callback) accept http://127.0.0.1:8000/static/twilio.min.js:99 connect http://127.0.0.1:8000/static/twilio.min.js:99 callCustomer http://127.0.0.1:8000/static/prospecting/js/browser-calls.js:106 onclick http://127.0.0.1:8000/?page=3:1 My Twilio settings have been checked, double checked and triple checked. I believe them to be correct. -
Django-React argument of type 'WindowsPath' is not iterable - When processing the login post request
I am developing a simple Django react JWT authentication system. When I try to obtain the access token, I get the following stack trace. I was getting it just random with the website working, now I can't get the token. The server is not shutting down. [29/Sep/2020 17:40:27] "POST /api/token/obtain/ HTTP/1.1" 200 486 Traceback (most recent call last): File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 196, in finish_response self.close() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\servers\basehttp.py", line 114, in close super().close() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\simple_server.py", line 38, in close SimpleHandler.close(self) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 335, in close self.result.close() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\http\response.py", line 253, in close signals.request_finished.send(sender=self._handler_class) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\dispatch\dispatcher.py", line 173, in send return [ File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\dispatch\dispatcher.py", line 174, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\__init__.py", line 57, in close_old_connections conn.close_if_unusable_or_obsolete() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 525, in close_if_unusable_or_obsolete self.close() File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\bratca\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable [29/Sep/2020 17:40:27] "POST /api/token/obtain/ HTTP/1.1" 500 59 and the following error right after it, I guess it's a chain of … -
django: Update dabatase table with a formset
I am confused about formsets. I built a form and a view to insert one database table row that working just fine, and I just built a formset in a view to be able to insert several rows at once. My issue is that the formset does not seem to work. Nothing gets changed in the DB. Here is what my form look like: class ProcurementOperationRecordForm(forms.ModelForm): class Meta: model = replenishment fields = ('Id', 'Quantity', 'NetAmount', 'Supplier', 'SellPrice') and here is what my former view looked like: #def New_Purchase(request): #if request.method == 'POST': #form = ProcurementOperationRecordForm(request.POST) #if form.is_valid(): #form.save() #quantity = form.cleaned_data.get('Quantity') #id = form.cleaned_data.get('Id') #update = replenishment.objects.filter(Id = id).update(StockOnOrder =+ quantity) #update2 = Item2.objects.filter(reference = id).update(en_cours_de_reception =+ quantity) #quantity = form.cleaned_data.get('Quantity') #id = form.cleaned_data.get('Id') #update = replenishment.objects.filter(Id = id).update(StockOnOrder = (StockOnOrder + quantity)) #return redirect('/dash2.html') #else: #form = ProcurementOperationRecordForm() #context = {'form': form,} #return render(request, 'new_purchase.html', context) and here is what my formset view looks like: def New_Purchase(request): context = {} form = formset_factory(ProcurementOperationRecordForm, extra = 3) formset = form() context['formset'] = formset return render(request, 'new_purchase.html', context) I don't know what to do to make this formset works, would someone have a clue that could unblock the situation? -
Django internationalization doesn't work on my system
It has been several hours I am going through answers in Stackoverflow and looking documentation to solve this. I recently asked this question explaining why Django internationalization doesn't work in my project. I downloaded gettext versions from here. I am asking this question because I restarted a new project from scratch set up everything for Django translation, but still this new project doesn't work as well. What is happening? any hint or clue please. It sounds it is something outside Django in my installation or computer or what I don't know? Thank you -
Changing render context data if Post request
I would like to change my variable data according to what i get from my post request. Print(data) return correct values in my console but data in my template is still equal to Post.objects.all() even if my inp = "radio-two" or "radio-three". views.py @csrf_exempt def update_radio(request): post = Post.objects.all() tag = Tag.objects.all() editor = EditorProfile.objects.all() data = Post.objects.all() if request.method == 'POST': print("get input") print("update radio post request") inp = request.POST.get('input',None) if(inp == "radio-two"): data = post elif(inp == "radio-three"): data= editor else: data = tag print(data) return render(request, 'blogapp/radio2.html',{'data':data}) -
My Django project can't import shortcuts (Pylint Import Error)
Unable to import 'django.shortcuts'pylint(import-error) how can i solve this error -
Django ORM query two ManyToMany relationships, via a ForeignKey relationship
class ThingDefinition(models.Model): ... class Thing(models.Model): definition = ForeignKey(ThingDefinition) class FooGroup(models.Model): thing_definitions = ManyToManyField(ThingDefinition, blank=True) class Bucket(models.Model): contents = ManyToManyField(Thing, blank=True) foo_group = ForeignKey(FooGroup) @property def prop(self): expected_contents = {self.foo_group.thing_definitions} actual_contents = {x.thing_definition for x in self.contents} return bool(expected_contents.difference(actual_contents)) I am trying to write a django ORM query tog get the value of prop. I have written some python which gives the right answer; it is too slow to use, but it should make it clear what I am trying to achieve. To summarise in English: For each Thing in the many to many field self.contents, get the value of the foreign key to ThingDefinition Follow the foreign key relationship self.foo_group, and get the values of the ManyToManyField thing_definitions. Compare these two querysets, and return True if the latter contains things not contained in the former. -
Have Django templates render registration/login form and React rest of the application
Is it a good approach to have Django built-in templates to handle login/registration views, which on successfull login would redirect to a login required view with html template that has the React application embeded in it? Rest of the communication would be a django-rest-framework and React-query or redux-saga on the frontend. Obviously no request without the user authorized will be allowed. -
Using Factory Boy inside a dict for a data model factory in Django? Alternatively, getting FactoryBoy to evaluate subfactory on demand?
I have the following ModelFactory: class ProjectDataModelFactory(DjangoModelFactory): project = factory.SubFactory("projects.factories.ProjectModelFactory") version = "1" content = { "id": {"value": fuzzy.FuzzyText(length=7, chars=string.ascii_letters).fuzz().upper(), "type": "string"}, "win_probability": {"value": fuzzy.FuzzyInteger(0, 100).fuzz(), "type": "number"}, "bid_value": { "value": fuzzy.FuzzyInteger(0, 10000000).fuzz(), "type": "number", }, "status": {"value": random.choice(["Won", "Lost"]), "type": "string"}, "sector": { "value": random.choice( ["Construction", "Technology", "Finance", "Consulting", "Agriculture", "Engineering"] ), "type": "string", }, } In content["id"], I would like to have value be project.external_id instead of fuzzy.FuzzyText(length=7, chars=string.ascii_letters).fuzz().upper(). external_idis part of the ProjectModel. But when I put project.external_id in the place of the fuzzer, I get this error: AttributeError: 'SubFactory' object has no attribute 'external_id This only seems to be a problem with dicts. We have not had issues using it in other contexts. I do not have a lot of experience using FactoryBoy, so it could easily be something trivial. Any ideas? -
No modules named _sqlite3 when starting Django project on a shared hosting site
I am using a shared hosting site (centOS) to host my Django site. I can get python 3.8.5 running and Django installed, but if I run python manage.py shell, I get the following error output Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home4/bendempe/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home4/bendempe/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home4/bendempe/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home4/bendempe/python/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home4/bendempe/python/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home4/bendempe/python/Python-3.8.5/Lib/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home4/bendempe/python/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home4/bendempe/python/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/models/base.py", line 122, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/models/base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/models/options.py", line 206, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/utils.py", … -
get value form and if it is null, leave the field empty for input
hi I have automated my field but if the value to be retrieved is null it puts error undefined method for nil: NilClass how I solve this problem in the view with get value Controller def show @ref_entraineur = CarriereDocumentFootballeur.where(id: params[:id]) end in views <%= f.text_field :num_entraineur , label: "Numéro Entraineur " , value: @ref_employeur.last.num_entraineur %> -
How to solve round() bug in python? [duplicate]
I recently found out that round function gives wrong output sometimes.Can anyone plz solve this? print(round(60256.5)) And the expected output was 60257. But instead it was 60256 -
Django Celery Scheduled Task Crashing
Im trying to run a scheduled task on my Django project that is hosted on Heroku, however my task keeps crashing and I dont know how to fix this. Here is the error message bellow I'm getting in the error logs. I have in my settings.py my timezone set to 'America/New_York' and I even tried added the time zone as well in the celery.py to be the same to try to troubleshoot it but has no affect on it. I appreciate the help. Thanks Full Traceback 2020-09-29T14:42:42.978802+00:00 app[beat.1]: [2020-09-29 10:42:42,978: INFO/MainProcess] DatabaseScheduler: Schedule changed. 2020-09-29T14:42:42.978947+00:00 app[beat.1]: [2020-09-29 10:42:42,978: INFO/MainProcess] Writing entries... 2020-09-29T14:42:43.007143+00:00 app[beat.1]: [2020-09-29 10:42:43,006: INFO/MainProcess] Writing entries... 2020-09-29T14:42:43.009099+00:00 app[beat.1]: [2020-09-29 10:42:43,007: CRITICAL/MainProcess] beat raised exception <class 'TypeError'>: TypeError("can't compare offset-naive and offset-aware datetimes",) 2020-09-29T14:42:43.009100+00:00 app[beat.1]: Traceback (most recent call last): 2020-09-29T14:42:43.009101+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/celery/apps/beat.py", line 109, in start_scheduler 2020-09-29T14:42:43.009102+00:00 app[beat.1]: service.start() 2020-09-29T14:42:43.009103+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/celery/beat.py", line 631, in start 2020-09-29T14:42:43.009103+00:00 app[beat.1]: interval = self.scheduler.tick() 2020-09-29T14:42:43.009104+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/celery/beat.py", line 329, in tick 2020-09-29T14:42:43.009104+00:00 app[beat.1]: self.populate_heap() 2020-09-29T14:42:43.009105+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/celery/beat.py", line 303, in populate_heap 2020-09-29T14:42:43.009105+00:00 app[beat.1]: is_due, next_call_delay = entry.is_due() 2020-09-29T14:42:43.009106+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django_celery_beat/schedulers.py", line 116, in is_due 2020-09-29T14:42:43.009106+00:00 app[beat.1]: if now < self.model.start_time: 2020-09-29T14:42:43.009238+00:00 app[beat.1]: TypeError: can't compare offset-naive … -
Django views opens different content
I am new to Django. I have created 2 seperate views and URLs, however, when I load my development server and click on slides to open slides_detail.html, it opens sub_detail.html, at this point I have no clue what could cause that as there are no similar names which would lead to opening completely different detail page. Both slides and subcontent sits in the same HTML document, same with URLs and views. There are no errors, to show. Thanks in advance: URLS: path('<int:sub_id>/', views.sub_detail, name='sub_detail'), path('<int:slides_id>/', views.slides_detail, name='slides_detail'), Views: # Will show specific sub content details def sub_detail(request, sub_id): subcontent = get_object_or_404(SubContent, pk=sub_id) context = { 'subcontent': subcontent, } return render(request, 'home/sub_detail.html', context) # Will show specific slides content details def slides_detail(request, slides_id): slides = Slides.objects.get(pk=slides_id) context = { 'slides': slides, } return render(request, 'home/slides_detail.html', context) HTML for slides: {% for slides in slides %} <div class="swiper-slide"> <div class="card"> <a href="{% url 'slides_detail' slides.id %}"> <img src="{{ slides.image.url }}" class="card-img-top img-height" alt="..."></a> <div class="card-body bg-dark"> <h5 class="card-title text-light font-weight-bold text-center">{{ slides.title }}</h5> </div> </div> </div> {% endfor %} HTML for subcontent: {% for sub in subcontent %} {% if forloop.counter|divisibleby:2 %} <div class="row"> {% if sub.image %} <div class="col-md-6 section-index-img"> <img … -
local variable 'intent' referenced before assignment
Can anyone please help me to fix this problem local variable 'intent' referenced before assignment i could not find out why client_secret in the context is triggered. to my knowledge if the code in if statement fails then else block will be executed but i have set a print statement and it does not appear in the teminal either. if someone can please help me in solving this issue. from django.shortcuts import render, redirect, reverse from django.contrib import messages from django.conf import settings from .forms import OrderForm from .models import Order, OrderLineItem, ProductLineItem, ExerciseLineItem, NutritionLineItem from merchandise.models import Product from exercise.models import ExercisePlans from nutrition.models import NutritionPlans from cart.contexts import cart_contents import stripe def checkout(request): stripe_public_key = settings.STRIPE_PUBLIC_KEY stripe_secret_key = settings.STRIPE_SECRET_KEY if request.method == 'POST': cart = request.session.get('cart', { 'merchandise_dic': {}, 'excercise_plans_dic': {}, 'nutrition_plans_dic': {}, }) form_data = { 'full_name': request.POST['full_name'], 'email': request.POST['email'], 'phone_number': request.POST['phone_number'], 'country': request.POST['country'], 'postcode': request.POST['postcode'], 'town_or_city': request.POST['town_or_city'], 'street_address1': request.POST['street_address1'], 'street_address2': request.POST['street_address2'], 'county': request.POST['county'], } order_form = OrderForm(form_data) if order_form.is_valid(): print("Order form is valid") order = order_form.save() for product_type, dic in cart.items(): if product_type == 'merchandise_dic': for item_id, quantity in dic.items(): print(f"This is item id of merchandise: {item_id}") print(f"This is quantity of merchandise: {quantity}") product = Product.objects.get(id=item_id) … -
Designing search API endpoint with filter and query
I have been looking into designing a RESTful search endpoint and I think most people would agree that using GET method as the best approach to do it. Lets say I am currently designing a website to sell used car and a search endpoint required to search available cars. How do we handle a search endpoint that allows different query params to be added and how we write the url pattern in django? For example /cars?color=red&year=2010&keyword=audi I guess the url pattern would be re_path(/cars/, views.car) and we get the color, year and keyword using request.GET? What about if we to use the /cars/ endpoint to have more specific search? For example further expand the url to include other parameters /cars/toyota and /cars/california/toyota Does that means I will need to include more url patterns for each param added and possible different view for it? urlpatterns = [ re_path(/cars/?P<brand>[\w]+/, views.car_brand_search), re_path(/cars/?P<state>[\w]+/<?P<brand>[\w]+/, views_car_state_brand_search) ] -
docker-compose: site running but css not applying
I am trying to run my Django app (V 1.8.6) in a docker container using docker-compose. This is my setting.py: MEDIA_ROOT = "/srv/media/" MEDIA_URL = "/media/" STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") This is my docker compose: version: "3" services: # # Nettle API server # nettle: image: mcvitty_img command: python manage.py runserver 0.0.0.0:8000 --settings=sites.production.settings ports: - "80:8000" volumes: bluebell: {} postgres-data: {} rabbitmq-data: {} I am successfully running the collect static in my Dockerfile: RUN python manage.py migrate --settings=sites.production.settings --fake-initial RUN python manage.py sitetree_resync_apps --settings=sites.production.settings RUN python manage.py collectstatic --settings=sites.production.settings --noinput But sadly this is the result: This are the logs I get: nettle_1 | [29/Sep/2020 15:08:19] "GET /static/css/all.min.css HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/widget.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/js/all.min.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/autocomplete.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/style.css HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/remote.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/text_widget.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/autocomplete.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/addanother.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/widget.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET …