Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are the next steps after I made a functional Django web app in my personal laptop?
I'm new to programming. What are the general steps a web developer takes after he made a web app or static website using Django in a personal computer? I'm not asking for specifics cause probably is too long, but more general stuff that I can later research myself online. For example: Make a web app in Django. Buy a physical server. Install apache. Buy a domain name or hosting. Bear with me, I'm a noob so probably I listed nonsense, but just trying to ask how its supposed to ask here. For example, if I wanted to make a cake: Get a recipe. Gather the materials/ingredients. Mix ingredients. Place it in oven to bake. Take it out let it cool. Serve to people. I just need the correct path to take, not much the specifics on how to accomplish each path "station". Hope I asked well, thanks guys. -
'str' object has no attribute 'get' attribute error in django
This is the views.py class EditForm(forms.Form): content = forms.CharField(label="content",widget=forms.Textarea,required=True) def edit(request, title): if request.method == "POST": form = EditForm(request.POST) if form.is_valid(): content = form.cleaned_data["content"] util.save_entry(title, content) return render(request, "encyclopedia/page.html", { "title": title, "content": util.get_entry(title) }) else: content = util.get_entry(title) return render(request, "encyclopedia/edit.html", { "form":EditForm(content) }) This is urls.py path("wiki/<str:title>/edit", views.edit, name="edit") This is edit.html % extends "encyclopedia/layout.html" %} {% block title %} Edit {{ title }} {% endblock %} {% block body %} <form action="/wiki/{{ title }}/edit" method="post"> {% csrf_token %} {{ form }} <input type="submit"> </form> {% endblock %} i am getting 'str' object has no attribute 'get' attribute error when i go to the /title/edit route.I am new to django please be elaborate, thanks in advance. -
How to solve this payment to the right user problem
''' Problem description: We have two users objects created with a User class. Each user is a customer in our company. The users are able to send payments to us through their bank account but we don't have an ID for their bank account on record so we don't know which of them is sending us what money. If the two users send payments to us, with an optional memo field, how do we handle matching the payments to the right user? Please describe why you arrived at your solution. ''' How do I solve this problem. Can anyone help me with code ? class User: def __init__(self,first_name,last_name,email,phone): self.first_name = first_name self.last_name = last_name self.email = email self.phone = phone self.owes = 0 self.payments = [] def get_balance(self): total_paid = 0 for paid in self.payments: if "amount" in paid: total_paid += paid.get("amount") balance = self.owes - total_paid return balance user_a = User(first_name="Lionel",last_name="Messi",email="messi@gmail.com",phone="1111111111") user_a.owes = 56 user_b = User(first_name="Cristiano",last_name="Ronaldo",email="ronaldo@gmail.com",phone="2222222222") user_b.owes = 450 print(f"User A's name is {user_a.first_name} {user_a.last_name}, Balance is ${user_a.get_balance()}") print(f"User B's name is {user_b.first_name} {user_b.last_name}, Balance is ${user_b.owes}") print("\n") new_payment_1 = {"type":"Zelle","amount":300,"date":"05-07-2020","memo":"Cristiano Ronaldo 546432"} new_payment_2 = {"type":"Zelle","amount":450,"date":"05-07-2020","memo":""} -
Image upload error from React Form into Django ImageField
I want to update ImageField in my Django model and i am using axios PATCH method for it. Image comes from my Ant Design Form and i save it in my state. Why i cant update my image file as so? Should i format image file differently before sending it to backend? Error that occurs is 400 Bad request. My profile updating form: import React from "react"; import { Form, Input, Button, Select, message, Upload } from "antd"; import {connect} from 'react-redux'; import { UploadOutlined } from '@ant-design/icons'; import axios from "axios"; const FormItem = Form.Item; const { Option } = Select; const success = () => { message.success('Teie profiil on salvestatud edukalt, võite lehte uuendada'); }; class ProfileForm extends React.Component { state = { file: null, }; dummyRequest({ file, onSuccess }) { onSuccess("ok"); } constructor(props) { super(props) this.state = {sport: this.props.profile.sport}; this.handleChange = this.handleChange.bind(this); this.handleFormSubmit = this.handleFormSubmit.bind(this); } handleImageChange(file) { this.setState({ file: file }) console.log(file) }; handleChange(name, value) { this.setState({ [name]: value }); } handleFormSubmit = (event) => { const name = event.target.elements.name.value; const email = event.target.elements.email.value; const location = event.target.elements.location.value; const image = this.state.file.name; console.log(image); const sport = this.state.sport; axios.defaults.headers = { "Content-Type": "application/json", Authorization: this.props.token } const … -
How to parse serializer data in django rest framework
enter image description here I want to parse this so that i can get a list of phase id to run another query for specific reason. this is serializer.data Response. how to parse this to get a list of ids ? -
Django application: UserPassesTestMixin to verify user is the author of posts before allowing access to view?
The goal of my application is to allow users to create posts for their own private account viewing. I'm using a class based view to show the current logged in user their posts. In order to prevent users from being able to see other user's posts, I have a UserPassesTestMixin test_func that iterates through the query set and checks to make sure they are the author of those posts. The problem that I'm having is when there are no posts to display, I receive a 404 error code stating that there is nothing matching the query. I want it to still display the page even when there are no posts available. When I only use the get_queryset function, it works and displays my template without posts, but without having the UserPassesTestMixin and test_func, a user could enter another person's username into the URL and be able to view the other person's account/posts. Here is the code for this class based view in my views.py file: class UserSessionListView(LoginRequiredMixin, UserPassesTestMixin, ListView): model = session template_name = 'programmerjournal/user_sessions.html' context_object_name = 'sessions' paginate_by = 24 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return session.objects.filter(author=user).order_by('-date_added') def test_func(self): user = get_object_or_404(User, username=self.kwargs.get('username')) posts = get_list_or_404(session, author=user) for … -
How can I upload the image file with axios?
Do I need to change the model below to upload images to django restapi? function axmethod(url, method, options) { if (options !== undefined) { var {params = {}, data = {}} = options } else { params = data = {} } return new Promise((resolve, reject) => { const config = { } axios({ url, method, params, data, }).then(res => { resolve(res) }, res => { reject(res) }) }) } please help if i need to add? -
python - django - file descriptors not closing
I have standalone django program which runs a thread that runs every 5 seconds, reads data from DB using django querysey and publishes it to kafka. What is happening is that after certain period of time (3-4 days), I get below error File \"/usr/local/lib/python2.7/dist-packages/kafka/conn.py\", line 239, in recv readable, _, _ = select([self._sock], [], [], timeout) ValueError: filedescriptor out of range in select()", After debugging I found that file descriptors on the system were exhausted. But I don't see any resource leak in the program. Standalone program: from g_notifications import process_once as g thread_event = Event() def process(obj, source, *args): try: while True: obj(*args) thread_event.wait(5) except Exception: thread_event.set() thread_event.clear() def main(): django.setup() thread_g = Thread(target=process, name='g', args=(g, 'g')) thread_g.start() Thread part: import socket from django.db import connection from notification.kafka_publish import KafkaPublisher from settings.common import KAFKA_TOPIC kafka_publisher_g = None def process_once(publisher_type=KafkaPublisher): global kafka_publisher_g try: socket.gethostbyname('mysql') except socket.error: return if kafka_publisher_g is None: kafka_publisher_g = publisher_type() try: notification_objects = list(Notification.objects.all().order_by('id')[:5]) except Exception as exc: log.exception("Unexpected error could not complete database query!") return finally: close_db_connection(connection) error_flag = _publish_notification_and_verify(notification_objects) if error_flag: kafka_publisher_g.close() kafka_publisher_g = None def _publish_notification_and_verify(notification_objects): global kafka_publisher_g error_flag = False for notification_object in notification_objects: message = notification_object.notification_data try: response = kafka_publisher_g.publish(bytes(message)) if … -
How do I create add a domain's configuration file to /etc/apache2/sites-available/ in Apache2?
I'm trying to point a domain (example.com) to an IP address where I have a working website built with Linode and Django. I don't want to change GoDaddy's nameservers (I purchased the domain from GoDaddy), and I was looking for example.com.conf in my /etc/apache2/sites-available/, but I could not find it. How do I get example.com.conf? -
Unable to host in heroku do to excessive errors
I have been trying to host in Heroku for the last week and can't figure out the problem I am facing! The app is deployed and built successfully but when I open the URL it says "Application Error" Then when I run heroku logs I was given with this... 2020-08-21T16:21:04.049609+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2020-08-21T16:21:04.049638+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2020-08-21T16:21:04.136860+00:00 heroku[web.1]: Process exited with status 1 2020-08-21T16:21:04.175715+00:00 heroku[web.1]: State changed from up to crashed 2020-08-21T16:21:11.000000+00:00 app[api]: Build succeeded 2020-08-21T16:25:25.745203+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=kti-bylimra.herokuapp.com request_id=920d0650-de28-4b2f-928d-6a97a46fc0db fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:25:27.248826+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=kti-bylimra.herokuapp.com request_id=3be3c388-44d4-4481-891a-4ccc8ed79c85 fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:25:37.977206+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=kti-bylimra.herokuapp.com request_id=b8ea34c4-2625-47c2-842f-256d727e48de fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:25:38.166373+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=kti-bylimra.herokuapp.com request_id=f095f479-6ec5-4f22-ac97-0d3e499ebc2c fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:25:38.926833+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=kti-bylimra.herokuapp.com request_id=99979365-e018-47f7-9167-2594b7c3eaa9 fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:26:00.656226+00:00 app[api]: Starting process with command `python manage.py migrate` by user najaaznabhan@gmail.com 2020-08-21T16:26:12.645457+00:00 heroku[run.1617]: State changed from starting to up 2020-08-21T16:26:12.745856+00:00 heroku[run.1617]: Awaiting client 2020-08-21T16:26:12.766309+00:00 heroku[run.1617]: Starting process with command `python manage.py migrate` … -
Python Sort by DateTime using list.sort()
I am trying to sort a list of comments by date. They have a date field that contains a datetime object(?) auto-created by Django. Because of how multiple comment-models have been combined in the list, I cannot use Django's built-in .order_by() sorter. Right now I am testing with just 3 comments, but they are already out of order when I sort them. The three datetimes as strings: 2020-08-21 16:17:40.690851+00:00 2020-08-21 15:04:32.315342+00:00 2020-08-21 12:10:21.720688+00:00 The comment models: class MealComment(models.Model): date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date',) class SubComment(models.Model): date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date',) How the list is created and sorted: mealcomments = user.mealcomment.all() subcomments = user.subcomment.all() if mealcomments and subcomments: comments = list() for comment in list(mealcomments): comments.append(comment) for comment in list(subcomments): comments.append(comment) comments.sort(key=lambda a: a.date) The comments are currently sorting into this order (which looks unsorted but is definitely going through the sort function): Aug. 21, 2020, 4:17 p.m. Aug. 21, 2020, 3:04 p.m. Aug. 21, 2020, 12:10 p.m. Why are they not sorting into any particular order, and how can I sort them correctly? -
Django manage.py shell save() doesn't save to postgresql database
I am new to Django. Testing out a simple application (test_cedar_app) with a PostgreSQL database called test_cedar. I have the following model for the application: class answer_key(models.Model): answer_text = models.CharField(max_length=20) def __str__(self): return self.answer_text I made a migration and applied it, and verified in my psql command-line client with \dt that the schema was created properly. I opened the Django command-line client using python manage.py shell and entered the following: ak_1 = answer_key(answer_text='Yes') ak_2 = answer_key(answer_text='No') ak_1.save() ak_2.save() These appeared to save, as the following revealed that the full query set for answer_key contains ak_1 and ak_2: from test_cedar_app.models import answer_key answer_key.objects.all() returned <QuerySet [<answer_key: Yes>, <answer_key: No>]> However, if I then enter the psql command-line (psql test_cedar), and enter the following: SELECT * FROM test_cedar_app_answer_key Nothing appears. Why do my changes not propagate to the database as it appears within the psql command-line tool? -
Issues with Secret Key when deploying Django App to Heroku
I keep getting django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. when trying to deploy my django app to heroku. I'm using python-dotenv and my settings.py file looks like this: import os from dotenv import load_dotenv load_dotenv() SECRET_KEY = os.getenv("DJANGO_SECRET_KEY") And the .env file (which is in my .gitignore file has the DJANGO SECRET KEY stored: export DJANGO_SECRET_KEY=mykeyhere I'm using pipenv if it helps - everything is working fine locally, but heroku doesn't seem to pick up on the variable. Any thoughts? (I also tried adding the secret key as a config variable on the heroku dashboard without success) -
SQLite 3.8.3 or later is required
I am really confused on why it keep saying that I need to be 3.8.3 or higher when I just updated it? https://i.stack.imgur.com/Ojs4n.png -
Why is django allauth redirecting to /accounts/login/?=next/MY_PAGE instead of logging in?
I am attempting to handle user authentication on a site using Django allauth. However, upon entering a username and password and clicking "log in" on my site, I am redirected to /accounts/login/?=next/MY_PAGE and the login page is simply reloaded. I have seen a number of similar questions, and I know that sometimes people run into issues with this when authenticating with socials, but I am not using any form of social authentication. I already have the LOGIN_REDIRECT_URL set to the desired page's URL, and I attempted to create an adapter as follows: class AccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) def get_login_redirect_url(self, request): path = "/news/" return path where get_login_redirect_url should direct the application to the desired page. I have read in other posts that the fact that the next page (in this case "News") isn't being loaded means that allauth is not actually logging me in, and that's why I end up just getting the login page reloaded. Would anyone be able to point me in the right direction? Thanks! -
django_filter: remove 'ordering=' in url when ordering is empty string
How do i remove 'ordering=' from the URL when the ordering dropdown menu is set to None or '----' in this cause, which is the default option. '&ordering=' showing up in url Demo Link filters.py class BrandFilter(django_filters.FilterSet): brand = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple) category = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple) ordering = django_filters.OrderingFilter( choices = ( ('-is_featured', 'Featured'), ('-created_at', 'Date, New to Old'), ('created_at', 'Date, Old to New' ), ), fields = ( ('is_featured', 'featured'), #{model field name, parameter in the URL} ('created_at', 'created'), ('price', 'price'), ), field_labels = { 'is_featured': 'Featured', #{model field name, human readable label} 'created_at': 'Date', 'price': 'Price', } ) class Meta: model = Product fields = ('brand','category') def __init__(self, products= "", category=Category.objects.none(),*args, **kwargs): super(BrandFilter, self).__init__(*args, **kwargs) self.filters['brand'].queryset = Brand.objects.filter(product__in=products).distinct() self.filters['category'].queryset = category -
Django test db schema missing columns present in live db
I'm trying to set up more robust testing for my Django project but upon running python manage.py test I get an error: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block Presumably caused by: postgres_1 | 2020-08-21 16:15:11.365 UTC [441] STATEMENT: CREATE DATABASE "test_postgres" postgres_1 | 2020-08-21 16:15:16.594 UTC [443] ERROR: column memberships_membership.level does not exist at character 151 postgres_1 | 2020-08-21 16:15:16.594 UTC [443] STATEMENT: SELECT "memberships_membership"."id", "memberships_membership"."created_at", "memberships_membership"."modified_at", "memberships_membership"."name", "memberships_membership"."level", "memberships_membership"."stripe_id", "memberships_membership"."active", "memberships_membership"."info", "memberships_membership"."amount", "memberships_membership"."interval", "memberships_membership"."interval_count", "memberships_membership"."currency", "memberships_membership"."desktop_access", "memberships_membership"."past_projects" FROM "memberships_membership" WHERE ("memberships_membership"."active" = true AND "memberships_membership"."info" = 'Default free plan that allows TradePros to view Jobs/Leads but not interact with them or any TradeUser.' AND "memberships_membership"."level" = 1 AND "memberships_membership"."name" = 'Trades') postgres_1 | 2020-08-21 16:15:16.595 UTC [443] ERROR: current transaction is aborted, commands ignored until end of transaction block This is odd because the column is certainly present in the admin dashboard and even upon inspecting the database, we observe that the level column is there: postgres=# \d memberships_membership Table "public.memberships_membership" Column | Type | Collation | Nullable | Default ----------------+--------------------------+-----------+----------+-------------------------------------------------- -- id | integer | | not null … -
wagtail collectstatic is failing
I'm using python 3.7 , wagtail 2.10 After: python manage.py collectstatic I have the errors below. My insite about the issue is that there is a Django related problem about STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' The files not founded must be used by Django admin. Can't figured out until now how to solve the problem. Post-processing 'bootstrap3/css/bootstrap.min.css' failed! ... File "/home/mihai/env_wagtail2/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 93, in hashed_name raise ValueError("The file '%s' could not be found with %r." % (filename, self)) ValueError: The file 'bootstrap3/fonts/glyphicons-halflings-regular.eot' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x7fa45bdc5160>. -
Creating multiple objects with bulk_create() or models.Manager in Django
Let's say I have 2 sports modalities in the Athlete class, each with 7 categories and in each category there are 20 athletes. My goal is to fill out a form with training information about Tactic or Technique or Conditioning, of a specific modality/category, that can populate the 20 athletes at once. I'm only using djando Admin, so I don't have views.py Many websites indicate using bulk_create(), which receives a list as input, to create several objects. Another option seems to be to overwrite the object manager with models.Manager. I would like to know if any of these options apply to buy problem and how I could use them. I hope the information has been clear. Thank you. models.py class Athlete(models.Model): # Modalities BASKETBALL = 'Basketball' VOLLEYBALL = 'Voleyball' MODALITIES = [ (BASKETBALL, 'Basketball'), (VOLLEYBALL, 'Voleyball'), ] # Categories U12 = 'Under 12' U13 = 'Under 13' U14 = 'Under 14' U15 = 'Under 15' U17 = 'Under 17' U19 = 'Under 19' U21 = 'Under 21' CATEGORIES = [ (U12, 'Under 12'), (U13, 'Under 13'), (U14, 'Under 14'), (U15, 'Under 15'), (U17, 'Under 17'), (U19, 'Under 19'), (U21, 'Under 21'), ] id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) modalities = … -
Get data from Django REST Framework into Vue & calling data from different components
I managed to get the data from my Django database into my Vue file. However, as this data will be used in multiple components, I want to make 1 data.js sheet from where I can call the data. Code in data.js file where I want to call the InvoiceData from. export default { name: 'InvoiceData', data(){ return { InvoiceData: [], } }, async created(){ var response = await fetch('http://127.0.0.1:8000/api/invoices/'); this.InvoiceData = await response.json(); },} My Code in component.vue file <template> <div> {{InvoiceData}} </div> </template> <script> import InvoiceData from "../../data" export default { name: 'componentfile', </script> when the codes are together in one Vue file, it works. <template> <div> {{InvoiceData}} </div> </template> <script> export default { name: 'InvoiceData', data(){ return { InvoiceData: [], } }, async created(){ var response = await fetch('http://127.0.0.1:8000/api/invoices/'); this.InvoiceData = await response.json(); },} </script> What am I doing wrong? Thanks for the help! -
Regex in django templates to match bold
im trying to define a function that renders Markdown, from .md formatted files, into HTML safely. Note: In this example i only try to bold text. What i got so far: def query(request, title_name): content = util.get_entry(title_name) bold_pattern = re.compile('[(\*\*|__)]{2}(?P<bold_text>[\w\s]+)[(\*\*|__)]{2}') bold_matches = re.findall(bold_pattern, content) #Returns list for match in bold_matches: for word in content: word = word.replace(match, f'<strong>{word}</strong>') word = mark_safe(word) return render(request, ".../entry.html",{ "content": content, ... }) The issue: It doesn't mark_safe the substring or it doesn't appear. {% extends "encyclopedia/layout.html" %} {% block title %}{{ title }}{% endblock title %} {% block body %} {{content}} <p>Edit this page <a href="{% url 'edit' title %}">here</a></p> {% endblock body %} -
Sqlite unable to recognise token ":"
I'm using Django Admin to create a port, here's how the model of the port is class Port(models.Model): interface = models.CharField(max_length=100) description = models.CharField(max_length=100) duplex = models.CharField(max_length=100) link_status = models.CharField(max_length=100) protocol_status = models.CharField(max_length=100) speed = models.CharField(max_length=100) access_vlan = models.CharField(max_length=100) native_vlan = models.CharField(max_length=100) admin_mode = models.CharField(max_length=100) mode = models.CharField(max_length=100) switchport = models.CharField(max_length=100) switchport_negotiation = models.CharField(max_length=100) trunking_vlans = ArrayField(models.TextField(blank=False), blank=False) switch = models.ForeignKey(Switch, on_delete=models.CASCADE) class Meta: unique_together = (("interface", "switch"),) def __str__(self): return f"Interface {self.interface}, description: {self.description}, duplex: {self.duplex}, " \ f"link_status:{self.link_status}, protocol_status: {self.protocol_status}, speed: {self.speed}, " \ f"access_vlan:{self.access_vlan}, native_vlan: {self.native_vlan}, " \ f"trunking_vlans: {self.trunking_vlans}, switch: {self.switch} " in the Django admin, when I use this: https://imgur.com/a/Tw79VDF as an input, the following error appears: File "/home/dias/ssc-webapp/ssc_django/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: unrecognized token: ":" During handling of the above exception, another exception occurred: ... File "/home/dias/ssc-webapp/ssc_django/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/operations.py", line 141, in _quote_params_for_last_executed_query return cursor.execute(sql, params).fetchone() sqlite3.InterfaceError: Error binding parameter 12 - probably unsupported type. -
Django Database Model Terminal issue
I've tried to run Django database with this command (python manage.py makemigrations) And I've got an issue I wish you can help me to handle this problem, Thank you very much Terminal -
AttributeError: module 'MySQLdb.constants.FIELD_TYPE' has no attribute 'JSON' while migrating in Django
I do not know in what way solve this error. Any hints? I have simple Django projects and receive this error when try to do python3 manage.py migrate. This is related to any programming error in app or this is possible there is any error related to installation of mysql and completeness of its packages? Maybe there is any error in manage.py file? Or maybe this is case in not compatible version of Django and mysql? Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/home/anna/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/anna/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/anna/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/anna/.local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/anna/.local/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/anna/.local/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/anna/.local/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/anna/.local/lib/python3.7/site-packages/django/db/models/base.py", line 122, … -
Django multiple requests made when passing variable
I am trying to create an update form from an inlineformset and include a button that checks the next record. Here is my view: def update_challenges(request, challenge_id): challenge_ids = list(ChallengeModel.objects.values_list('id', flat=True)) next_index = challenge_ids.index(int(challenge_id)) + 1 next_challenge_id = challenge_ids[next_index] challenge = ChallengeModel.objects.get(pk=challenge_id) RoundFormset = inlineformset_factory(ChallengeModel, Round, fields=('index','description'),extra=0, widgets = { 'description': TextInput(), 'index':NumberInput() }) VarFormset = inlineformset_factory(ChallengeModel, Var, fields=('name',),extra=0) if request.method == 'POST': round_formset = RoundFormset(request.POST, instance=challenge) var_formset = VarFormset(request.POST, instance=challenge) if round_formset.is_valid() and var_formset.is_valid(): round_formset.save() var_formset.save() return redirect('update_challenges', challenge_id=challenge.id) round_formset = RoundFormset(instance=challenge) var_formset = VarFormset(instance=challenge) return render(request, 'drinking_game/update_challenges.html', {'round_formset':round_formset, 'var_formset':var_formset, 'challenge_id':challenge_id, 'next_challenge_id':next_challenge_id}) And here is the button I use for going to the next challenge:<button class="home-play-btn" onclick="location.href='{% url 'update_challenges' next_challenge_id %}'">Next challenge</button> However, when I check the output of my console, a new get request to the old url gets made right after the new request. This looks the following: [21/Aug/2020 15:29:23] "GET /update_challenges/221/ HTTP/1.1" 200 6373 [21/Aug/2020 15:29:23] "GET /update_challenges/220/ HTTP/1.1" 200 6339 The url path for this view is path('update_challenges/<challenge_id>/', views.update_challenges, name='update_challenges') What goes wrong that the old request is also made? Thanks.