Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"CELERY_BEAT_SCHEDULER" config is not work in django settings
I set CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" in my django project settings file. But It doesn't seem to work. I check the celerybeat logs and I found that the celery beat scheduler is celery.beat.PersistentScheduler. I can only set beat scheduler to "DatabaseScheduler" at the celery beat startup file (celery -A config beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler). How can I set the scheduler in django settings file ? I don't want to set the scheduler in the celery beat startup command. -
How to pass a dictionary and a context in the same return render() function from a view to template in python
I would like to list a data from database and one variable in the context, however, when i pass both in the same return render() function it gives me This is my view View -
django form resubmission on page refresh
After I submit the form for the first time and then refresh the form it gets resubmitted and and I don't want that create_group.html: <form id="create_group" class="form-horizontal" role="form" action="" method="post"> {% csrf_token %} {% include 'whatsapp_blast/form_template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button style="background-color:#FA4616;border: none;" type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> views.py: def create_group(request): groups = Group.objects.filter(user=request.user) print(groups) if request.method == "POST": print("In IF") form = GroupForm(request.POST) if form.is_valid(): group = form.save(commit=False) group.user = request.user group.save() # Redirect to THIS view, assuming it lives in 'some app' return HttpResponseRedirect("whatsapp_blast.views.create_group") else: print("else") form = GroupForm(request.POST) print(form) context = { "form": form, } return render(request,'whatsapp_blast/create_group.html', context) -
Model Instance Methods using the __str__() method
I have come across this in these Sections of the Django Documentation. I am however confused by the difference between the two. What is the difference between: (found HERE) class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name and: (found HERE) class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return '%s %s' % (self.first_name, self.last_name) Which one is the correct one? Note that both work interchangeably as far as I have tested -
How session based contests are handled in django url
I am new to django . i want to create a session based contest and unique url for the same which will be valid for certain time. What is the good practice to implement it. -
How to call a view function while changing a select option in Django template?
I created a filter form on left side and showing the filtered queryset on right side: How to sort the returned queryset while changing the options of select tag: <div class="input-container"> <select class="input-text" onchange="{% url 'listing:search' %}" name="sort" id="sort"> <option value="price_l2h">Price (low to high)</option> <option value="price_h2l">Price (high to low)</option> <option value="newest">Newest</option> <option value="bedroom">Bedroom</option> <option value="bathroom">Bathroom</option> <option value="sqrft">sqrft</option> </select> </div> I noticed that onchange="{% url 'listing:search' %}" cant't help and I don't know how to add that sorting functionality. This is a snippet of listing:search function. Kindly help me sort the returned queryset based on option selected from select tag. Thank You -
Using Websockets with Django on Google App engine Flex
I'm currently trying to setup a Google app engine flex using a django framework with django-channels. for my current project i need a websocket, so i'm trying to reconstruct the tutorial offered on the website by Django-channels: https://channels.readthedocs.io/en/latest/tutorial/ Currently I'm stuck on adding redis to my google-app-flex instance. I followed the google documentation on setting up a redis connection - unfortunatly the example is in Flask: google doc I assume my error is trivial, and i just need to connect django CHANNEL_LAYERS to redis proporly. executing sudo gcloud redis instances describe <redisname> --region=us-central1 gives me following responce: Image: "Redis Describtion" executing sudo gcloud app describe, this responce: I configured my app.yaml as follows: # app.yaml # [START runtime] runtime: python env: flex entrypoint: daphne django_channels_heroku.asgi:application --port $PORT --bind 0.0.0.0 runtime_config: python_version: 3 automatic_scaling: min_num_instances: 1 max_num_instances: 7 # Update with Redis instance IP and port env_variables: REDISHOST: '<the ip in "host" from "Redis Describtion" image above>' REDISPORT: '6379' # Update with Redis instance network name network: name: default # [END runtime] ..and in my settings.py i added this as the redis connection (which feels really wrong btw): #settings.py import redis #settings.py stuff... #connect to redis redis_host = os.environ.get('REDISHOST', '127.0.0.1') redis_port … -
How to correctly integrate mailchimp with your website?
I wanted to use Mailchimp for my a website which would basically take user's email when submitting,so I got the url from mailchimp which stands like the url below, I added the post-json and also &c=? at the end! https://xxxxxx.us3.list-manage.com/subscribe/post-json?u=b5d4f5b14088dceec18dc9ca8&amp;id=9d2643cd8e&c=? And integrated it with my jquery like this! $(".mailchimp-submit").submit(function(e){ e.preventDefault() var this_ = $(this) var successMsg = "success_message" $.ajax({ type: "GET", url: "url", data: this_.serialize(), cache : false, dataType : 'jsonp', error : function(err) {errorMsg()}, success:(data)=>{ if (data.result != "success") { errorMsg(successMsg) } else { msg.text() msg.css("color","#6610f2") } }, }) }) And built my form like this! <form class="mailchimp-submit wow fadeInUp" data-wow-delay="0.6s" method="GET" > <div class="input-group subcribes"> <input type="text" name="EMAIL" class="form-control memail" placeholder="abc@example.com" required> <button class="btn btn_submit f_size_15 f_500" type="submit">{% trans 'Get Started' %}</button> </div> </form> But I submit my email on FireFox it gives me a warning in console: The resource at “https://xxxxxxx.us3.list-manage.com/subscribe/post-json?u=b…1590645826995&EMAIL=yoneyos382%40whowlft.com&_=1590645826996” was blocked because content blocking is enabled. I thought it's the case with the browser so I tried it on chrome, but on that it gives me an error like this! A cookie associated with a cross-site resource at https://list-manage.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with … -
Make each fieldset within the inline collapsable, not the whole inline
I wanted to know if there is any way to make the fieldsets (StackedInline items) within the Inline container collapsable. I have gone through some previous questions and blogs but they are all trying to collapse the inline using classes = ['collapse'] Which is pretty easy but wanted to know if the same is possible for the children instead of container. -
Update serializer data in Django
I'm trying to add a dictionary to my serialized data but I'm getting an error dictionary update sequence element #0 has length 6; 2 is required This is what I have tried: def get_data(self, request): created_by = User_Detail.objects.get(auth_token__isnull=False) newdict = {'created_by': created_by.id} details = ExSerializer(Tower.objects.all(), many=True).data newdict.update(details) return Response({"expenses": newdict}) I tried the above code but it's not working for me. -
DTO's in Django Python?
So I am starting to learn Django, and looking to build a Rest API with it. I am basically coming from .Net background. I know that the Python conventions are quite different than .Net's and I understand that well, but in my perspective, I see lot of redundancies and lack of standards(Solid) when developing application in Django. Here is my project hierarchy. [DjangoProject]: [Finance]: admin.py apis.py services.py test.py urls.py models.py [Users]:... apis.py -> Each API will have it's one class class ReportCreateApi(APIView): class InputSerializer(serializers.Serializer): title = serializers.CharField() description = serializers.CharField() pictures = serializers.CharField() lat = serializers.CharField() long = serializers.CharField() vote = serializers.CharField() def post(self, request): serializer = self.InputSerializer(data=request.data) serializer.is_valid(raise_exception=True) ReportService.ireport_create(**serializer.validated_data) return Response(status=status.HTTP_201_CREATED) services.api -> Services will have **kwargs as parameters class ReportService: @staticmethod def ireport_create(**report) -> Report: logger.info('Creating IReport') ireport = Report(**report) #Report is a modal btw ireport.save() return ireport Although it works for now, it doesn't look right to me. With this anyone can pass unlimited number of parameters that may not be expected by the services. What would be the best approach to pass the parameters to the service from api so that I can map it to the model when creating one inside the service? -
Unable to send the html div values to django view using ajax post request
I wanted to send two html values from ajax to django view on click of an html element for that I had wrote the ajax post request as follows: AJAX is: $(document).ready(function() { $("#msg_send_btn").click(function() { var msg=$("#write_msg").val() var id=$("#insertName").html() $.ajax({ url: "target_view/", type: "POST", data: { id:id, msg:msg, csrfmiddlewaretoken: '{{ csrf_token }}' }, success : function(json) { alert("Successfully sent the id= "+id+" msg= "+msg+" to Django"); }, error : function(xhr,errmsg,err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } }) }) }) And in urls.py I had specified the url path('target_view/', views.chat1, name='chat1') views.py is def chat1(request): value1 = request.POST.get('id') value2 = request.POST.get('msg') print(value1,value2) return HttpResponse(value1,value2) and the problem here is when I the html page consisting of ajax request I am getting an success alert message which I had specified with the id and msg on click of the button and when I run the python server and goes to http://127.0.0.1:8000/target_view/ I am getting none even in terminal I am getting None None Can anyone help me out from this? Thanks in advance -
Adding/Exposing a port with Django to an existing Docker container
This may have a fairly simple answer here, but... I am trying to use this container: https://hub.docker.com/r/gboeing/osmnx in order to just easily handle some complex dependencies. I ran into all kinds of conda dependency issues with the library I'd like to use when just building a docker image from the continuum/anaconda container. So, I'd like to expose a port and run a Django server from inside this container. I manually installed Django and ran the server inside the container. However, I cannot connect to localhost, http://127.0.0.1:8000/. (base) root@91805d36444c:/server# python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 27, 2020 - 05:31:45 Django version 3.0.6, using settings 'server.settings' Starting development server at http://127.0.0.1:8000/ Navigating to http://127.0.0.1:8000/ in the browser, cannot be reached. Possibly relevant info: Docker version 19.03.9, build 9d988398e7 My OS is Description: Ubuntu 18.04.4 LTS I have no issues accessing http://127.0.0.1:8000/ with something like this https://docs.docker.com/compose/django/ -
fetch acting differently in different places
I'm making a React + Django Integrated website. Here is the relevant snippet of my App.js in one folder and what it outputs - componentDidMount(){ fetch("/login/api/login_page") .then(response => { if (response.status > 400){ return this.setState(()=> {return {placeholder:"Something went wrong!"}; }); } return response.json(); }) .then(data=>{ this.setState(()=> { return{ data, loaded: true }; }); }); } //The rest has been omitted for brevity The link of that page itself is http://127.0.0.1:8000/loginresults/list/ and it accesses http://127.0.0.1:8000/login/api/login_page . However when I use nearly identical code in another .js file elsewhere it causes a weird error. componentDidMount() { fetch('/timetracker/api/TimeTracker/allObjects') .then(response => { if (response.status > 400) { return this.setState(() => { return { placeholder: "Something went wrong!" }; }); } return response.json(); }) This is called in http://127.0.0.1:8000/ttgui/op/ and when it tries to access it, it keeps searching a URL - http://127.0.0.1:8000/ttgui/op/timetracker/api/TimeTracker/allObjects/ whereas it should be going to http://127.0.0.1:8000/timetracker/api/TimeTracker/allObjects/ as illustrated above. Does anyone know why it's acting differently in these two different use cases? -
how do I update/delete a content in Django?
So I have a form in Django that lets users write their diary. Now I want to add edit button and delete button, but I'm having error. So here are the codes. template (detail.html) ... <form method='post' class="form-group"> {% csrf_token %} <div class="row justify-content-center"> <a href="{% url 'delete' authuser_id slug %}"> <button class='btn btn-primary button-delete'>Delete</button> </a> </div> </form> urls.py ... urlpatterns = [ ... path('detail/<int:authuser_id>/<slug:slug>', views.detail, name='detail'), path('detail/<int:authuser_id>/<slug:slug>', views.delete, name='delete'), ] views.py from .models import DiaryInput ... def detail(request, authuser_id, slug): todayDiary = DiaryInput.objects.get(slug=slug) return render(request, '/detail.html', {'todayDiary' : todayDiary}) def delete(request, authuser_id, slug): todayDiary = DiaryInput.objects.get(slug=slug) todayDiary.delete() return redirect('/') When I go to the detail page of a specific diary, I get an error that says : Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['detail/detail/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/delete$'] I believe there is something wrong with my template, in the {% url %} tag, but I don't see what I've done wrong. I appreciate your help :) -
Extending the `Field` class in Django
All my searching gave results for "custom fields" in Django which is not what I'm after, I'm trying to customize the Field class. The only similar question was not answered. I'm building a form in Django, and I'm trying to specify a specific icon to appear by each input field. For example, I have added a non-standard icon argument when building my form: checkin.py from django import forms class CheckInForm(forms.Form): last_name = forms.CharField( icon="fa-id-card-o" ) dob = forms.DateField( icon="fa-calendar" ) I would like to access this new icon argument from my template: checkin.html <form action="" method="post"> {% csrf_token %} <table> {% for field in form %} <label for="{{ field.name }}" class="col-4 col-form-label"> {{ field.label }} </label> <div class="col-8"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text"> <i class="fa {{ field.icon }}"></i> <!--- icon argument ---> </div> </div> {{ field }} </div> </div> {% endfor %} </table> <div class="form-group row"> <div class="offset-4 col-8"> <button name="submit" type="submit" class="btn btn-primary">Check In</button> </div> </div> </form> When I run this code, it of course fails with: TypeError: init() got an unexpected keyword argument 'icon' Attempted approach It seems to me this is a good case to extend some Python classes. Both CharField and DateField are subclasses of … -
How to pass parameter in current url to an html template in Django 3
I have: Movie Model class Movie(models.Model): title = models.CharField(max_length=255) synopsis = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('movie_detail', args=[str(self.id)]) Discussion Model class Discussion(models.Model): title = models.CharField(max_length=255) body = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) date = models.DateTimeField(auto_now_add=True, null=True, blank=True) movie = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name='discussion', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('discussion_detail', args=[str(self.movie.id), str(self.id)]) DiscussionListView class DiscussionListView(LoginRequiredMixin, ListView): model = Discussion template_name = 'discussion_list.html' login_url = 'login' And I also have discussion_list.html Here is what I want: I’m in the url /article/1/discussion/. The integer 1 is a movie_pk because the url is defined as /article/<int:movie_pk>/discussion/ which in this case refer to the priority key of a Movie Model, for example StarWars I. This is a page of list of discussion titles related to this movie. (This has already been achieved) There is a button “New” where, if i click on it, I will be directed to /article/1/discussion/new. There, I can create a new discussion. (The feature I want to add) However: In discussion_list.html, we require the url tag {% url discussion_new %} to have a parameter since discussion_new is defined as /article/<int:movie_pk>/discussion/new Thus: How to pass the movie_pk from … -
i want to add user activity to database in django
i want to add login and logout time of every user to the data base in my model i dont know how to create it model.py class User(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=20) username = models.CharField(max_length=20) password = models.CharField(max_length=20) timezone = models.CharField(max_length=32, choices=TIMEZONES,default='UTC') login_time = models.DateTimeField(default=datetime.now()) logout_time = models.DateTimeField(default=datetime.now()) def __str__(self): return self.name Every time a user login or logout the current activity is stored views.py @csrf_exempt def dash_board(request): if request.method == 'POST': if User.objects.filter(username=request.POST['username'], password=request.POST['password']).exists(): global user user = User.objects.get(username=request.POST['username'], password=request.POST['password']) act = User.objects.get(id=user.id) act.login_time = datetime.now() act.save() return render(request, 'dash.html', {'user': user, }) else: return render(request, 'index.html') @csrf_exempt def logout(request): if request.method == "POST": act = User.objects.get(id=user.id) act.logout_time=datetime.now() act.save() return render(request,'index.html') else: return HttpResponse("<h1>Error While LogOut..!!</h1>") Can anyone help me to solve this -
load of csv or json with jquery in django always brings back entire page html instead of contents of file
I've got a Django project on Win 10. I am trying to load a local json or csv file with custom jQuery. I've discovered that whenever I try to load the contents of a json or csv file, located somewhere in my /static/ directory, it always brings back the entire html page instead of the contents of the file. Doesn't matter if it is json or csv. I know by now that if there is an error, the html will come back, but I do not know how I could solve this problem at this point. function test () { fetch("admin/js/custom/codetable.json") .then(res => res.json()) .then((out) => { console.log('Output: ', out); }).catch(err => console.error(err)); } will bring back Unexpected token < in JSON at position 0 That is not a data format error, as I had previously suspected. I know the path resolves because if I intentionally foogle the path, there will be an additional 404 error. If I try this: function test2() { fetch("admin/js/custom/codetable.csv") .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.blob(); }) .then(myBlob => { myImage.src = URL.createObjectURL(myBlob); }) .catch(error => { console.error('There has been a problem with your fetch operation:', … -
Field 'id' expected a number but got 'std1', how do I get the ForeignKey ID of a Model field to use in Django Form?
I have Detail Model, which have the ForeignKey of the Django's default User Model. I created a Form to take the input from user and update the Detail Model fields if it exists else create a new detail. For this purpose, I am filtering the Detail.objects.all() on the username of the user which was selected in the Form at Front-End. Now, I need a ID of the username that was selected in order to update the Detail Model. How can I get the ID? If I just pass the username, it says Field 'id' expected a number but got 'std1'. My models.py: class Detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'is_superuser': False, 'is_staff': False}, verbose_name="Select a Student") subject = models.CharField(max_length=50, verbose_name='Subject Name', help_text='Write the name of the subject.') skype_session_attendance = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(20)], verbose_name="Skype Session Attendances (of this subject, in numbers)", help_text="Enter the numbers of skype sessions of this subject, the student attended out of 20.") internal_course_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(40)], verbose_name="Internal Course Marks (of this subject, in numbers)", help_text="Enter the total internal course marks of this subject, the student obtained out of 40.") programming_lab_activity = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(25)], verbose_name="Programming Lab Activities (of this subject, in numbers)", help_text="Enter the total numbers of programming lab activities … -
wsgi application name 'BASE_DIR' is not defined
I deployed django app on pythonanywhere.com. I am seeing this error. I searched a lot but didnt got anything. I am stuck with wsgi and dont know what to do with it. please help 2020-05-27 04:56:19,548: Error running WSGI application 2020-05-27 04:56:19,549: NameError: name 'BASE_DIR' is not defined 2020-05-27 04:56:19,549: File "/var/www/rashidtaha_pythonanywhere_com_wsgi.py", line 15, in <module> 2020-05-27 04:56:19,549: application = get_wsgi_application() 2020-05-27 04:56:19,549: 2020-05-27 04:56:19,549: File "/home/rashidtaha/.virtualenvs/rashidtaha.pythonanywhere.com/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-05-27 04:56:19,549: django.setup(set_prefix=False) 2020-05-27 04:56:19,549: 2020-05-27 04:56:19,549: File "/home/rashidtaha/.virtualenvs/rashidtaha.pythonanywhere.com/lib/python3.6/site-packages/django/__init__.py", line 19, in setup 2020-05-27 04:56:19,549: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2020-05-27 04:56:19,550: 2020-05-27 04:56:19,550: File "/home/rashidtaha/.virtualenvs/rashidtaha.pythonanywhere.com/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ 2020-05-27 04:56:19,550: self._setup(name) 2020-05-27 04:56:19,550: 2020-05-27 04:56:19,550: File "/home/rashidtaha/.virtualenvs/rashidtaha.pythonanywhere.com/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup 2020-05-27 04:56:19,550: self._wrapped = Settings(settings_module) 2020-05-27 04:56:19,550: 2020-05-27 04:56:19,550: File "/home/rashidtaha/.virtualenvs/rashidtaha.pythonanywhere.com/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ 2020-05-27 04:56:19,550: mod = importlib.import_module(self.SETTINGS_MODULE) 2020-05-27 04:56:19,550: 2020-05-27 04:56:19,550: File "/home/rashidtaha/rashidtaha.pythonanywhere.com/env/lib/python3.8/site-packages/isort/__init__.py", line 25, in <module> 2020-05-27 04:56:19,551: from . import settings # noqa: F401 2020-05-27 04:56:19,551: 2020-05-27 04:56:19,551: File "/home/rashidtaha/rashidtaha.pythonanywhere.com/env/lib/python3.8/site-packages/isort/settings.py", line 359, in <module> 2020-05-27 04:56:19,551: STATIC_ROOT = os.path.join(BASE_DIR, 'static') 2020-05-27 04:56:19,551: *************************************************** 2020-05-27 04:56:19,551: If you're seeing an import error and don't know why, 2020-05-27 04:56:19,551: we have a dedicated help page to help you debug: 2020-05-27 04:56:19,551: https://help.pythonanywhere.com/pages/DebuggingImportError/ -
all animation-icons in the card aren't working seamlessly
When I run the test server, I'm able to click on the like-icons of second and the last card, and the rest of em doesn't work if I click on them, they only work if I click on the 2nd and the last card icons at first, I've tried a lot of things but I don't know what I'm messing up I've no clue what is going on, please help, thnx <script> var animated = false; $('.heart1').click(function(){ if(!animated){ $(this).addClass('heart-line'); animated = true; } else { $(this).removeClass('heart-line').addClass('heart1'); animated = false; } }); </script> .card { width: 250px; height: 350; border-radius: 10px; box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); background-color: white; margin-left: 30px; margin-right: 30px; margin-top: 30px; margin-bottom: 30px; } .card:hover { box-shadow: 0 12px 20px 0 rgba(0,0,0,0.2); } .year { float: left; padding-top: 5px; padding-left: 5px; font-family: Circular Std Book; } .top { position: relative; } .heart1 { width: 100px; height: 100px; position: absolute; left: 220px; top: 20px; transform: translate(-50%, -50%); background: url(heart.png); cursor: pointer; } .heart-line { background-position: right; transition: background 1s steps(28); } <div class="card"> <div class="top"> <div class="year">{{m.Year}}</div> <div class="heart1"></div> </div> </div> -
Attribute Error (Django) when creating survey forms
Here are my models: class Survey(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Question(models.Model): title = models.CharField(max_length=100) content = models.TextField() survey = models.ForeignKey(Survey, on_delete=models.CASCADE) I create a view for adding a question to a survey. The user is on a survey view when they have the opportunity to create a question, like here: class SurveyQuestionCreateView(LoginRequiredMixin, CreateView): model = Question fields = ['title', 'content'] def form_valid(self, form): form.instance.survey = self.request.survey return super().form_valid(form) However, this gives me the error "'WSGIRequest' object has no attribute 'survey'" A question obviously has a survey attributed to it, and it should be importing from the survey that's being viewed. Still I get this error. -
How to solve an admin operational problem in django?
i am working on an django project (website) i started coding 2 months ago and while working with django project i stucked at a problem. Actually, I am learning how to make websites, And when i login to admin it works fine but when i add product then it shows [OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 3.0.6 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\Owner\PycharmProjects\Pyshop\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 Python Executable: C:\Users\Owner\PycharmProjects\Pyshop\venv\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Owner\PycharmProjects\Pyshop', 'C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\Owner\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\Owner\AppData\Local\Programs\Python\Python38-32', 'C:\Users\Owner\PycharmProjects\Pyshop\venv', 'C:\Users\Owner\PycharmProjects\Pyshop\venv\lib\site-packages'] Server time: Wed, 27 May 2020 04:31:07 +0000][1] Please help me with this -
How to continue using my web app as twilio function is running in the background?
I am working on an alert application using Django and the Twilio api to make calls and messages. I am sending close to 2000 calls and messages, using 20 different phone numbers, using a function similar to the one below: def call_number(phone_numbers, message_to_broadcast): # index twilio controls the phone number that the message is being sent from response = VoiceResponse() response.say('Hello. this is a test message ' + message_to_broadcast + 'Goodbye.', voice='alice' ) index_twilio= 0 try: for phones in phone_numbers: client.calls.create(to=phones, from_=numbers['twilio_numbers'][index_twilio], status_callback='https://mywebsite.com//ealert/voicedistribution/', twiml=response) index_twilio = (0 if index_twilio >= 19 else index_twilio+1) except (TwilioRestException): # A generic 400 or 500 level exception from the Twilio API continue When I click on the submit button, my application just keeps loading. I would like to be redirected immediately to my home page and have this function run on the background. My question is: how do I resume using my application, and be redirected immediately, while the server is still making calls and sending messages in the background? Been looking around but I have not been able to find enough. Another question is, is it possible to make this faster instead of running both my functions this way: def main(): call_number(phones, message) …