Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Im having trouble uploading files from computer to trinymce text editor
Okay. I have a tiynmce text editor. I have the "upload" button displaying to insert pictures. I dont know how to make that work though. It goes to my computer and everything, but how do i actually make the function work in django? I been searching for about four hours and i cant find nothing dealing with djano. -
HTTP POST to bytebin.lucko.me responds differently to python's requests than jquery's ajax. Why?
python code: def callback(data): print(data) requests.post( 'https://bytebin.lucko.me/post', data='test', headers={'Content-type': 'application/json; charset=utf-8'}, hooks={'response': callback}) data printed is < Response: 201 >, a response object, when doing POST request with python's requests javascript code: function callback(data){ console.log(data) } $.ajax("https://bytebin.lucko.me/post", { contentType: "application/json; charset=utf-8", dataType: "json", data: 'test', method: "POST", success: callback, error: () => { } }); data printed is {'key': 'random alphanumeric'}, the desired output Why is the output different? I want the data with the key attribute when making a POST request in python Please help, thanks in advance. -
How to run a python script with data from a form in django?
I'm trying to run a python script in a Django proyect. I have a form where the user inputs some data and I have to run a function with said data, and show it to the user. What would be the best way of doing it?, hopefully keeping the python code separated from the html template. -
Django [Errno 2] No such file or directory while writting log file
I have a django view function to dump mysql database on a remote ubuntu server, and save the commands into a log file. But while running, it keeps telling me there is something wrong with the files. Here I present some code, and could someone help me? Django 2.1.7, python3.6, Ubuntu16.04LTS class Step1aView(IndexView): def MySQLDumpBackup(self, dbhost, dbuser, dbpwd, dbname): # backup mysql database to sql file backupDir = r"/opt/workspace" dbCharset = 'utf8' backupDate = time.strftime(r"%Y-%m-%d_%H:%M:%S") dumppath = r"/usr/bin/mysqldump" # position of mysqldump on the server # commands to execute self.command = dumppath + " -h %s -u %s -p%s %s --default_character-set=%s > %s/%s_%s.sql" %(dbhost,dbuser,dbpwd,dbname,dbCharset,backupDir,backupDate,dbname) # if the log file does not exists, create it as DjangoDbLog.txt logName = backupDir + '/DjangoDbLog.txt' # logName = 'DjangoDbLog.txt' if os.path.exists(logName) == False: logFile = open(logName, 'w') logFile.close() else: pass logFile = open(logName, 'a') logFile.write('\n' + self.command + 'Time:' + backupDate) logFile.close() # execute the command os.system(self.command) filenames = backupDate+'_'+dbname+'.sql' return filenames def post(self, request): if request.method == 'POST': dbhost = request.POST.get('Ori_ip') dbport = int(request.POST.get('Ori_port')) dbname = request.POST.get('Ori_db') dbuser = request.POST.get('Ori_name') dbpwd = request.POST.get('Ori_passwd') dbchar = request.POST.get('Ori_char') dbhost = str(dbhost) dbname = str(dbname) dbuser = str(dbuser) dbpwd = str(dbpwd) dbchar = str(dbchar) try: filenames=self.MySQLDumpBackup(dbhost, … -
How to load data from JSON files into MySQL instance with the Django ORM?
I'm using Django to build out an ETL engine and I've built out some methods to extract and transform data from some API endpoints that is being saved locally to my machine in .JSON format. File formats nomenclature is as follows: repos_transformed_2019-05-06-13-23-59.json and repos_extraction_2019-05-06-13-23-59.json in case that matters for the Django ORM's lookup. I've got a MySQL instance running that has schema that matches up exactly with the keys that are defined in my .JSON file but the Django ORM is not loading the data into my database from the loaddata command. I have to manually create an instance of the model and hardcode it all in manually. Obviously this would not work in a production environment and I'm trying to find a way to load this data in in .json file "batches" without having to manually crank away at this. After reading the docs (specifically loaddata) I am trying to load it into my database like so: django-admin loaddata repos_transformed_2019-05-06-13-23-59.json --database invisible-hand and I get an error for the settings for some reason: django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Here is a … -
Django: print the last object of model for every (FK)
I have two models: class Mantipo(models.Model): tipo = models.CharField(max_length=255) ... class BillInitial(models.Model): tipo = models.ForeignKey(Mantipo, null=True, blank=True) nombre = models.CharField(max_length=255) ... Let's say I have the following objects of "BillInitial" model: | id | tipo (FK) | nombre | | 1 | uno | X | | 2 | dos | y | | 3 | cinco | x | | 4 | cinco | x | | 5 | dos | z | | 6 | uno | X | I want output the last objects of nombre (X) like: | id | tipo (FK) | nombre | | 4 | cinco | x | | 6 | uno | X | -
i want to unzip a file zip in view and save all files that they are in a zip file upload
i have have a view how upload files like png pdf docs i want to extract a zip file and upload all my files how's in the zip file COM=zipfile if formData["category"] == Advertisement.MEDIA[0]: if file_type == 'COM': with ZipFile(files_uploaded['file'], 'r') as z: for f in z.namelist(): names = z.namelist() for i in range(len(names)): bs = False else: ad.file = img_upload_to_file( company, files_uploaded['file'], formData["file_generated"], file_type, log) ad.duration = get_duration_according_by_file_type( formData, ad.file) ad.save() -
How can I access to MTM fields attribute in my template
I have 3 models: User, Server and Protocol. In my template, I want to display only the list of servers that are accessible by a particular protocol (SSH for example) and user. models.py: class Protocol(models.Model): name = models.CharField( verbose_name = ('Protocol name'), max_length = 50, unique = True, default = "Protocol", blank = False ) port = models.IntegerField( verbose_name = ('Port Number'), default = 22, blank = False, validators=[MinValueValidator(0), MaxValueValidator(65535)] ) def __str__(self): return self.name class Server(models.Model): name = models.CharField( unique = True, verbose_name = ('Server name'), max_length = 50, default = "Server name", blank = False ) hostname = models.CharField( verbose_name = ('Host name'), max_length = 40, default = "hostname", blank = False ) ip = models.GenericIPAddressField( verbose_name = ('IP address'), protocol = 'ipv4', blank=False ) user = models.ManyToManyField(User, related_name='User') protocol = models.ManyToManyField(Protocol, related_name='Protocol') def __str__(self): return self.name view.py: class ServerListView(LoginRequiredMixin,ListView): queryset = Server.objects.all() context_object_name = 'servers' template file: {%for server in servers%} <a><div> <h4>{{server.name}}</h4> <h6>Hostname: {{server.hostname}}</h6> <h6>IP Address: {{server.ip}}</h6> </div> </a> {%endfor%} Everything works fine. However, I cannot display the protocol associated to each server. I tried these lines but the result is None and it displays nothing! {% for protocol in server.Protocol.all %} <h1>protocol: {{ protocol }}</h1> … -
How can I link 2 django templates with one button?
I need to link to link two django templates with a button on my index page,what would be the best way of doing it? I need to link bis.html. This is how I have things set up. urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', HomeView.as_view()), url(r'^$/bis', BisView.as_view()), ] views.py class HomeView(TemplateView): template_name = 'index.html' class BisView(TemplateView): template_name = 'bis.html' index.html ... <li><a href="/bis">Bisection</a></li> ... -
Heroku Django Application Error: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I have just deployed my Django and spaCy app to Heroku but it is not running. I checked the logs and found the error: gunicorn.errors.HaltServer: Here is my Procfile: web: gunicorn dj_patt_check.wsgi:application Here is my wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dj_patt_check.settings') application = get_wsgi_application() How can I solve the issue? My gunicorn version is 19.9.0. Detailed log is here: 2019-05-07T22:22:10.306575+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 245, in handle_chld 2019-05-07T22:22:10.306736+00:00 app[web.1]: self.reap_workers() 2019-05-07T22:22:10.306739+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2019-05-07T22:22:10.306971+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2019-05-07T22:22:10.306996+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2019-05-07T22:22:10.391600+00:00 heroku[web.1]: State changed from up to crashed 2019-05-07T22:22:10.370261+00:00 heroku[web.1]: Process exited with status 1 2019-05-07T22:22:11.000000+00:00 app[api]: Build succeeded -
I am trying to allow users to uplaod pictures to the tinymce text editor and insert in the users post
I am trying to allow users to upload images into their tinymce text area as they are writing their post. I currently have the tinymce text widget on the website, but when you click images, you have to type in a URL.. I want them to be able to pick from their computer files. -
Django query works in shell, but jinja wont recognize in template
Right now I can run a query in the python shell and have it return True, but when trying to replicate in my html jinja template, I can't get it return the same True result. I have a query that puts a Post.object.get(id=1) as a variable. P1=Post.objects.get(id=1) then ran: P1.liked_by.all() which does return results: <QuerySet [<User: User object(10)>, <User: User object (12), <User: User object (13)>]> then I put a variable in for a User found in that query: JV= User.objects.get(id=10) This user id is found in the P1.liked_by.all() query, so now when I test to see if it is found. JV in P1.liked_by.all() True Now when I try to access this in my html jinja template. I can not get it to check against it and return true. Even though I can print the values on the page. Here is my Views.py: def topic(request,topic_id): if not 'u_id' in request.session: return redirect('/') print(request.session) context={ "topic":Topic.objects.get(id=topic_id), "user":User.objects.get(id=request.session["u_id"]), "posts":Post.objects.filter(topic=topic_id), } return render(request, 'topic.html', context) Here is my HTML: {% for post in posts %} <div class="cast-content"> <h3>Casting submit by <u>{{post.user.user_name}}!</u></h3> <p>number of likes:{{post.liked_by.count}}</p> <p>post id:{{post.id}}</p> <p>user_id in session= {{user.id}}</p> <p>liked by:{{post.liked_by.all}}</p> <img src="{{post.image.url}}" class="post-pix" alt="..."> <br> <p>post liked_by values: {{post.liked_by.values}}</p> {% if … -
Receives DeferredAttribute instead of value during calling method
I'm trying to call the method, the one below: def get_tenant_model(): return get_model(settings.TENANT_MODEL) Tenant model in settings: TENANT_MODEL = "app.Client" And in this place: a = get_tenant_model() print(a.name) I getting: <django.db.models.query_utils.DeferredAttribute object at 0x7f0cf7d746a0> Why I can't get name of Client? -
Password error when customizing Django authentication
I'm trying to customize the authentication that comes by default in Django with a table of Mysql already made (collaborators). When I want to register a user (with the command python manage.py createsuperuser) I get the following error: django.db.utils.OperationalError: (1054, "Unknown column 'collaborators.password' in 'field list'"). That error mentions that the password column does not exist, and indeed I do not have it in the table, is there any way to indicate that the password is obtained from a column called "general_password"? I attach my code. models.py class MyUserManager(BaseUserManager): use_in_migrations = True def create_superuser(self, no_colaborador, nombres_colaborador, apellido_paterno_colaborador, apellido_materno_colaborador, id_plantel, id_area_colaborador, no_empleado_sup, contrasena_general, empleado_interno): user = self.model(no_colaborador = no_colaborador, nombres_colaborador = nombres_colaborador, apellido_paterno_colaborador = apellido_paterno_colaborador, apellido_materno_colaborador = apellido_materno_colaborador, id_plantel = id_plantel, id_area_colaborador = id_area_colaborador, no_empleado_sup = no_empleado_sup, contrasena_general = contrasena_general, empleado_interno = empleado_interno,) user.set_password(contrasena_general) user.save(using=self._db) return user class Colaboradores(AbstractBaseUser): no_colaborador = models.IntegerField(primary_key=True) nombres_colaborador = models.CharField(max_length=150) apellido_paterno_colaborador = models.CharField(max_length=150) apellido_materno_colaborador = models.CharField(max_length=150) id_plantel = models.IntegerField() id_area_colaborador = models.IntegerField() id_centro_costos = models.IntegerField() no_empleado_sup = models.IntegerField() contrasena_general = models.CharField(max_length=100) empleado_interno = models.CharField(max_length=10) objects = MyUserManager() USERNAME_FIELD = "no_colaborador" class Meta: managed = False db_table = 'colaboradores' app_label = "journal" def __str__ (self): return self.email def def_full_name (self): return self.nombres_colaborador def has_perm(self, perm, obj=None): return … -
Connection between Django Views and Javascript function
I'm currently setting up my Django project which is a search engine and I've been trying to estabish a connection between a custom Django View and a Javascript function but I kept having issues, so I decided to restart this from the beginning and hopefully get someone's help. I have this Javascript code const data = [] // Not sure how to get the data from the backend?? let index = 0; let results = []; const randomSearchMatchPercentages = ( array ) => { for ( const element of array ) { // define a maximum and a minimum range const maximum = index <= 100 ? 100 - index : 0; const minimum = maximum > 0 ? maximum - 5 : 0; element.match = Math.round( Math.random() * ( maximum - minimum ) + minimum ) + "%"; results.push( element ); // decrease the maximum and minimum for the next iteration index += 5; } console.log( results ); } randomSearchMatchPercentages( data ); That I need to connect with a custom View like this: def MatchingScore(request): return JsonResponse(output) I have established a connection and get the data from the backend for my autocomplete with this View: def autocomplete(request): sqs = … -
AssertionError: 301 != 200
I'm using SimpleTestCase to test my website in Django but only pass 2 of 4 I tried using this but still did not work This is my tests.py from django.test import SimpleTestCase class PageTest(SimpleTestCase): def test_portfolio_page_status_code(self): response = self.client.get("/portfolio") self.assertEquals(response.status_code, 200) def test_blog_page_status_code(self): response = self.client.get("/blog") self.assertEqual(response.status_code, 200) def test_home_page_status_code(self): response = self.client.get("") self.assertEquals(response.status_code, 200) def test_quotes_page_status_code(self): response = self.client.get("/quotes/") self.assertEquals(response.status_code, 200) The traceback is: ====================================================================== FAIL: test_blog_page_status_code (personal_portfolio.tests.PageTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/user/dir/personal_portfolio/tests.py", line 11, in test_blog_page_status_code self.assertEqual(response.status_code, 200) AssertionError: 301 != 200 ====================================================================== FAIL: test_portfolio_page_status_code (personal_portfolio.tests.PageTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/user/dir/personal_portfolio/tests.py", line 7, in test_portfolio_page_status_code self.assertEquals(response.status_code, 200) AssertionError: 301 != 200 Where do you think I got this wrong? -
Django: Adding an if statement to check if file as been uploaded in a contact form
I have a website contact form that involves attaching several optional documents. Once the form has been filled out, an email is sent to an employee which includes form inputs along with these documents as email attachments. I am looking to add an if statement before the msg.attach_file command in my views.py file that prevents attaching the file if a document was never uploaded. Something along the lines of... if upload_file_type2 blank = false msg.attach_file('uploads/filetype2/') I know that above line is incorrect, but I am unsure of how to write an if-statement that says the form entry was blank. Below are relevant files. Models.py upload_file_type1 = models.FileField(upload_to=file_path1, blank=True) upload_file_type2 = models.FileField(upload_to=file_path2, blank=True) Views.py def quote_req(request): submitted = False if request.method == 'POST': form = QuoteForm(request.POST, request.FILES) upload_file_type1 = request.FILES['upload_file_type1'] upload_file_type2 = request.FILES['upload_file_type2'] if form.is_valid(): form.save() # assert false msg = EmailMessage('Contact Form', description, settings.EMAIL_HOST_USER, ['sample@mail.com']) msg.attach_file('file_path1') #THIS IS WHERE PROPOSED IF STATEMENT WOULD GO msg.attach_file('file_path2') msg.send() return HttpResponseRedirect('/quote/?submitted=True') else: form = QuoteForm() if 'submitted' in request.GET: submitted = True -
Django Form WizardView choosing form through radio button
I'm using Django 2.17 and trying to implement a HTML Form that can change due a radio button selection. According with the choice a django form must be loaded. I've read about Django Formtools (https://swapps.com/blog/how-to-do-a-wizard-form/), it's something close, except the conditional clause that I want. It'll be 3 options, so 3 different Django Forms to my Views. The flux will be something like: Radio button choosing one of 3 options. HTML Table to one of the 3 Forms. Passing the data of the Form to another page. I've also read these: Django form wizard dispatcher -> This one seems close to what I want, but I'm confused if the first part of the code is in url.py or in view.py, as the first tutorial recommends. https://django-formtools.readthedocs.io/en/stable/wizard.html#wizard-template-for-each-form Using these 3 links I've written a scrap of a code. It consists in a Form with a radio button that will pass through conditions to set wich of the 3 Forms will be used. But it's getting me an error just when I try to load my IndexView. The code are the following and the error is in the end: view.py: import json from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpResponseRedirect, HttpResponse from … -
Problem understanding oAuth integration with REST API
I'm a frontend developer having a hard to understand oAuth. I've followed the documentation of django-rest-framework-social-oauth2 and the API works as the docs suggest. But I can't understand the idea behind it. I have a React-based website (client) and a Django-based REST API (server), running separately. According to docs, the client has to make a POST call to the server to get the token in order to use it to get access to other endpoints. curl -X POST -d “client_id=<client_id>&client_secret=<client_secret>&grant_type=password&username=<user_name>&password=<password>” http://localhost:8000/auth/token but I have to pass client_id and client_secret in that API call. Am I suppose to put client_id and client_secret in the client? If yes, then Why do we have a secret in the first place? If not, then why the docs say so? -
How to update user models without a form?
I want to update user model in a views.py. Is there a way to do that? What I want to do is minus user point in views.py and update into models without a form. but it gave me " 'int' object has no attribute 'save'" views.py def buy_item(request, item_name): item = ShopItem.objects.get(item_name=item_name) price = item.item_price user = request.user user_point = user.point if user_point >= price: user_point = user_point - price point_left = user_point point_left.save() msg = messages.success(request, 'You bought item!') return redirect('/shop', msg) else: msg = messages.success(request, 'You do not have enough point') context = ({ 'point': user_point, 'item': item, 'form': form }) return render(request, 'item.html', context) item models.py class ShopItem(models.Model): item_name = models.CharField(max_length=16) item_image = models.ImageField(upload_to='media_items') item_description = models.CharField(max_length=255) item_command = models.CharField(max_length=255) item_price = models.IntegerField(default=0) def __str__(self): return self.item_name def snippet(self): return self.item_description[:45] user models.py class UserProfile(AbstractUser): username = models.CharField(max_length=16, unique=True) email = models.EmailField(default='', unique=True) phone = models.CharField(max_length=10) point = models.IntegerField(default=0) password1 = models.CharField(max_length=255) password2 = models.CharField(max_length=255) USERNAME_FIELD = 'username' What I want is to save the point after changed. What should I do? Please help! I'm really new to this. Sorry for my English. -
error ImproperlyConfigured django-db-multitenant
i'm try convert my app to multitenant i have this code: settings.py MIDDLEWARE_CLASSES = [ .... 'db_multitenant.middleware.MultiTenantMiddleware', ] DATABASES = { 'default':{ #'ENGINE': 'django.db.backends.mysql', 'ENGINE': 'db_multitenant.db.backends.mysql', 'NAME': 'rgmanagement', .... MULTITENANT_MAPPER_CLASS = 'seguridad.mapper.SimpleTenantMapper' from db_multitenant.utils import update_from_env update_from_env(database_settings=DATABASES['default'], cache_settings='') this is my mapper.py: from db_multitenant import mapper class SimpleTenantMapper(mapper.TenantMapper): def get_tenant_name(self, request): """Toma la primera parte del host como el nombre de tenant""" hostname = request.get_host().split(':')[0].lower() return hostname.split('.')[0] def get_db_name(self, request, tenant_name): return 'rgmanagement-%s' % tenant_name def get_cache_prefix(self, request, tenant_name, db_name): """Los argumentos db_name y tenant_name son dados por TenantMapper""" return 'rgmanagement-%s' % tenant_name whe i run: python manage.py migrate get this error: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 398, in execute self.check() File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/usr/lib64/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/usr/lib64/python2.7/site-packages/django/core/checks/model_checks.py", line 28, in check_all_models errors.extend(model.check(**kwargs)) File "/usr/lib64/python2.7/site-packages/django/db/models/base.py", line 1178, in check errors.extend(cls._check_fields(**kwargs)) File "/usr/lib64/python2.7/site-packages/django/db/models/base.py", line 1255, in _check_fields errors.extend(field.check(**kwargs)) File "/usr/lib64/python2.7/site-packages/django/db/models/fields/__init__.py", line 925, in check errors = super(AutoField, self).check(**kwargs) File "/usr/lib64/python2.7/site-packages/django/db/models/fields/__init__.py", line 208, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/usr/lib64/python2.7/site-packages/django/db/models/fields/__init__.py", line … -
Implementing editing/deleting a comment on a post in the same post_detail page
I'm using django's class-based views, and have successfully implemented a form for posting a comment on the same page as the DetailView for my Post model. I'm trying to implement an update/delete function for the comments, but I'm having trouble locating the specific comment using pk's. What approach could I take to locate the specific comment and edit/delete it? I would like the edit button to lead to a page with a form filled in with the current comment data, and the delete button to lead to a comment_confirm_delete.html template. It would be awesome to edit the comment with a form on the same page, but I'm trying to get it working on a separate page first. I found a lot of resources on how to do it using function-based views, but would like to use class-based views. This is the urlpattern for comment delete (I haven't gotten to the update yet) path('post/<int:pk_post>/comment/<int:pk_comment>/delete',CommentDeleteView.as_view(), name='comment-delete') This is in my views.py for the class that inherits DeleteView class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) comment = Comment.objects.get(id=self.kwargs.get('pk_comment', '')) context['comment'] = comment return context def test_func(self): Comment = self.get_object() return self.request.user == comment.author This … -
Changing the numbering on an ordered list to reverse percentages
I'm trying to give a percent matching score like 90% Match to each of my search results. Is there any ways to write a function in python or to create some Javascript code that would automatically assign a random value from 100 to 0% (in reverse order) to every items inside of an ordered list (which are my search results) based on the default order of the list (1,2,3,4..). The only problem is that I don't know the exact number of results that will be displayed since every queries can be different, and I'm using Elasticsearch as an index. A quick example of the html: <div> {% if page_obj.object_list %} <ol class="row top20"> {% for result in page_obj.object_list %} <li class="list-item"> <div class="showcase col-sm-6 col-md-4"> <a href="{{ result.object.get_absolute_url }}"> <h3>{{result.object.title}}</h3> <img src="{{ result.object.image }}" class="img-responsive"> </a> </div> <li> {% endfor %} </ol> </div> {% else %} <p> Sorry, no result found </p> {% endif %} Now the final expected results should look to something like this: - Title 1 image... *100% Match* <-- Random % Value based on the order --> - Title 2 image... *92% Match* - Title 3 image... *85% Match* - Title 4 image... *56% Match* I'm … -
How can I manage my users in Django so that when making the same request to the API by two different users the treatment is individual?
The case is that there are two users created and when trying to execute the same request at the same time (upload a file), both files are uploaded to the administrator user. Can it be something related to JWT, cookies, sessions or something like that? Thx in advance -
Django app and IIS - error occurred while reading WSGI handler
I am trying to upload a Django app using IIS in Windows. I follow a tutorial but I keep getting this error, and I have no clue about how to solve it. I installed all the pre requisites. The error is: Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\users\rodri\python\python37-32\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\users\rodri\python\python37-32\lib\site-packages\wfastcgi.py", line 622, in read_wsgi_handler env = get_environment(physical_path) File "c:\users\rodri\python\python37-32\lib\site-packages\wfastcgi.py", line 399, in get_environment doc = minidom.parse(web_config) File "c:\users\rodri\python\python37-32\lib\xml\dom\minidom.py", line 1958, in parse return expatbuilder.parse(file) File "c:\users\rodri\python\python37-32\lib\xml\dom\expatbuilder.py", line 911, in parse result = builder.parseFile(fp) File "c:\users\rodri\python\python37-32\lib\xml\dom\expatbuilder.py", line 207, in parseFile parser.Parse(buffer, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 24, column 16 StdOut: StdErr: and I have two web.config files. One in the main wwwroot and another to handle static files. <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\users\rodri\python\python37-32\python.exe|c:\users\rodri\python\python37-32\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!--Required Settings--> <add key="WSGI_HANDLER" value="NLPFrontEnd.wsgi.application" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\NLPFrontEnd" /> <add key="DJANGO_SETTINGS_MODULE" value="NLPFrontEnd.settings" /> </appSettings> </configuration> <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.webServer> <!--Overrides the FastCGI handler to let IIS serve the static files--> <handlers> <clear /> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read" /> </handlers> </system.webServer> </configuration> Any help would very …