Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3: Unable to generate dynamic object view
I have successfully created the expected structure for my model and in the error variables I can see that the DB object was returned but I am not able to resolve the page. I am getting error " TypeError at /ticket-edit/2 - init() got an unexpected keyword argument 'instance'" - am I referencing the object incorrectly? Is there an approach allowing appTicketID=appTicketID (I use aTicketID instead but the DB field is appTicketID)? In the error the local var shows that the expected ticket was retrieved: Variable: Value aTicketID: '2' context: {} obj: <Ticket: 2 2021-10-06 Ticket Title Ticket Desc> request <WSGIRequest: GET '/ticket-edit/2'> Urls.py (I use URL instead of path to generate the ID link) urlpatterns = [ url(r'^ticket-edit/(?P<aTicketID>\d+)', views.ticket_edit, name='ticket-edit') ] Models.py class Ticket(models.Model): #---Base Meta----------------------------------------- appTicketID = models.AutoField(primary_key=True) date_submitted = models.DateTimeField( max_length=20, auto_now_add=True) issue_title = models.CharField(max_length=90) issue_description = models.CharField(max_length=1000) def __str__(self): return (f"{self.appTicketID} " f"{self.date_submitted} " f"{self.issue_title} " f"{self.issue_description} " def get_absolute_url(self): return reverse_lazy('ticket-edit', kwargs={'aTicketID': self.appTicketID} Views.py @login_required def ticket_edit(request, aTicketID): context = {} obj=Ticket.objects.get(appTicketID=aTicketID) updateform=TicketForm(instance=obj) if aTicketID == None: aTicketID = 1 aticket = Ticket.objects.filter(appTicketID=aTicketID) print('\n-----------------------------------------------------------------') print('TicketFiltered: ', aticket) print('-----------------------------------------------------------------\n') context = { "has_error": False, "updateform": updateform, "aticket": aticket } return render(request,'appname/ticket-edit.html', context) -
Django custom model - field username gets removed
Hi I am writing a custom user model on django and i have username field along with email field when i set USERNAME_FIELD = 'username' i get this error raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: User has no field named 'username' when i checked the migrations for the model i find that the username field does not exist among the model fields when i change the field name to something other than username it works here is my model: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.db.models.enums import Choices from django.utils.translation import gettext_lazy as _ class User(AbstractBaseUser): class Role(models.TextChoices): User = 'USER', _('User') Admin = 'ADMIN', _('Admin') Stuff = 'STUFF', _('Stuff') username = models.CharField(max_length=64, unique=True) email = models.EmailField(max_length=256, unique= True, verbose_name="Email") full_name = models.CharField(max_length=256, verbose_name= "Full Name", null=True, blank=True) active = models.BooleanField(default=True, verbose_name= "Active") role = models.CharField(max_length=10, choices = Role.choices, default = Role.User, verbose_name= "Role") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'username' REQUIRED_FIELD = ['username', 'email','password'] def __str__(self): return self.username @property def role(self): return self.role @property def admin(self): return (self.role == self.Role.Admin) @property def stuff(self): return (self.role == self.Role.Stuff) @property def username(self): return self.username -
Django warnings "Not found XXXX" when re-rendering html pages
I collect html from search engine result pages (baidu, sogou, Google, Bing) and use Django to re-render them. It is successful when rendering pages from Baidu or Sogou, but for pages from Google or Bing, there are lots of warnings about "not found XXX". For example, in rendering Bing pages, some warnings: [21/Oct/2021 22:15:44] "GET /sa/simg/Roboto_Regular.woff2 HTTP/1.1" 404 2484 Not Found: /s/ac/25308934/MsnJVData/HoverTranslationV2.css [21/Oct/2021 22:15:44] Not Found: /th "GET /th?id=OVP.amkWCd5lEnKAiv3c6hEoiQEsCo&w=197&h=110&c=7&rs=1&qlt=90&o=6&pid=1.7 HTTP/1.1" 404 2508 Not Found: /th [21/Oct/2021 22:15:44] "GET /rp/4q26YP9oX8_7FiOTRx6BpR60bSg.png HTTP/1.1" 404 2502 Not Found: /fd/ls/lsp.aspx I have more own scripts for these rendered pages such as adding some popup windows. I also tested my script on static pages and it worked. However, when rendering the page, my script didn't work at all, so I wonder if these warnings hold my own scripts. I am looking for a way to ignore or skip these warnings. -
Django how to display model objects in HTML
Hi,I'm new to Django, I have a question here, it would be great if anyone can help. I have a table in Django, there are team and task in the table, I want to display all the tasks under a team in HTML. Now I can only display all task and all team together, I can't display them in a well-classified way. Is it the tamplate tags in the assign.html that I need to make some changes? Please give me some hints, thanks in advance. models.py ''' class Todo(models.Model): status_option = ( ('to_do', 'to_do'), ('in_progress', 'in_progress'), ('done', 'done'), ) status = models.CharField(max_length=20, choices=status_option, default='to_do') # todo_list's content team = models.ForeignKey('Team', on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=20) create_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) project_code = models.CharField(max_length=20) details = models.TextField() def __str__(self): return self.status # return self.team['team'].queryset def update_status(self): if self.status == 'to_do': self.status = 'in_progress' elif self.status == 'in_progress': self.status = 'done' self.save() class Team(models.Model): name = models.CharField(max_length=20) employeeID = models.CharField(max_length=20) email = models.CharField(max_length=50) position = models.CharField(max_length=50) password = models.CharField(max_length=20) projects = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.name ''' views.py ''' def assign(request): team = Team.objects.all() todos = Todo.objects.all().order_by('team') # progresses = team.todo_set.filter(status='in_progress') # dones = … -
js onbeforeunload I want to submit the form after page refresh or close, but failed
I want to submit my form data to database when user refresh or close the window. I tried this, but it didn't work. The p demo1 will change to No when refresh or close. But will change to Yes after refresh or close. But the sumbit part is not trigger. I tried this two method, both of them didn't work document.getElementById("all_questions").submit(); $('#save').click(); It can work if I click the submit button, use Django as framework <script> window.onbeforeunload = function(e){ document.getElementById("demo1").innerHTML="No"; document.getElementById("all_questions").submit(); $('#save').click(); } </script> <form method = "POST" name = "answer_question" id="all_questions"> <p id="demo1">Yes</p> data <div class="save-item1"><button class="save-button" type="submit" id="save" name="Complete">Save</button></div> </form> -
sock failed (111: Connection refused) while connecting to upstream using nginx + uwsgi for django
I'm making a django server. The server uses nginx and uwsgi. The following error occurred in the server performance test. 2021/10/07 02:23:03 [error] 31#31: *9168 connect() to unix:/run/uwsgi/xxxx.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: xx.xxx.xxx.xx, server: xxxx.xxx.com, request: "GET /xxxx HTTP/1.1", upstream: "uwsgi://unix:/run/uwsgi/xxxx.sock:", host: "xxxx.xxx.com" I did some research on this problem and found that I could just adjust the uwsgi socket queue size. (Resource temporarily unavailable using uwsgi + nginx) However, if I add the listen option to the uwsgi configuration, I get the following error: 2021/10/19 06:34:16 [error] 31#31: *69 connect() to unix:/run/uwsgi/xxxx.sock failed (111: Connection refused) while connecting to upstream, client: xx.xxx.xxx.xxx, server: xxxx.xxx.com, request: "GET /health-check HTTP/1.1", upstream: "uwsgi://unix:/run/uwsgi/xxxx.sock:", host: "xx.xxx.xxx.xxx" Tried many ways to solve this problem but it didn't work. I need help. Here is my nginx, uwsgi, etc configurations. uwsgi.ini [uwsgi] project = xxxx project_root = /xxxx wsgi_path = xxxx_server_site chdir = %(project_root) module = %(wsgi_path).wsgi:application master = true processses = 4 listen = 4096 # Problem occurred after adding this option. If removed, it works normally. socket = /run/uwsgi/%(project).sock chmod-socket = 666 vacuum = true logto = /var/log/uwsgi/%(project).log /etc/nginx/conf.d/default.conf server { listen 80; server_name xxxx.xxx.com; location / { … -
Django access file by path in FileSystemStorage
I'm trying to use virus totals api to scan a uploaded file to django website, i'm using the Djangos FileSystemStorage to store the uploaded files. I have set the Media path to /media/ in settings MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and tested adding a url for the uploaded files and it was accessible at /media/{{file name}} eg through www.domain.com/media/{{file name}} urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Although when i attempt to access this file within script to attach to a request i receive the file not found at this directory error. to get the path i am currently using the fs.url(name) command which returns /media/{{file name}} I understand the FileStorageSystems /media/ path does not actually exist within the folder suggested eg app/media is there a alternative command to retrieve the true path? or do i need to use a different storage system for this purpose? thanks Current Script uploaded_file = request.FILES['file'] # getting file from form fs = FileSystemStorage() # initlize FileSystemStorage name = fs.save(uploaded_file.name, uploaded_file) # Save Uploaded file to storage params = dict(apikey=API_KEY) # add api key for request with open(fs.url(name), 'rb') as file: # context manager opening saved file files = dict(file=(fs.url(name), file)) # create dict of … -
Display image from external link in Django Admin Change Form
I am trying to display an image from online source (e.g. facebook) which is not a field in the model in the User Change Form. I can successfully display it in the user list page or in a separate Model page but I want to add this image to the existing user editing page below username and password fields. -
ReactJS: Javascript fetch works on desktop browsers but returns a 403 error which says (authentication credentials not provided) on IOS safari
I'm working on a project using Create-react-app with a backend API written in Django(Python) where I used fetch to make my API calls. API calls run fine on android browsers and on desktop browsers but on IOS Browsers(both safari and chrome) the API returns the 403 error with response (authentication credentials not provided). this issue is a bit more tasking for me as it is quite difficult for me to perform remote debugging for IOS using my windows PC. I was only able to view the error due to JavaScript console using chrome://inspect on IOS and consoling the API response to the Iphone's console I would like some help on this issue. -
I have a huge but not complex sql query that must convert to django orm query
I have to convert the following sql query but i don't know how to convert it to equal query in django orm I would be very happy if you can :))) select dialog_messages.*, sender.first_name as sender_first_name, sender.last_name as sender_last_name, sender.cell_number as sender_cell_number, sender.avatar_full_path as sender_avatar_full_path, receiver.first_name as receiver_first_name, receiver.first_name as receiver_first_name, receiver.last_name as receiver_last_name, receiver.cell_number as receiver_cell_number, receiver.avatar_full_path as receiver_avatar_full_path from dialog_messages`` inner join user sender on ``sender``.``user_id`` = dialog_messages``.``sender_id`` inner join user receiver on receiver``.``user_id`` = ``dialog_messages``.``receiver_id`` where `dialog_id`` = ? order by ``dialog_messages``.``id`` desc -
Deploy django on apache server is not working
I'm trying to setup an apache server running django but I have have some troubles to make it run it well. At this moment it seems to be correctly configures but i can not access now. this is how my apache log file looks apache: [Thu Oct 21 22:29:36.608487 2021] [suexec:notice] [pid 16400] AH01232: suEXEC mechanism enabled (wrapper: /usr/lib/apache2/suexec) [Thu Oct 21 22:29:36.946497 2021] [:notice] [pid 16414] mod_ruid2/0.9.8 enabled [Thu Oct 21 22:29:36.991981 2021] [mpm_prefork:notice] [pid 16414] AH00163: Apache/2.4.29 (Ubuntu) mod_fcgid/2.3.9 OpenSSL/1.1.1 configured -- resuming normal operations [Thu Oct 21 22:29:36.992010 2021] [core:notice] [pid 16414] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 21 22:29:49.610060 2021] [mpm_prefork:notice] [pid 16414] AH00169: caught SIGTERM, shutting down [Thu Oct 21 22:29:49.759118 2021] [suexec:notice] [pid 17390] AH01232: suEXEC mechanism enabled (wrapper: /usr/lib/apache2/suexec) [Thu Oct 21 22:29:49.868100 2021] [:notice] [pid 17393] mod_ruid2/0.9.8 enabled [Thu Oct 21 22:29:49.886537 2021] [mpm_prefork:notice] [pid 17393] AH00163: Apache/2.4.29 (Ubuntu) mod_fcgid/2.3.9 OpenSSL/1.1.1 configured -- resuming normal operations [Thu Oct 21 22:29:49.886565 2021] [core:notice] [pid 17393] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 21 22:29:51.173110 2021] [mpm_prefork:notice] [pid 17393] AH00171: Graceful restart requested, doing restart [Thu Oct 21 22:29:51.355561 2021] [:notice] [pid 17393] mod_ruid2/0.9.8 enabled [Thu Oct 21 22:29:51.355846 2021] [mpm_prefork:notice] [pid 17393] AH00163: Apache/2.4.29 … -
How to show in Django Admin Icons based on model value
I need to show an Icon in Django Admin based on the value. For example: If Model Field weather has value sun then show icon sun (png or webfont) Is this possible? -
Django throws 500 when debug is False in Production
I am unable to understand why Django 3 fails when I run with DEBUG=False. Also there seems to be a problem with urls: www.domain.com/ -> Does not work www.domain.com/en/ -> No problem The logs seem to mention a million problems but I don't understand what the initial problem is, so I am looking for help: Exception while resolving variable 'self' in template '404.html'. Traceback (most recent call last): File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 167, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 290, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 585, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) '^django-admin/'>], [<URLResolver <module 'wagtail.admin.urls' from '/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/wagtail/admin/urls/__init__.py'> (None:None) '^admin/'>], [<URLResolver <module 'wagtail.documents.urls' from '/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/wagtail/documents/urls.py'> (None:None) '^documents/'>], [<URLPattern '^i18n/$' [name='set_language']>], [<URLPattern '^sitemap\.xml$'>], [<URLResolver <URLResolver list> (None:None) 'bg/'>]], 'path': ''} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'self' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 835, in _resolve_lookup if isinstance(current, BaseContext) and getattr(type(current), bit): … -
django: request.POST.get() return NoneType
I am work from data acquired from an html form. I am currently failing to capture the data on the server side. Every input returns "NoneType" on the server. I feel like I tried everything that I could find around here, notably changing id for name in the html form, nothing works. here is what I got so far: views.py: def quadriatransport_simulationView(request): return render(request, "simulation.html") @csrf_exempt def compute(request): destination = request.POST.get("destination") nombre_de_palettes = request.POST.get("nombre_de_palettes") poids_par_palette = request.POST.get("poids_par_palette") Optimisation_prix = request.POST.get("Optimisation_prix") Optimisation_delai = request.POST.get("Optimisation_delai") result = {"destination":destination} print(result) return JsonResponse({"operation_result": result}) results returns a dictionnary where destination is None now here is what I have been able to do on the webpage <form method="POST"> {% csrf_token %} <label><h3>Input variables to calculate EOQ:</h3></label> <br> <br> <span>Destination (departement) <input type="text" id="destination"> <br> <br> <span>Nombre de palettes <input type="text" id="nombre_de_palettes"> <br> <br> <span>Poids par palette <input type="text" id="poids_par_palette"> <br> <br> <span>Optimiser prix <input type="checkbox" id="Optimisation_prix"> <br> <br> <span>Optimiser délai de livraion <input type="checkbox" id="Optimisation_delai"> <br> <input id="ajax-call" type="submit" value="Simuler"> </form> <p id="ajax"></p> and here is my js script inside of the webpage <script> document.querySelector("#ajax-call").addEventListener("click", event => { event.preventDefault(); let formData = new FormData(); formData.append('estination', document.querySelector("#destination").value); formData.append('nombre_de_palettes', document.querySelector("#nombre_de_palettes").value); formData.append('poids_par_palette', document.querySelector("#poids_par_palette").value); formData.append('Optimisation_prix', document.querySelector("#Optimisation_prix").value); formData.append('Optimisation_delai', document.querySelector("#Optimisation_delai").value); let … -
Using Outlook SMTP server to send email through a contact form but unable to send as I need the server to be able to accept multiple "From" addresses
Currently using Django as the chosen framework for my project and I have implemented a contact form and my main goal is for users to complete the contact form and the admin of the site (me) get an email, which shows me the details of their enquiry. I am trying to use the Outlook SMTP server and these are my current settings in settings.py: EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '<my_emailAddress>' EMAIL_HOST_PASSWORD = os.environ.get('OUTLOOK_PASSWORD') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = '<my_emailAddress>' However, whenever I complete the form and send the request to the server I am receiving the following error code: (554, b'5.2.252 SendAsDenied; <my_emailAddress> not allowed to send as <inputtedForm_emailAddress>; STOREDRV.Submission.Exception: SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message. I am looking for some help surround this issue - it would be greatly appreciated. Thanks in advance, Rhys -
You may install a binary package by installing 'psycopg2-binary' from PyPI [WINDOWS]
Hi guys I'm getting this error and I don't know how to fix this the command that I run in my console is the following: pip install -r ..\requirements\local.txt It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try again. For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 I don't know how to fix this I really need help -
Django Python - import error: No module named 'views'
I am trying to run a webserver in Django using this tutorial series: https://www.youtube.com/watch?v=Rpi0Ne1nMdk&list=PLPSM8rIid1a3TkwEmHyDALNuHhqiUiU5A I get an error when I try and import the script 'landing.views' inside urls.py, here is the error in it's entirety: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\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 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'views' Here is the code that generates the error seen above in urls.py: from django.urls import path from landing.views import Index urlpatterns = [ path('', Index.as_view(), name='index'), ] I have also tried looking at posts that other users have … -
Incorrect response from .get_or_create function in Django
I have been trying to understand why the .get_or_create function I'm using isn't working. It's supposed to find the object in the DB with matching parameters and create a new one if none are found. When running this, it always says that there are not matching objects and the tuple return True every time hence always creating a new object (a duplicate). This causes the Except statement to run every time as well. Here is my function: for desktop in desktops: try: clean_location = serialized_location_information(desktop) clean_machine = serialize_machine_information(desktop) location_name, location_created = Location.objects.get_or_create( latitude=clean_location["latitude"], longitude=clean_location["longitude"], provider=clean_machine["provider"], defaults={ "country": clean_location["country"], "state": clean_location["state"], "city": clean_location["city"], "street_address": clean_location["street_address"], "postal_code": clean_location["postal_code"], "name": clean_location["name"], "status": clean_location["status"], } ) if l_created: logger.info(f"New Location was created successfully") except Exception as ex: logger.error(f"Could not get or create location: {ex}") location = None pass Here is my model: class Location(models.Model): class Meta: unique_together = ['latitude','longitude','provider'] latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) country = models.CharField(max_length=100, blank=True) state = models.CharField(max_length=25, blank=True) city = models.CharField(max_length=250, blank=True) street_address = models.CharField(max_length=250, blank=True) postal_code = models.CharField(max_length=100, blank=True) name = models.TextField(blank=True) status = models.PositiveSmallIntegerField(default=10, choices=LocationStatus.CHOICES) provider = models.ForeignKey(Provider, on_delete=models.CASCADE, default= '') def __str__(self): return f"{self.name}" -
One dictionary key is overriding the others. Dictionary is being accessed at definition
I am experiencing an odd issue where 21 of the dictionary keys work correctly. However, when this specific 22nd one is added, things stop working correctly. The dictionary is accessed when being defined as well as being immediately accessed always with the 22nd key (whether it is correct or not). The dictionary is inside of a Django function view that aims to edit Product forms and save them to a quotation. Below is the template and url as well as function view. {% url 'quote:edit_line_item' pk=quote.pk product_name=item.product_name line_item=item.pk%} re_path(r'quote/(?P<pk>\d+)/edit-line-item/(?P<product_name>.+)/(?P<line_item>\d+)/$', views.add_to_quote, name = 'edit_line_item') def add_to_quote(request,*args,**kwargs): pk = kwargs['pk'] if kwargs.get('line_item') == None: product_template_form = 'quote/product_template_form.html' form_dict = { 'FilterProduct':FilterProductForm(request.POST,initial={'quote':pk},user=request.user), 'Product1': Product1Form(request.POST,initial={'quote':pk}, 'Product2': Product2Form(request.POST,initial={'quote':pk}, ... 'Product21':Product21Form(request.POST,initial={'quote':pk}, } form = form_dict[request.POST['product_name']] else: obj = get_object_or_404(model_dict[kwargs['product_name']], pk=kwargs['line_item']) print(f"object {obj}") print(kwargs) product_template_form = 'quote/edit_product_form.html' print("here") form_dict = { "FilterProduct": FilterProductForm(request.POST or None, initial={'quote':kwargs['pk']}, instance = obj,user=request.user), # "FilterProduct": print("why am I printing?"), 'Product1': Product1Form(request.POST or None, initial={'quote':kwargs['pk']}, instance = obj), 'Product2': Product2Form(request.POST or None, initial={'quote':kwargs['pk']}, instance = obj), ... 'Product21': Product21Form(request.POST or None, initial={'quote':kwargs['pk']}, instance = obj), } print("there") print(kwargs.get('product_name')) form = form_dict[str(kwargs.get('product_name'))] ...continues from here with logic return render(request, product_template_form, {'form':form}) Since the line_item kwarg is provided the else statement of the function … -
Network request failed error in React native using django api
i am trying to get the simple data from the api that i created in django tried many instructions but could not resolve this error with api Here is my react native code export default function App() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const handleSubmit = () => { ##tried:127.0.0.1 also computer ip then localhost## return fetch("http://localhost:8000/demo/customer/") .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); return responseJson; }) .catch((error) => { console.error(error); }); }; return ( <View style={styles.container}> <View style={styles.login}> <Text>Login</Text> <TextInput placeholder="Email" keyboardType="email-address" style={styles.inp} onChangeText={(text) => setEmail(text)} /> <TextInput placeholder="password" style={styles.inp} onChangeText={(text) => setPassword(text)} /> <Button title="login" color="orange" onPress={handleSubmit} /> </View> <View> <Text> {email}-{password} </Text> </View> </View> ); } this is the error that i get most of my time and sometimes it gives null when using apisauce error Network request failed at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue django setting INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djoser', 'corsheaders', 'demo' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST … -
Django3 Nginx Gunicorn Supervisor not logging error
Im trying to catch/ log django errors (500) in my prod environment. However all the log files doesn't contain any traceback. To test if it works I have a view in django with: raise Exception("test exception to test the logging") It doesn't matter how I change the configuration - it doesn't log it. Current config: Django (SETTINGS.py) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs/django.log'), }, 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'), }, }, } prod_gunicorn.bash #!/bin/bash NAME="RPG-DJANGO" DJANGODIR=/home/my_user/rpg-django SOCKFILE=/home/my_user/prod_env/run/gunicorn.sock USER=my_user GROUP=sudo NUM_WORKERS=4 DJANGO_SETTINGS_MODULE=rpg.settings DJANGO_WSGI_MODULE=rpg.wsgi cd $DJANGODIR source /home/my_user/prod_env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --access-logfile /home/my_user/rpg-django/logs/gun_access.log \ --error-logfile /home/my_user/rpg-django/logs/gun_error.log \ --capture-output \ --log-level=debug /etc/supervisor/conf.d/rpg-django.conf [program:RPG-DJANGO] command=/home/my_user/rpg-django/prod_gunicorn.bash user=root stdout_logfile=/home/my_user/rpg-django/logs/prod_gunicorn.log stderr_logfile =/home/my_user/rpg-django/logs/prod_gunicorn.log redirect_stderr=true autostart=true autorestart=true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 /etc/nginx/sites-available/rpg-django.conf server { server_name rpg.skin-society.com; access_log /home/my_user/rpg-django/logs/nginx-access.log; error_log /home/my_user/rpg-django/logs/nginx-error.log; location = /favicon.ico { access_log off; log_not_found off; } location ^~ /static { root /home/my_user/rpg-django; } location / { include proxy_params; proxy_pass http://unix:/home/my_user/prod_env/run/gunicorn.sock; } } -
Get the value of an IntegerChoices value in Django?
Suppose I have the following Django (3.2) code: class AType(models.IntegerChoices): ZERO = 0, 'Zero' ONE = 1, 'One' TWO = 2, 'Two' class A(models.Model): a_type = models.IntegerField(choices=AType.choices) Also, that I have a Django template with a variable a: {{a.a_type}} is a number. How do I get "Zero" (the string associated with a_type)? -
How to show data from views on chartjs in django?
I am making an app on Django at the moment and I don't know how to get the data from views to the chart properly. Here's my code for views: def data(request): nysestuff = nyse.objects.all() riskappstuff = riskapp.objects.all() feargreedstuff = feargreed.objects.all() putcallstuff = putcall.objects.all() feargreednm = [float(feargreedstuff[i].Fear_Greed/100) for i in range(len(feargreedstuff))] outputdata = [(float(nysestuff[i].NYSE_Up_Vol) + feargreednm[i] + float(putcallstuff[i].Put_Call) + float(riskappstuff[i].Risk_App))/4 for i in range(len(feargreedstuff))] yesno = [outputdata[i] > 50 for i in range(len(outputdata))] labels = [str(nysestuff[i].Daily_NYSE) for i in range(len(nysestuff))] context= { 'outputdata': outputdata, 'labels': labels, 'yesno': yesno } return render(request, 'newapp/index.html', context=context) I want to get outputdata and labels into the chart. Here's my code for the html: <!DOCTYPE html> <h1>Trial page</h1> <body>{{labels}}</body> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!--Chart js--> <title>Sample Graph</title> <script src="https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js"></script> </head> <canvas id="myChart" width="200" height="100"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: {{labels}}, datasets: [{ label: '# of Votes', data: {{outputdata}}, // backgroundColor: [ // 'rgba(255, 99, 132, 0.2)', // 'rgba(54, 162, 235, 0.2)', // 'rgba(255, 206, 86, 0.2)', // 'rgba(75, 192, 192, 0.2)', // 'rgba(153, 102, 255, 0.2)', // 'rgba(255, 159, 64, 0.2)' // ], … -
Cleaned_data coming as empty data in django form?
I have a form field and it is a form.JsonField(). When I am submitting data,and logging the data received in the cleaned_data, it always outputs the empty data. Reason being, when I log the request.POST, I can see the incoming data is coming as list e.g <Querydict:{"name":["test",'']. When I pass request.POST to my form, I always get self.cleaned_data.get("name") as empty. It always gives me the last item from the list value. Possible solution in my mind, is to manipulate the request.POST data before sending to form and then everything will work fine. e.g update_request = request.POST.copy() updated_request['name'] = updated_request.getlist('name')[0] Now, I can pass this to my form e.g form = MyForm(updated_request,instance=self.get_sample()) Point is this seems more like a hack compared to a clean solution. Is there a more efficient way to do this instead of hacking all this in the views. -
How can I solve this DJANGO_SETTINGS_MODULE or call settings.configure() problem?
I'm currently learning to use Django with a Udemy course that is pretty outdated but since it was the best rated I thought I'd give it a try. After covered how to set the models.py file they showed how to use Faker to populate the admin section with fake data. The problem arises when trying to run this populate file, this is what shows up: 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. This is my populate file from faker import Faker from first_app.models import AccessRecord, Webpage, Topic import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') django.setup() # FAKE POP SCRIPT fakegen = Faker() topics = ['Search', 'Social', 'Market', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # get the topic for the entry top = add_topic() # create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # create the new webpage entry webpg = Webpage.objects.get_or_create( topic=top, url=fake_url, name=fake_name)[0] # create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create( name=webpg, date=fake_date)[0] if __name__ == '__main__': print('populating script..') populate(20) …