Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Will Django Migrations result in conflicts with distributed version control?
I'm planning to work on a Django project with several collegues via Gitlab. Let developer A create a model on branch feature/model_a: class model_A(models.Model): field_A = models.CharField(...) Dev A runs makemigrations, receives a migration file (something like 0001_migration) and commits and pushes it to the remote repository. Now Dev B develops another model on feature/model_b: class model_B(models.Model): field_B = models.CharField(...) and also creates a migration file (Django will call this migration file also 0001_migration!). So given that the two developers develop their models on separate branches (which I believe is a good and recommended practice), they will now have a repository conflict. What are recommended and proven ways to prevent this problem? -
How can i Register and Login In The Same Page in Django?
i would like to have both my login form and my registration form on the same page within the same template, so i would like to have them under one view function but i am not too sure on how i can do that, here is my code. Views.py def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) == "Register" if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request,"Account was Created for " + user) context = {'form':form} return render(request,'login.html',context) def login(request): if request.method == "POST": if request.POST.get('submit') == 'Login': username = request.POST.get('username') password = request.POST.get('password1') user = authenticate(request, username=username, password=password) if user is not None: login(request,user) return redirect('shop.html') else: messages.info(request, 'Wrong Username or password') context = {} return render(request,'shop.html',context) login.html <div class="formBx"> <form method="POST",name="Login",value="Login"> {% csrf_token %} <h2>Sign In</h2> {{form.username}} {{form.password1}} <input type="submit" name="submit" value="Login"> <p class="signup">Don't have an Account?<a href="#" onclick="toggleForm();">Sign Up.</a></p> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} </form> </div> </div> <div class="user signUpBx"> <div class="formBx"> <form method="POST" value="Register"> {% csrf_token %} <h2>Create an account</h2> {{form.username}} {{form.email}} {{form.password1}} {{form.password2}} <input type="submit" name="submit" value="Register"> <p class="signup">Already Have an Account?<a href="#" onclick="toggleForm();">Sign In.</a></p> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} … -
What is the Django way to add data to a form that is already instantiated?
Suppose you have a ModelForm to which you have already binded the data from a request.POST. If there are fields of the ModelForm that I don't want the user to have to fill in and that are therefore not shown in the form (ex: the user is already logged in, I don't want the user to fill a 'author' field, I can get that from request.user), what is the 'Django' way of doing it ? class RandomView(View): ... def post(self, request, *args, **kwargs): form = RandomForm(request.POST) form.fill_remaining_form_fields(request) ### How would you implement this ??? if form.is_valid(): ... I have tried adding the fields to the form instance (ex: self.data['author'] = request.user) but given its a QueryDict it is immutable so it clearly isn't the correct way of doing this. Any suggestions ? -
mssql-django - TCP Provider: Error Code 0x2746 (10054) (SQLDriverConnect)
Have a dockerized Django 4 app running on Docker (Debian10) host, connecting to a network SQL Server 2012 (running on Windows10 box) in development environment. Cannot get same docker image to connect to SQL Server 2014 (running on Server2012 VM) in staging environment. Can see on SQL Server event logs that DB connection is successful: Login succeeded for user '<USERNAME>'. Connection made using SQL Server authentication. [CLIENT: <DB_SERVER_IP>] However, Django errors out with the following Stack Trace: alluradjango-web-1 | self.connect() alluradjango-web-1 | File "/home/djangouser/.local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner alluradjango-web-1 | return func(*args, **kwargs) alluradjango-web-1 | File "/home/djangouser/.local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect alluradjango-web-1 | self.connection = self.get_new_connection(conn_params) alluradjango-web-1 | File "/home/djangouser/.local/lib/python3.9/site-packages/mssql/base.py", line 329, in get_new_connection alluradjango-web-1 | conn = Database.connect(connstr, alluradjango-web-1 | django.db.utils.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)') requirements.txt: asgiref==3.5.0 backports.zoneinfo==0.2.1 Django==4.0.3 django-allow-cidr==0.4.0 django-environ djangorestframework==3.13.1 mssql-django==1.1.2 netaddr==0.8.0 pyodbc==4.0.32 pytz==2021.3 sqlparse==0.4.2 black==22.1.0 pylint==2.12.2 pylint-django==2.5.2 python-decouple==3.6 pre-commit==2.17.0 djangouser@2062b37a0a3a:~$ odbcinst -j unixODBC 2.3.6 DRIVERS............: /etc/odbcinst.ini SYSTEM DATA SOURCES: /etc/odbc.ini FILE DATA SOURCES..: /etc/ODBCDataSources USER DATA SOURCES..: /home/djangouser/.odbc.ini SQLULEN Size.......: 8 SQLLEN Size........: 8 SQLSETPOSIROW Size.: 8 /etc/odbc.ini is empty djangouser@2062b37a0a3a:~$ cat /etc/odbcinst.ini [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server … -
Why Heroku redirect my site on HTTPS with no SSL setup?
I've deploy my django website on heroku. After adding my custom domain, when i try to access to http://www.example.com it redirect me to https://www.example.com and i get this message ERR_SSL_UNRECOGNIZED_NAME_ALERT I haven't add any SSL certificate, is it normal that i'm redirect to HTTPS? -
Django cannot access dictionary, returns blank
When I try and access a simple dict in django: {'The Batman': [{'datetime': datetime.datetime(2022, 4, 1, 11, 0, tzinfo=datetime.timezone.utc), 'id': '1'},{'datetime': datetime.datetime(2022, 4, 1, 11, 0, tzinfo=datetime.timezone.utc), 'id': '1'}], 'Ice Age': [{'datetime': datetime.datetime(2022, 4, 1, 11, 0, tzinfo=datetime.timezone.utc), 'id': '1'}, {'datetime': datetime.datetime(2022, 4, 1, 11, 0, tzinfo=datetime.timezone.utc), 'id': '1'}]} I use this loop to access the keys: {% for film in data %} ...Code here {% endfor %} but then when I go to access the values, it returns nothing. I am accessing the values as follows: {% for showing in film.key %} ...Code here {% endfor %} I am printing out the data to my screen every time, so I know there is data there, because the headings register too. Unsure what is happening or what I am doing wrong. Fairly new to Django so pls be nice :) -
How can I do addition in django views?
When I go to add multiple integer variables, I'm getting below error. Now, what has to do? Error: TypeError at / unsupported operand type(s) for +: 'method' and 'int' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: TypeError Exception Value: unsupported operand type(s) for +: 'method' and 'int' views: total_frontend_order = request.user.user_frontend_order.all().count total_backend_order = request.user.user_backend_order.all().count total_complete_website_order = request.user.user_complete_website_order.all().count a = total_frontend_order+1 -
Getting TypeError when trying to upload to s3 from heroku
Error: TypeError at /accounts/work_feed/upload/1 sequence item 0: expected str instance, NoneType found Im getting this error when I try to upload an image from my django app on heroku to an aws s3 bucket. My settings.py looks like: ROOT_URLCONF = 'ClassTrail.urls' DATABASES = { 'default': dj_database_url.config() } STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' django_heroku.settings(locals()) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('BUCKET_NAME') S3_URL = 'https://%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_QUERYSTRING_AUTH = False (I cut out some irrelevant bits of settings.py) My app works perfectly with postgres and aws locally, but when I run the website on heroku, everything works except for uploading files to aws. Thank you for any help! -
Django ModelViewSet. How to merge two perfrom methods/functions?
Is there a way to merge perform methods/functions? The view uses ModelViewSet. I have two functions perform_create and perform_update that do the same thing and I wondered could I merge them somehow? Body { "title": "1 Title", "description": "1 Description", "author": { "id": 1 } } View class ArticleView(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer def perform_create(self, serializer): author = get_object_or_404(Author, id=self.request.data['author']['id']) return serializer.save(author=author) def perform_update(self, serializer): author = get_object_or_404(Author, id=self.request.data['author']['id']) return serializer.save(author=author) Serializers class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = AuthorSerializer() class Meta: model = Article fields = '__all__' -
File access issues with django and gunicorn
I’m wondering how file permissions work on Django. I have created a file debug.log where I want my logging to output. Its permissions look like this -rw-rw-r-- 1 ubuntu ubuntu 0 Apr 3 19:16 debug.log I have a Django superuser called ubuntu who I think should have rw access to this file based on what this says. However, when I run systemctl status gunicorn, I get File "/usr/lib/python3.8/logging/config.py", line 570, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'file' Which according to this post Should mean that either the file doesn’t exist, or my user doesn’t have access. The filename has value os.path.join(BASE_DIR, 'debug.log'). And if I print that value out, I get /home/ubuntu/ACE/rangr/debug.log which is where the debug.log file is. Does anyone know why my django user doesn't have access to debug.log or why django thinks the file doesn't exist? -
Update django app every 30 days after deployement
I have build a DJango app and now I want to deploy it. As this is very first time for me to deploy django app so I am confused on what platform to use. I am thinking to use AWS. could someone help me and answer my questions for few things. Please don't judge me for my questions. How to deploy my app on AWS? How will I connect my app to the database and where will I get the Database? If after deploying the app I need to update the code (say I add one more table in DB(class in models.py)) so will I be able to retain my existing data ? what changes needs to be done in production environment as in hiding the secret key or DB connection string or Email settings? The third point is very important as I need to update my app every month. Thanks in advance and please let me know if someone can help me out in this. -
Django more-admin-filters in Filt
I created my admin filtering with multi dropdown filter. The problem with Multidropdown filter I can choose the names that i want. How to solve this problem? models.py Tee_name = models.CharField(max_length=255, verbose_name=_("Tea Name")) admin.py list_filter = [ ("tea_name",MultiSelectDropdownFilter) ] -
compile django app to executable using PyInstaller
I am trying to compile a Django app as an executable. I know that this is not best practice - the app was built as a server app running on log in, but now the app shall be used by Users who shall not have access to the server. The challenge is now to make the app installable in such a way that the average Windows user is capable of double-clicking the exe and type in the url in a browser of their choice. I am working on Linux with Django 3.2.7, Python 3.8 and PyInstaller 4.1 (I know that I must compile on a windows platform for Windows OS to run the exe, but I first wanted to try using PyInstaller on my OS). Now, when starting the app, it complains not to find a specific folder in the dist directory, which when I add the demanded folder, changes to file not found "settings.pyc". ".pyc" files are compiled Python files, but I cannot grep the filename, so PyInstaller did not even create it. I executed the PyInstaller command in the directory where the first "mysite" is located. I also tried to separately hook the "myapp" folder by adding a … -
Variable 'html' referenced before assigned: UnboundLocalError
This code previously worked and outputed what I wanted on the website, but then this error happened from django.shortcuts import render import json def get_html_content(fplid): import requests API_KEY = "eb9f22abb3158b83c5b1b7f03c325c65" url = 'https://fantasy.premierleague.com/api/entry/{fplid}/event/30/picks/' payload = {'api_key': API_KEY, 'url': url} for _ in range(3): try: response = requests.get('http://api.scraperapi.com/', params= payload) if response.status_code in [200, 404]: break except requests.exceptions.ConnectionError: response = '' #userdata = json.loads(response.text) return response.text def home(request): if 'fplid' in request.GET: fplid = request.GET.get('fplid') html = get_html_content(fplid) return render(request, 'scrape/home.html', {'fpldata': html}) here is my views.py file. I think I assigned html before, but I'm not sure, how is it referenced before it renders. I added scraperapi for many ip addresses, as I thought maybe I was banned from the api. I am unsure what is going on. <body> <h1>Enter Your FPL id </h1> <form method="GET"> <label for="fplid"> </label> <input type="text", name="fplid", id="fplid"> <br> <input type="submit" value="Submit" /> </form> <h3> {{fpldata}}</h3> </body> This is the home.html file if it is relevant -
Django update/render bloghome page using the form filter elements
Let us say I have an HTML page (blogHome.html) with different elements like this one, <div class="container-fluid bg-light"> <div class="container"> <div class="row sm-3 justify-content-center"> <div class="col md-3 p-3 d-flex justify-content-center"> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="vegetarian" name="vegetarian" checked> <label for="vegetarian">Vegetarian</label> </div> </div> <div class="col md-3 p-3 d-flex justify-content-center"> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="nonvegetarian" name="nonvegetarian" checked> <label for="nonvegetarian">Non-Vegetarian</label> </div> </div> <div class="col md-3 p-3 d-flex justify-content-center"> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="vegan" name="vegan" checked> <label for="vegan">Vegan</label> </div> </div> </div> </div> <div class="container"> <a href="#" class="btn btn-primary" type="submit">Get Filter Values</a> </div> <div class="container my-3"> <div class="row"> {% for post in allPosts %} <div class="col-md-3"> <!-- HERE --> <div class="card mb-4 shadow-sm"> <!-- HERE --> <img class="card-img-top" src='{% static "img/tamilnadu.jpg" %}' alt="Card image cap"> <div class="card-body"> <strong class="d-inline-block mb-2 text-primary">Article by {{post.author}} ({{post.views}} views)</strong> <h3 class="card-title"><a class="text-dark" href="/blog/{{post.slug}}"></a>{{post.title}}</h3> <div class="mb-1 text-muted">{{post.timestamp}}</div> <p class="card-text mb-auto"><div class="preview">{{post.content|safe|truncatechars:200}}</div></p> </div> </div><!-- /.card --> </div><!-- /.col-md-3 --> {% if forloop.counter|divisibleby:4 %} </div> <div class="row">{% endif %} {# HERE #} {% endfor %} </div><!-- /.row --> This is how my urls.py looks like urlpatterns = [ path('', views.blogHome, name="bloghome"), ] My models.py file class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=255) author = models.CharField(max_length=25) content … -
How solve in vue model
Access to XMLHttpRequest at 'http://127.0.0.1:8000/graphene' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource -
How to get the json key and value in Django's Templating language?
I'm trying to build a website for tv series using Django framework, I put in the models.py all kinds of details about that show and a JSONField to define the number seasons and episodes in each season. Example: { "s1" : 15 , "s2" : 25 , "s3" : 23} I made a dropdown in the template where the series is playing so the user can select the episode the problem starts when I try to access the values of the keys in the JSON object passed. I tried that: {% for key in show.episodes %} Season {{key}} {% for value in show.episodes[{{key}}] %} {{ value }} {% endfor %} {% endfor %} But it this is not working, I assume that the [] thing in js doesn't work in Django's Templating language, but I cant seem to find any solution. -
I am trying to run the command 'heroku run bash' but it is giving following error ;
(trying to deploy a django project and trying to create tables and superuser) (env) D:\CRM>heroku run bash » Warning: heroku update available from 7.53.0 to 7.60.1. Running bash on ⬢ quiet-waters-22939... done Error: connect ECONNREFUSED 52.3.44.61:5000 my postgresql settings are : listen_addresses = '*' # what IP address(es) to listen on; # comma-separated list of addresses; # defaults to 'localhost'; use '*' for all # (change requires restart) port = 5432 # (change requires restart) IS the above error due to the fact that the port number in the postgresql = 5432 and the error is on port number 5000? if yes , the do i need to change the port number OR is it something else ? another similar errors : (env) D:\CRM>heroku pg:psql » Warning: heroku update available from 7.53.0 to 7.60.1. --> Connecting to postgresql-clean-14965 psql: error: connection to server at "ec2-54-157-79-121.compute-1.amazonaws.com" (54.157.79.121), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? ! psql exited with code 2 $ heroku run python manage.py migrate » Warning: heroku update available from 7.53.0 to 7.60.1. Running python manage.py migrate on ⬢ quiet-waters-22939... done Error: connect ECONNREFUSED 54.156.98.218:5000 -
502 Bad Gateway during during user Django user registration on ubuntu,ngnix
I am working on a django project,the registration view works pretty fine on development on my localhost and heruko test server.But when I switch to production using Ubuntu and Ngnix.I get a 502 bad gateway error whenever a user tries to submit the registration form.Other forms e.g the login is perfect.The only problem is the registration part on production. def registerView(request): form = UserCreationForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.is_active = False # user.set_unusable_password() user.save() current_site = get_current_site(request) mail_subject = 'Activate your account.' email_var = { 'user' : user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } to_email = form.cleaned_data.get('email') from_email = settings.DEFAULT_FROM_EMAIL html_content = render_to_string('confirm_email.html',email_var) text_content = strip_tags(html_content) msg_html = render_to_string('confirm_email.html',email_var) send_mail(mail_subject,msg_html,from_email, [to_email],html_message=msg_html) return render(request,'email_redirect.html',{}) context = { 'form':form, } return render(request,'register.html',context) class ActivateAccount(View): def get(self, request, uidb64, token, *args, **kwargs): try: uid = urlsafe_base64_decode(uidb64).decode() user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return render(request,'confirm_sucess.html',{}) else: return render(request,'confirm_error.html',{}) forms.py class UserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': ('The two password fields didn’t match.'), } password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ['firstname','email',] def clean_password2(self): … -
while connecting mysql database [closed]
System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection connection = Database.connect(**conn_params) File "C:\ProgramData\Anaconda3\lib\site-packages\MySQLdb_init_.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\MySQLdb\connections.py", line 185, in init super().init(*args, **kwargs2) MySQLdb._exceptions.ProgrammingError: (1102, "Incorrect database name 'd:\final year (5th sem)\final year project\code\final_year_project\brickcafe'") -
Start async event loop with n tasks from sync function
In my Django webapp, I have a method that emails all subscribers a notification whenever a new blog post is created. Executing this method is time-consuming, and I'm trying to make it more efficient with python's asyncio library. My motive is not just for the sake of performance, but also because my web server times out any form submissions that take longer than 300 seconds (including the form that creates new blog posts, and hence emails all subscribers). I'm assuming it's not wise to make a timeout window much longer than that, and I know that executing this method is only going to take more time the more subscriber objects I have. So, I'm thinking some sort of async solution is the way to go. Anyways, enough rambling. Here is what I've tried: # This method gets called every time a new blog post (agpost) is saved for the first time. def send_subs_new_post_email(agpost): logger.info("Setting up async emailing loop...") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(setup_async_sub_email_loop(agpost, loop)) loop.close() # Add a send_email task in the event loop for every subscriber. async def setup_async_sub_email_loop(agpost, loop): for i, sub in enumerate(Subscriber.objects.all()): domain = Site.objects.get_current().domain absolute_path = 'https://' + str(format(domain)) # Build unsubscribe link token = … -
Daphne does not running after server restart on digitalOcean
After Creating daphne.service file. I run following command. ''' sudo systemctl daemon-reload sudo systemctl start daphne.service sudo systemctl status daphne.service ''' output: is showing Active(Running) enter image description here When I run again the last command just after it is showing: failed (Result exit-code) enter image description here I also checked log of daphne.service. It says that env/bin/python : can't open file and env/bin/daphne : No such file or directory. -
Extending functionality of an external package's View in Django
I'd like to extend the functionality of a specific View in an external package that initiate SSO authentication with SAML. the package: https://github.com/zibasec/django-saml2-pro-auth I have a service that uses the package and logs in users from multiple apps, right now the sso login works but i'd like to extend specifically the SsoView - view of the package such that I could save the referrer so I know where to return to when I finish the authentication I guess it happens because I call the view from within my View and the namespace of my urls is not the same as theirs - in theirs the app_name is indeed saml2_pro_auth. Is there a better way to extend the View or solve this issue? Thanks in advance I tried to write a view in my app's views that uses the SsoView but it gives me "saml2_pro_auth is not a registered namespace" error of django when it is trying to reverse a url. The package's view class SsoView(GenericSamlView): http_method_names = ["get", "head"] def get(self, request, *args, **kwargs): # SP-SSO start request auth = kwargs["saml_auth"] req = kwargs["saml_req"] return_to = req["get_data"].get(REDIRECT_FIELD_NAME, app_settings.SAML_REDIRECT) or "/" saml_request = auth.login(return_to=return_to) response = redirect(saml_request) response.set_signed_cookie( "sp_auth", auth.get_last_request_id(), salt="saml2_pro_auth.authnrequestid", … -
Invalid Default value for entry that doesnt exist
I am looking at this example in the Django docs to add a field to my CustomUser which has just a few choices. I added this class StringInstrument(models.TextChoices): VIOLIN = 'VIO', _('Viool') ALT_VIOLIN = 'AVI', _('Alt Viool') CELLO = 'CEL', _('Cello') DOUBLE_BASS = 'CON', _('Contrabas') OTHER = 'OTH', _('Anders') working_on = models.CharField( max_length=3, choices=StringInstrument.choices, default=StringInstrument.OTHER ) which gave me the following traceback when migrating: File "...\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "...\Python39\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "...\Python39\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "...\Python39\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "...\Python39\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "...\Python39\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "...\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "...\Python39\lib\site-packages\django\db\migrations\executor.py", line 131, in migrate state = self._migrate_all_forwards( File "...\Python39\lib\site-packages\django\db\migrations\executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "...\Python39\lib\site-packages\django\db\migrations\executor.py", line 248, in apply_migration state = migration.apply(state, schema_editor) File "...\Python39\lib\site-packages\django\db\migrations\migration.py", line 131, in apply operation.database_forwards( File "...\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 108, in database_forwards schema_editor.add_field( File "...\Python39\lib\site-packages\django\db\backends\mysql\schema.py", line 105, in add_field super().add_field(model, field) File "...\Python39\lib\site-packages\django\db\backends\base\schema.py", line 641, in add_field self.execute(sql, params) File "...\Python39\lib\site-packages\django\db\backends\base\schema.py", line 192, in execute cursor.execute(sql, params) return super().execute(sql, params) File "...\Python39\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File … -
Please is there a way to make my django page pagination with with Quiz App?
my problem is on page pagination on Django quiz App when I click on the next question, its will unselect the previous selected input and only one answer will be recorded. Form Codes: <form action="/calculate_marks" onsubmit="return saveAns()" enctype="multipart/form-data" id ='quiz' method="POST"> {% csrf_token %} <input type="hidden" name="csrfmiddlewaretoken" value="C24rUotmdHawVQJL3KrqiWxvti8UffOFYUc8TRbZtLt36AVLdP3jbkzUVe3beRAa"> <h1>{{course}} Quiz</h1><br> <h4>Number of Questions in the Quiz: {{q_count}}</h4> <hr> <p>pages {{page_obj}}</p> <hr> {% for q in page_obj %} <!-- <h6 style="text-align: right;">[marks {{q.marks}}]</h6> --> {% if q.img_quiz.url %} <div class="text-center" ><img src="{{q.img_quiz.url}}" width="100%" height="300px" alt=""> </div><br> {% endif %} <div style="border: 2px dotted green;" class="container shadow-lg mb-1 bg-white rounded"> <p class="d-flex" style="overflow-x: auto; white-space: pre-wrap; font-size: 20px;font-family: sans-serif;" > {{ q.question }}</p> {% if q.marks %} <h6 style="text-align: right;">[marks {{q.marks}}]</h6> {% endif %} </div> {% if q.option1 %} <div class="card-header shadow-lg mb-1 bg-white rounded"> <input type="radio" name="{{forloop.counter}}" id="{{q.option1}}" value="Option1"> <label for="option1"> {{q.option1}}</label><br> </div> {% endif %} {% if q.option2 %} <div class="card-header shadow-lg mb-1 bg-white rounded"> <input type="radio" name="{{forloop.counter}}" id="{{q.option2}}" value="Option2"> <label for="option2">{{q.option2}}</label><br> </div> {% endif %} {% if q.option3 %} <div class="card-header shadow-lg mb-1 bg-white rounded"> <input type="radio" name="{{forloop.counter}}" id="{{q.option3}}" value="Option3"> <label for="option3">{{q.option3}}</label><br> </div> {% endif %} {% if q.option4 %} <div class="card-header shadow-lg mb-1 bg-white rounded"> <input type="radio" name="{{forloop.counter}}" …