Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should a shopping cart id be tied to a user id?
I want to create a shopping cart app that is tied to the user id. Mainly because if the user logs out, the items in the cart won't be deleted. This is my first Django project so I'm not 100% sure if this is a good idea as the tutorials I'm following all use sessions for the carts, so it would be great if someone could give me some feedback. Here is my models.py: from django.db import models from django.conf import settings from menulistapp.models import menulist User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): try: cart_obj = Cart.objects.get(id=request.user.id) new_obj = False except Cart.DoesNotExist: new_obj = True cart_obj = Cart.objects.create(user=request.user) cart_obj.id = request.user.id return cart_obj class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ManyToManyField(menulist, blank=True) total = models.DecimalField(default=0.0, max_digits=10, decimal_places=1) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) Here's my views: def cart_home(request): template = "cartapp/home.html" cart_id = request.user.id cart_obj = Cart.objects.new_or_get(request) context = { "x": request.user, } return render(request, template, context) -
The QuerySet value for an exact lookup must be limited to one result using slicing
I am trying to generate a queryset using one to many rlationship via foreign key.I am trying to obtain profile instance from current logged in user, then getting profile following, after than, i will extract post as well as comment. The associating models are:- #models.py from django.contrib.auth.models import User #this is how profile of a sample user, say MAX looks like class Profile(models.Model): Follwers=models.IntegerField(default='0') user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) bio=models.TextField(max_length=120,blank=True) location=models.CharField(max_length=30,blank=True) birth_date=models.DateField(null=True,blank=True) verified=models.BooleanField(default=False) ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def update_user_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class FollowingProfiles(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) ProfileName=models.CharField(max_length=120,blank=True,null=True) def __str__(self): return self.ProfileName class post(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True) DatePosted=models.DateTimeField(default=timezone.now) Content=models.TextField(blank=True,null=True) def __str__(self): return self.Profile.user.username class comment(models.Model): post=models.ForeignKey(post,on_delete=models.CASCADE) Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Content=models.CharField(max_length=120,null=False,blank=False,default='it is sapora') def __str__(self): return self.Profile.user.username #views.py def feed(request): if request.user.is_authenticated: profile=Profile.objects.filter(user=request.user) userfollowing=FollowingProfiles.objects.filter(Profile=profile) for following in userfollowing: username=following.ProfileName useraccount=User.objects.filter(username=username) mprofile=Profile.objects.filter(user=useraccount) Post=post.objects.filter(Profile=mprofile) comment=comment.objects.filter(post=Post) final_post_queryset=final_post_queryset+Post final_comment_queryset=final_comment_queryset+comment return render(request,'feed/feed.html',{'final_comment_queryset':final_comment_queryset,'final_post_queryset':final_post_queryset}) else: return redirect('signup') It produces following error:- The QuerySet value for an exact lookup must be limited to one result using slicing. -
Django : SQLite Database is Locked when I build like feature on my home page
I am implementing Like functionality in Web application. Idea is Simple to List number of Post(Blogs) on Home page and Add a Like Button to each post(Blog). It works fine when I build it with normal <form action='{% url target %}' method='POST'> But when I implemented this with AJAX call It only allows me to like or dislike a particular post(blog) a single time.i.e One I liked a Post for first time it works, also when I dislike the same Post It works fine, But when I again Like that Post it throws an django.db.utils.OperationalError: database is locked like_section.html <form id="like-form{{ post.id }}"> {% csrf_token %} <button type="submit" id="{{ post.id }}btn" name="like" value="{{ post.id }}" class="btn upvote">Like</button> <script type="text/javascript"> {% for like in post.likes.all %} {% if like != user %} dislikingPost("{{ post.id }}btn"); {% else %} likingPost("{{ post.id }}btn"); {% endif %} {% endfor %} $(document).ready(function(event){ $(document).on('click', '#{{ post.id }}btn', function(event){ event.preventDefault(); pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "like_post" %}', data: { 'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success:function(response){ $('#like-form{{ post.id }}').html(response['form']) // $('#{{ post.id }}btn').style.color = 'green'; }, error: function(er, e){ console.log(er.responseText); } }); }); }); </script> </form> views.py: def like_post(request): all_posts = Posts.objects.all() … -
I want to learn Anaconda (Python) + Django, Database web development using Oracle DB
I have installed Python 3.7 using Anaconda 2018.12 and Django, want to learn Database Web Development using Oracle DB ( 11g and/or 12c ), please help where I can found the references/resource guidance/tutorials etc. which guide step-by-step from setup/configure onward. also recommend an IDE. regards -
Django Remove Login Alert Message AllAuth
I am using AllAuth with Django to make a logjn form. The issue is that I am trying to remove the error message in my login form that spawns from the form|crispy field, so that it only appears using the code at the bottom outside the form. Is this possible? Login.HTML <form class="login" method="POST" action="{% url 'account_login' %}" style="list-style-type: none;"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="primaryAction btn btn-primary shadow mt-2" style="width: 100%;" type="submit">{% trans "Sign In" %}</button> </form> // Added Error Message to Custom location {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="container-fluid messages moveInTop"> <div class="alert alert-error alert-danger card"> {{ error|escape }} </div> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="container-fluid messages moveInTop" style="width: 28rem; z-index: 100; position: fixed; bottom: 10%; opacity: .95; left: 60.2%;"> <div class="alert alert-error alert-danger messages card"> {{ error|escape }} </div> </div> {% endfor %} {% endif %} -
Django AJAX returns undefined instead of the variables
So I have a simple Django script which I've found online for an AJAX function that runs a Python script and gets the output via stdout. views.py from django.shortcuts import render def index(request): return render(request,'homepage/page.html') homepage/page.html <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>test</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { $('#clickme').click(function(){ alert('Im going to start processing'); $.ajax({ url: "static/homepage/js/external_func.py", type: "POST", datatype:"json", data: {'key':'value','key2':'value2'}, success: function(response){ console.log(response.keys); console.log(response.message); } }); }); }); </script> </head> <body> <button id="clickme"> click me </button> </body> </html> So you can see my url is linked to external_func.py which runs after the button is clicked. The script then returns a json. external_func.py import sys import json import cgi fs = cgi.FieldStorage() sys.stdout.write("Content-Type: application/json") sys.stdout.write("\n") sys.stdout.write("\n") result = {} result['success'] = True result['message'] = "The command Completed Successfully" result['keys'] = ",".join(fs.keys()) d = {} for k in fs.keys(): d[k] = fs.getvalue(k) result['data'] = d sys.stdout.write(json.dumps(result, indent=1)) sys.stdout.write("\n") sys.stdout.close() However, when I run the server and clicked on the button, the console shows undefined for both values, meaning response.keys and response.message is undefined. Now, when I instead switch the code to console.log(response) in homepage/page.html. The console prints out the entire external_func.py code in text. I couldn't find a solution … -
Django-Auth-LDAP with MemberUid
I am trying to configure django-auth-ldap to work with a very old LDAP schema that I have inherited. I am running into 2 issues with querying for LDAP groups. First, my LDAP schema uses the memberUid attribute rather than member attribute. Second, my LDAP schema has an uppercase OU that seems to be tripping-up django-auth-ldap. My django-auth-ldap setup is fairly straightforward, mostly taken directly from the official documentation. Here are a few significant lines. Note the uppercase 'G' in my OU. AUTH_LDAP_GROUP_SEARCH = LDAPSearch('ou=Group,dc=school,dc=edu', ldap.SCOPE_SUBTREE,'(objectClass=groupOfNames)',) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn') AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_staff":"cn=org-staff,ou=Group,dc=school,dc=edu" } Here is a snipper of my ldap dump. cn: cn=org-staff,ou=Group,dc=school,dc=edu objectClass: posixGroup objectClass: top cn: org-staff gidNumber: 999 memberUid: someuser And here is a particularly telling line from my syslog. Dec 27 22:56:47 server slapd[45950]: conn=1467 op=4 CMP dn="cn=org-staff,ou=group,dc=school,dc=edu" attr="member" Dec 27 22:56:47 server slapd[45950]: conn=1467 op=4 RESULT tag=111 err=16 text= LDAP error 16 is LDAP_NO_SUCH_ATTRIBUTE, which makes sense in this case given that the query is looking for the member attribute but my group does not have any such attribute. The second issue here is that for some reason the 'G' in my OU is not capitalized in the query. Is there any way to make … -
Is Django framework vulnerable to local file inclusion(LFI) and remote file inclusion(RFI)?
Like in php, include() method and allow_url_include can be vulnerable to lfi and rfi Does django's include is vulnerable to lfi and rfi? -
Overriding settings in Django when used by the models
We are using Django for Speedy Net and Speedy Match (currently Django 1.11.17, we can't upgrade to a newer version of Django because of one of our requirements, django-modeltranslation). Some of our settings are used by the models. For example: class USER_SETTINGS(object): MIN_USERNAME_LENGTH = 6 MAX_USERNAME_LENGTH = 40 MIN_SLUG_LENGTH = 6 MAX_SLUG_LENGTH = 200 # Users can register from age 0 to 180, but can't be kept on the site after age 250. MIN_AGE_ALLOWED_IN_MODEL = 0 # In years. MAX_AGE_ALLOWED_IN_MODEL = 250 # In years. MIN_AGE_ALLOWED_IN_FORMS = 0 # In years. MAX_AGE_ALLOWED_IN_FORMS = 180 # In years. MIN_PASSWORD_LENGTH = 8 MAX_PASSWORD_LENGTH = 120 MAX_NUMBER_OF_FRIENDS_ALLOWED = 800 PASSWORD_VALIDATORS = [ { 'NAME': 'speedy.core.accounts.validators.PasswordMinLengthValidator', }, { 'NAME': 'speedy.core.accounts.validators.PasswordMaxLengthValidator', }, ] (which is defined in https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/net/settings/global_settings.py). And then in the models I use: from django.conf import settings as django_settings class User(ValidateUserPasswordMixin, PermissionsMixin, Entity, AbstractBaseUser): settings = django_settings.USER_SETTINGS (and then use attributes of settings, such as settings.MIN_SLUG_LENGTH, in the class). The problem is, when I try to override such settings in tests (you can see my question & answer on Can I define classes in Django settings, and how can I override such settings in tests?), User.settings remains the same and is not overridden … -
How to remove "something ptr": when I render form with formset_factory?
When I render the site at the end of each form appear the string "Human ptr:"... how can I delete it? (Human is class where Player derives from) I have a form made with modelformset_factory rendered like this: team_area.html {% extends 'base_layout.html' %} {% block content %} <h1>Area Squadra</h1> <form method="post" action=""> {% csrf_token %} {{ player_formset.management_form }} {% for player_form in player_formset %} {% for field in player_form %} {{ field.label_tag }} {{ field }} {% endfor %} <br> {% endfor %} <input type="submit" value="Aggiorna"> </form> {% endblock %} And the view is managed by: views.py from django.shortcuts import render, redirect from skeleton.models import Player from django.contrib.auth.decorators import login_required from .forms import PlayerForm from django.forms import modelformset_factory from django.http import HttpResponseNotFound # Create your views here. @login_required(login_url="/accounts/login/") def team_area(request): if request.user.team != None: PlayerFormSet = modelformset_factory(Player, form=PlayerForm, extra=1, can_delete=True,) if request.method == "POST": player_formset = PlayerFormSet( request.POST, request.FILES, queryset=Player.objects.all().filter(team=request.user.team),) for player_form in player_formset: if player_form.is_valid(): player = player_form.save(commit=False) player.team = request.user.team #if player.first_name != '' and player.last_name != '': # player.save() if player_formset.is_valid(): player_formset.save() return redirect('team_area:home') else: player_formset = PlayerFormSet(queryset=Player.objects.all().filter(team=request.user.team)) return render(request, 'team_area/team_area.html', {'player_formset': player_formset}) else: return render(request, 'team_area/empty_page.html') I expect to remove Human ptr: possibly without css or … -
problem with customize code samples in api documentation
I am trying to add swift code samples to the auto-generated api documentation in my django-rest-framework project. The docs say I must subclass DocumentationRenderer and add the languages I want as well as create the templates for them. But it does not tell me what to do with the subclassed Renderer. from rest_framework.renderers import DocumentationRenderer class CustomRenderer(DocumentationRenderer): languages = ['ruby', 'go'] So I created "CustomRenderer" in my file under core/serializers.py great, now what? Where do I reference this class so I can actually apply it? https://www.django-rest-framework.org/topics/documenting-your-api/#customising-code-samples -
How to access objects of grandparent model associated with target model through ContentType GenericForeignKey?
I'm trying to filter objects of model based on associated grandparent model. They are associated with each other through an intermediary parent model. Parent model is associated with grandparent through ContentType GenericForeignKey. How can I access all objects of target model sharing same Grandparent. I tried to use GenericRelations on Grandparent but it did not work as it returns all the Parent Objects associated with that GrandParent Model. For that, I've to loop through querysets. Please check the code for details: class State(models.Model): name = models.CharField(max_length=25) population = models.PositiveIntegerField() class UnionTerritory(models.Model): name = models.CharField(max_length=25) population = models.PositiveIntegerField() class District(models.Model): name = models.CharField(max_length=25) content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type','object_id') population = models.PositiveIntegerField() class Town(models.Model): name = models.CharField(max_length=25) district = models.ForeignKey(District,related_name='towns',on_delete=models.CASCADE) population = models.PositiveIntegerField() """Here, District can be connected to State or UnionTerritory but town will always be part of district.""" Now, if I select any State or UnionTerritory Object; I want to have access to all towns under it. I want to filter all Town instances who share same State or UnionTerritory. Towns can be connected to different districts which belong to same state or same UnionTerritory. How can I access UnionTerritory or State associated with Town and … -
Django Apps aren't loaded yet: How to import models
I have a Django project looking like > project > gui > __init__.py > models.py > views.py > ... > project __init__.py ... I am trying to sync the sqllite db in django with some info I periodically query from other sources. So in project.init.py I spawn a thread that periodically queries data. However, I am having trouble accessing my models from there and update the database, because when I try to import them into init.py from gui.models import GuiModel I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Is there a trick to do that or a different way to create a separate thread? -
Django: Annotate aggregation of filtered related set
I'm looking for a way to annotate value of aggregated filtered related set. class Location(... ... class Ticket(... location = ForeignKey(Location...) date = ... price = ... I need to annotate maximal price of ticket in a daterange. So if I set only last 30 days, it returns me all Location objects and every object have 'max_price' annotation which equals to maximal price of the tickets from last 30 days. Tickets: <Ticket France 100 now-50days> <Ticket France 200 now-20days-> <Ticket France 300 now-20days> <Ticket Austria 200 now-10days> <Ticket Austria 50 now-10days> In this case, queryset returns: <Location France> + annotated 200 <Location Austria> + annotated 50 Is it possible to do it in one Query? -
Django - Form Does Not Save User Values
I currently have a form on the “myaccount.html” page of my web application. This form renders how I want however I cannot submit the form values for some reason to appear in the django admin. When a user hits “submit”, the page refreshes and the values stay in the input fields. I’ve tried many methods to solve this but no luck. I thought I had everything together but maybe I’m missing something somewhere? Is there anything I’m missing to resolve this issue? I’m new to Django so any help is gladly appreciated. Thanks! users/views.py from users.forms import CustomUserCreationForm from django.views.generic.edit import CreateView from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_GET, require_POST from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect from django.shortcuts import render, redirect from django.template import loader from django.urls import reverse_lazy from django.views import generic from django.views.generic import FormView from django.views.generic.edit import FormView from django.conf import settings from django import forms class SignUp(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('home') template_name = 'signup.html' class change(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('myaccount') template_name = 'myaccount.html' def form_valid(self, form): form.instance.name = self.request.name form.instance.address = self.request.address form.instance.zip_code = self.request.zip_code form.instance.mobile_number = self.request.mobile_number form.save() return super(change, self).form_valid(form) users/models.py from … -
What is the purpose of setting a variable in self.send for Django Channels?
In Django Channels tutorial, you set a variable called 'text_message'. This is for the consumer to echo the message that it has received. def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(**text_data**=json.dumps({ 'message': message })) What is the use of 'text_message'? I have removed it so that it looks like this, and still successfully rendered the message in my HTML. def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(json.dumps({ 'message': message })) -
How to use JWT (JSON Web Tokens) with Django and Python for creating the REST API for signup and login
I've being trying to implement the JWT (JSON Web Tokens) in the Django project. But I was not able to achieve the same. Can you please help me with some tutorial or tips or links to study the same. I tried using the pyjwt in my project, but the token generated every time I hit the API was same for the same user email address and password. -
Download a file with selenium on Heroku
I am attempting to download a file from a link, parse the file, then save specific data to my heroku database. I have successfully set up my selenium chrome webdriver and I am able to log in. Normally, when I get the url, it begins downloading automatically. I have set up a new directory for the file to be saved to on heroku. It does not appear to be here or anywhere. I have tried different methods of setting the download directory, other methods of logging in to the website, and have functionally done it locally, but not in heroku production. # importing libraries from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time import datetime from datetime import timedelta import os import json import csv # temporary credentials to later be stored # as env vars user = "user" psw = "pasw" account = 'account' # this is the directory to download the file file_directory = os.path.abspath('files') # making this directory the default chrome web driver directory options = webdriver.ChromeOptions() prefs = { "download.default_directory": file_directory } options.add_experimental_option('prefs',prefs) # setting up web driver driver = webdriver.Chrome(chrome_options=options) # logging in to pinterest url_login … -
What is the easiest way to tag user-submitted questions with category tags on a Django-base site?
I am building a site in Django where users submit questions about a wide range of topics. When a question is submitted, I would like it to be tagged with the various categories to which it belongs so it can be grouped with related questions. For example, if someone asks "does breastfeeding increase the risk of cancer?", I want that question tagged with categories like "child care, breastfeeding, cancer, etc". I understand that categorizing content is a common issue and I am curious what the best options are. -
DRF: Built-in way to group fields in Serializer?
Is there a built-in way to group fields in Serializer/ModelSerializer or to modify JSON structure? There is a Location model: class Location(Model): name_en = ... name_fr = ... ... If I use ModelSerializer I get plain representation of the object fields like: {'name_en':'England','name_fr':'Angleterre'} I want to group some fields under "names" key so I get {'names':{'name_en':'England','name_fr':'Angleterre'}} I know I can create custom fields but I want to know if there is a more straightforward way. I tried Meta.fields = {'names':['name_en','name_fr']...} which doesn't work -
Can't understand WebAuthn API error from JavaScript
I am currently building out an AJAX registration endpoint for Django to allow for FIDO2 authentication (physical hardware key login). This is from following the example/documentation from Yubico's official fido2 python library. The only dependencies are cbor.js and js-cookie. Everything server-side is working for now, however, I keep getting this JavaScript error while invoking the navigator.credentials.create method TypeError: Failed to execute 'create' on 'CredentialsContainer': The provided value is not of type '(ArrayBuffer or ArrayBufferView)' The code: var csrftoken = Cookies.get('csrftoken'); fetch('/register/begin', { method: 'POST', headers: { 'X-CSRFToken': csrftoken } }).then(function(response) { if(response.ok) { return response.arrayBuffer(); } throw new Error('Error getting registration data!'); }).then(CBOR.decode).then(function(options) { console.log(options) //This line is not working return navigator.credentials.create(options); //More code... complete registration... I can't figure this out. Do you know whats wrong? Thanks! -
Django: How to correct created date/time
I've a model Order, that has a field created. It's intention is to show when the order took place (date and time speaking). I'm using this line to create the field in the model: current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') However, the reviewing it from admin panel, it shows It was created in the future: 10:52 pm of 27/12. When the time right now is: 6:11 pm. You can see these details in this screenshot: How can I make sure the correct time gets recorded in productio env? It'll be hosted using Google Cloud Products. Right know I'm in development env. View that creates the Order: @csrf_exempt def cart_charge(request): culqipy.public_key = settings.CULQI_PUBLISHABLE_KEY culqipy.secret_key = settings.CULQI_SECRET_KEY amount = request.POST.get('amount') currency_code = request.POST.get('currency_code') email = request.POST.get('email') source_id = request.POST.get('source_id') last_four = request.POST.get('last_four') dir_charge = {"amount": int(amount), "currency_code": currency_code, "email": email, "source_id": source_id} print(dir_charge) charge = culqipy.Charge.create(dir_charge) transaction_amount = int(charge['amount'])/100 #Necesario dividir entre 100 para obtener el monto real, #Esto debido a cómo Culqi recibe los datos de los pagos current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') shipping_address1 = request.user.profile.shipping_address1 shipping_address2 = request.user.profile.shipping_address2 shipping_department = request.user.profile.shipping_department shipping_province = request.user.profile.shipping_province shipping_district = request.user.profile.shipping_district order = Order.objects.create( token = charge['id'], total =transaction_amount, email= email, #Using email entered in Culqi module, … -
How to create likes and number of people viewing a particular blog in a blog app [on hold]
I have been working on a blog app that as at now, people can sign up, sign in, create posts, update posts, delete posts but i need logic for the users to like other peoples posts or show how many people have viewed a particular post. thanks -
Auto fill form field in html with data value and make it read only
I'm in process of creating a page where you can add a customer with some information regarding to them. I want to assign an unique id for each customer. I of course type in the basic information myself, but I also need a field in the form that has been populated with a generated random id, that has been checked in the database if it already exists. If it doesn't then fill it into the form, and if it does then generate a new one until a not used one is found. Models.py class Opretkunde(models.Model): Fornavn = models.CharField(max_length=30) Efternavn = models.CharField(max_length=50) Telefon = models.IntegerField() Adresse = models.CharField(max_length=50) Postnummer = models.IntegerField() IA = models.CharField(max_length=10) salgsperson = models.CharField(max_length=150, default="missing") The field IA is the field which should be automatically populated with the randomly generated value forms.py class Opret_kunde_form(ModelForm): class Meta: model = Opretkunde fields = ['Fornavn', 'Efternavn', 'Telefon', 'Adresse', 'Postnummer', 'IA'] views.py def index(request): if request.method == 'POST': form = Opret_kunde_form(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.salgsperson = request.user instance.save() return HttpResponseRedirect(reverse('createUser:createUser')) else: form = Opret_kunde_form() return render(request, 'createCustomer.html', {'form': form}) The function im using to generate a value looks like this def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return … -
Make django display non-jinja element while waiting for it to be completed
So here's what I'm trying to do. Let's say I have a really long function that takes some time to process. Eventually, the output needs to be displayed on a webpage. I'm using Python 3.6 and Django 2 framework. views.py from django.shortcuts import render import time def f(): time.sleep(5) return [5,6,7] def index(request): return render(request,'homepage/page.html', {'funcF':f}) So as you can see, I have a function that waits for 5 seconds to pass before returning an array of numbers. homepage/page.html <p> Hello there! </p> {% for r in funcF %} <p> {{r}} </p> {% endfor %} My goal is that I want Hello there! to be displayed and wait for 5 seconds to pass, then display the numbers in the array. In it's current state, the webpage instead takes 5 seconds to reload, and it displays both Hello there! and the numbers on the array all at once. Any bright ideas?