Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotation of Similar Article Tags In Django Admin
I want to display similar tags count in the Django admin Tag section like this: name | posts ------------------------------- business | 3 Currently in my Tag table I have something this. This different posts that have similar tags to them. name | post_id ------------------------------- business | 1 business | 2 business | 3 My models class Posts(models.Model): title = models.CharField(max_length=500, verbose_name='Post Title') class Tags(models.Model): name = models.CharField(max_length=500) date_created = models.DateField(auto_now_add=True, verbose_name='Date Created') last_modified = models.DateField(auto_now=True, verbose_name='Last Modified') post = models.ForeignKey(Posts, on_delete=models.CASCADE, verbose_name='Posts') I have this in the admin.py class TagAdmin(admin.ModelAdmin): list_display = ('name', 'post_count', 'date_created', 'last_modified') search_fields = ['name'] ordering = ['id'] readonly_fields=('date_created', 'last_modified') def post_count(self, obj): return obj.post_count def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate(post_count=Sum("post")) return queryset admin.site.register(Tags, TagAdmin) This is how it looks in the admin panel name | post_count ------------------------------- business | 3 business | 3 business | 3 How do I achieve only displaying one instance of a tag name with all the posts that have that tag instead of the repetition above and instead the desired outcome below? name | posts ------------------------------- business | 3 -
Drf: authenticating without the USERNAME_FIELD
` extended from: Drf how to: simple-jwt authenticating without the USERNAME_FIELD I was tryna figure out how to authenticate a user with a field that is not set as the USERNAME_FIELD and faced some issues, it lets me input in the correct data fields, but it never authenticates I'm using this snippet from the previous questions answer: class MyTokenStudentSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['student_id'] = serializers.CharField(required=False) # self.fields['password'] = serializers.CharField(write_only=True, required=True) self.fields['password'] = PasswordField(trim_whitespace=False) username_field = 'student_id' auth_fields = ['student_id'] produces { "detail": "No active account found with the given credentials" } any modifications would be greatly appreciated. -
Annotate on Generic Relation
apologies, I'm fairly sure there's a way to do this with Q filters/F expressions but I can't quite get it right. I have a Generic Versioning Model, and several versionable models: class Version(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to=VERSIONED_OBJECTS_LIMIT ) object_id = models.PositiveIntegerField() source = GenericForeignKey("content_type", "object_id") object_uri = models.TextField(max_length=1024, null=True) version_number = models.IntegerField(default=1) is_latest = models.BooleanField(default=1) class Dataset(models.Model): versions = GenericRelation(Version) class DataModel(models.Model): versions = GenericRelation(version) I figured this approach would be wise as we version quite a few models. However, I'm struggling to create the annotation/query that would retrieve for me all model instances annotated by the latest version. For a given instance it is of course trivial, but I can't figure it out for the model writ large. latest_datasets = Dataset.objects.annotate(uri = version.uri).filter(versions__islatest=True) Obviously returns all datasets, since by design each dataset has at least one "is_latest" Version. Apologies -- maybe this is just bad db design, but I do think making "Version" a Generic abstraction made sense for our use case. So, if theres a way to get all instances of Model_x with the appended uri WHERE version.is_latest = True, I would love to know how. Thanks in advance, sorry for my ignorance. -
How to get user with POST Ajax call in django?
I'm trying to realize comments for products on site with AJAX, but faced the problem that I can not receive an author of comment in this case of code: new_comment.author = request.user I got this error in this case: "Exception Value: Object of type User is not JSON serializable" But without user I got parameters from back-end and have result 200, like this author "" content "dasda" created_at "2021-12-31T07:34:12.766Z" product 4 So the question how to be "author = request.user" can be serialized? Or it is can be realised only with Django Rest Framework? (I don't have experience in DRF, but know some things in theory) Can somebody advice please? def ajax_receiver(request): product = Product.objects.get(id=4) is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if request.method == 'POST' and is_ajax and request.user.is_authenticated: form = UserCommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) #new_comment.author = request.user new_comment.product = product new_comment.save() comment_info = { "author": new_comment.author, "content": new_comment.content, "created_at": new_comment.created_at, "product": product.id, } return JsonResponse({"comment_info": comment_info}, status=200) else: return JsonResponse({"success": False}, status=400) -
Django Python - .get function returns DoesNotExist matching query does not exist
I've been really stumped on the following issue.. I am trying to retrieve an order number after taking a stripe payment. Stripe returns a payment is completed and everything is working, on the success page I call the function below to retrieve the order number from the session table. The wierd thing is, even though it gives me a DoesNotExist error, it does find the right order number and returns the order number and all data is actually served. Function def get_order_number(session_id): order = session_order_table.objects.get(session_id=session_id) order_number = order.order_number return order_number success page function def success_page(request): summary_orders = None session_id = request.session["USER_SESSION_ID"] order_number = get_order_number(session_id) print('###############SESSION_ID######################') print(session_id) print(order_number) online_order = My_Cart_History_Model.objects.filter(order_number=order_number) .... error 1820bd97c5"\n },\n "type": "payment_intent.succeeded"\n}' 1x 777 test (Quality:VVS, Size: L, Color: yellow-gold) C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py:1416: RuntimeWarning: DateTimeField My_Cart_History_Model.transaction_date received a naive datetime (2021-12-31 07:21:41) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" Internal Server Error: /cart/my_webhook_view/ Traceback (most recent call last): File "C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\akram\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\pwl-server\django\t7\cart\views.py", line 533, in my_webhook_view fulfil_order(request=request ,payload=payload,session=session) File "D:\pwl-server\django\t7\cart\views.py", line 594, in fulfil_order return … -
changing primary key from username to uuid on POSTGREQL gives: django.db.utils.ProgrammingError: column "username" is in a primary key
I have a postgresql database and I am making a migration to switch my pk from username to uuid. I already made a data migration file where I add a uuid to every row in my model it worked fine on sqlite but when I was testing it on postgresql I got an error. The error was "django.db.utils.ProgrammingError: column "username" is in a primary key" I am not sure where to begin to debug this thing. Here is the model, data migration, migration, and stack trace of the error: # models.py class UserInformation(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) username = models.CharField(max_length=100, unique=True, blank=True, null=True) # data migration 42 import uuid from django.db import migrations def set_uuid_for_all_user_information(apps, schema_editor): UserInformation = apps.get_model('accounts', 'UserInformation') for userInformation_user in UserInformation.objects.all(): userInformation_user.uuid = uuid.uuid4().hex userInformation_user.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0041_auto_20211227_2113'), ] operations = [ migrations.RunPython(set_uuid_for_all_user_information), ] # migration 43 (this is where the postgresqsl error occurs) trying to change pk from username to uuid from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('accounts', '0042_auto_20211229_2319'), ] operations = [ migrations.AlterField( model_name='userinformation', name='user', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='auth.user'), ), migrations.AlterField( model_name='userinformation', name='username', field=models.CharField(blank=True, … -
How to apply multiple field options to one field in Django
I'm using Django, is there a way to apply foreign key and ChartField to one field at the same time? Sometimes I want to allow the user to enter a value that is not in the foreign key. I've googled for a long time and found various ways, but I can't find a solution. Please help. [models.py] class Supporting(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=False, null=True) -
How to insert field in table from database using python script and print it in html page or print python result in html directly using pycharm django
so i'm new to django and python, i'm having a mini project to make a decision support system. so i already build a website, already connect it to the database and have the python code, now i'm having difficulties to push the result/target in python to existing field in table dataresponden from database and print it to html. the flow is like this: an user input a data (nama, umur, gejala, komorbid) and stored it in table dataresponden(nama, umur, gejala, komorbid, hasil_rekomendasi) in database. user didn't input hasil_rekomendasi because hasil_rekomendasi is the result from the decision support system. in python, i read query dataresponden as dataset, i set hasil_rekomendasi as a target and calculate the remaining column. so i get the result i want named hasil_prediksi, now the problem is i want to push hasil_prediksi to column hasil_rekomendasi in table dataresponden because when user input the data they don't input hasil_rekomendasi. after that i want print it in my html page. i tried this Execute a python script on button click but didn't work, i tried to use update table but it didn't work too, this is the code in hasil.html : <div class="modal-body text-center pb-5" id="hasilrekomendasi"> <div class="container"> <div … -
Github actions deploy django application to elastic beanstalk
I'm simply trying to deploy my django application to elastic beanstalk using github actions but keep getting these error: Warning: Environment update finished, but health is Red and health status is Degraded. Giving it 30 seconds to recover... Warning: Environment still has health: Red and health status Degraded. Waiting 19 more seconds before failing... Warning: Environment still has health: Red and health status Degraded. Waiting 8 more seconds before failing... Error: Deployment failed: Error: Environment still has health Red 30 seconds after update finished! This it the code I'm using below: name: AWS Deploy on: push: branches: - test-main-branch jobs: build: runs-on: ubuntu-latest steps: - name: Checkout source code uses: actions/checkout@v2 - name: Generate deployment package run: zip -r deploy.zip . -x '*.git*' - name: Get timestamp uses: gerred/actions/current-time@master id: current-time - name: Run string replace uses: frabert/replace-string-action@master id: format-time with: pattern: '[:\.]+' string: "${{ steps.current-time.outputs.time }}" replace-with: "-" flags: "g" - name: Deploy to EB uses: einaregilsson/beanstalk-deploy@v20 with: aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }} aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} application_name: project-pit environment_name: project-pit-cloud version_label: 12345 region: ap-southeast-2 deployment_package: deploy.zip - name: Deployed! run: echo App deployed The application is showing up in my s3 bucket but I still get a Degraded health … -
Get name From extra_field django allauth and save to name field on Users Model
I have Users Model like this from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db.models.signals import pre_save from django.dispatch import receiver # Create your models here. from users.manager import UserManager class Users(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # Setting field USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] # Setting Object Manager objects = UserManager() class Meta: abstract = False I need to get {"name": "Feri Lukmansyah",} from social_account model (from django allauth) and save to name field from Users Model, I already use signal like this from django.dispatch import receiver from allauth.socialaccount.signals import social_account_added, social_account_updated from .models import Users @receiver(social_account_added) @receiver(social_account_updated) def add_name_from_google(request, sociallogin, **kwargs): pass but I don't know how to use signal on django allauth, everybody can help me fix this problem? or have any example to use django allauth signal? -
How to Implement Django Loggers/Logging in the code?
As i am a newbie. I'm working on Django Rest Framework using ModelViewset. Can anyone help me out in explaining or understanding, how to implement the loggers/logging? Even i'm using the Django OAuth2 toolkit for authentication, so how can log a username & password? -
action.php page not found and failure to send data to MariaDB table
This is kind of a double question since the first issue correlates to the latter. My first issue is that the action attribute on my html form directing towards a file called action.php results in a 404 error during form submission and I am not sure how I would create a path in urls.py that would lead to the code in action.php being executed. My second issue is that once the first issue is fixed, action.php is supposed to send the data from the answers submitted in my html form into a MariaDB database I have configured. However, some of the code I have written is appearing on my webpage which leads me to believe that data wont be sent to my database table. Any help would be greatly appreciated. DATA TREE urls.py from django.shortcuts import render from django.http import HttpResponse def say_hello(request): context = {"name": "DUDE"} return render(request, "hello_page.php", context) hello_page.php {% extends "base.php" %} {% block content %} <?php //include('config.php'); $host = "localhost"; $username = "USER"; $password = "PASS"; $database = "donations"; $dbconnect=mysqli_connect($host, $username, $password, $database); if ($dbconnect->connect_error) { die("Database connection failed: " . $dbconnect->connect_error); } ?> <html> <h1> WHATS UP {{name}}!!!!!</h1><br> <form action="action.php" method = "POST"> <label … -
Image Display in Django
ERRORS: <class 'blog.admin.CategoryAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'image_tag', which is n ot a callable, an attribute of 'CategoryAdmin', or an attribute or method on 'blog.Category'. System check identified 1 issue (0 silenced). -
django redirects to non existing url
Two days ago I created a django project and it worked all right. But, now when I am working on another django project still when I run server it's redirecting me to the older project. I am using different virtual environment for both of them. Even after deleting the old one the issue is not resolved. Thanks in advance. -
Creating an autocomplete search form (probably w/ jQuery) using a comprehensive (huge) movie title list (Django project) from IMDBPy
I am in the early stages of retrieving IMDB data via the Python package IMDBPy (their site) (proj github). I have been referring to this nice IMDBPy implementation for help with aspects of what I'm doing here. Several of the queries that I'm using generate datasets that come in "nested dictionary" form, e.g. 'movie_1':{'title':'One Flew Over the Cuckoo's Nest', 'director': 'Milos Forman'...}. My early version of the title retrieval takes this form in VIEWS.PY: def index(request): imdb = IMDb() test_movies = {} for i in range(1100000, 1100015): test_movies[f'movie_{i}'] = imdb.get_movie(f'{i}') context = { 'test_movies':test_movies, } return render(request, 'index.html', context) And this in my INDEX.HTML template: <div id="search-part1"> <ul> {% for k1,v1 in test_movies.items %} {% for k2,v2 in v1.items %} {% if 'title' in k2 %} <li>{{v2}}</li> {% endif %} {% endfor %} {% endfor %} </ul> <input type="text" name="search" id="search" class="form-control" placeholder="Search for Movies"> </div> Right now, the HTML is just to show that I *can generate a list of these titles. My actual implementation of the dropdown from the search bar (via jQuery's Autocomplete), is a little further down the road at this point. Here is an example that they provide of the Autocomplete in action, in the … -
django how to set form ModelChoiceField drop down to required if specific value is selected from the previous drop down
I have the following form: class RegisterForm(UserCreationForm): company_role = forms.ModelChoiceField(queryset=CompanyRole.objects, empty_label='Select Company Role') office = forms.ModelChoiceField(queryset=Office.objects, empty_label='Select Office', required=False) location = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Select Location", required=False) class Meta: model = User fields = ["first_name", "last_name", "username", "email", "password1", "password2", "company_role", "location", "office"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['office'].queryset = Office.objects.none() Is it possible through this form to set office ModelChoiceField drop down to be required if the first item (id 1) is selected in company_role ModelChoiceField drop down and also if second item (id 2) is selected in company_role ModelChoiceField drop down then set location ModelChoiceField drop down to be required? If so would greatly apprecaite some help on how to do so. Thanks in advance -
Send both POST and GET parameters in Django test client
I've created a view created in Django which accepts both GET and POST parameters. When trying to test it using django-rest-framework test APIClient, it's not clear how I can send both GET and POST parameters. self.client.post has a signature as follows: self, path, data=None, format=None, content_type=None, follow=False, **extra Using data would probably send POST data, is there any workarounds for this? -
How to query and update nested JSON data in Django
I have below class defined to do statistics for voting system. class FormPage(AbstractForm): submission_stats = models.JSONField(null=True, editable=False) Now, I have submission_stats in below format: [ { "id":4, "label":"checkboxes", "choices":[ { "content":"option-A", "num_vote":0, "user_list":[ ] }, { "content":"option-B", "num_vote":0, "user_list":[ ] }, { "content":"option-C", "num_vote":0, "user_list":[ ] } ] }, { "id":7, "label":"Radio Button", "choices":[ { "content":"option-1", "num_vote":0, "user_list":[ ] }, { "content":"option-2", "num_vote":0, "user_list":[ ] }, { "content":"option-3", "num_vote":0, "user_list":[ ] } ] } ] When I receive a vote submission, I want to update num_vote and user_list field in this JSONField accordingly. How to query and update elements in nested JSONField data please ? -
Cloning existing python project anyjson setup command error
I have this project shared to me via github, after I clone and run this steps: python -m venv ./venv venv\scripts\activate pip install -r requirements.txt in pip install -r: It gives me this errors: error in anyjson setup command: use_2to3 is invalid. ERROR: Could not find a version that satisfies the requirement anyjson==0.3.3 (from versions: 0.1, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.2.5, 0.3, 0.3.1, 0.3.2, 0.3.3) ERROR: No matching distribution found for anyjson==0.3.3 Here is what inside the requirements.txt amqp==1.4.9 anyjson==0.3.3 billiard==3.3.0.23 celery==3.1.25 certifi==2019.3.9 chardet==3.0.4 dj-database-url==0.5.0 Django==2.0.13 django-appconf==1.0.3 django-axes==1.7.0 django-celery==3.2.2 django-compressor==2.2 django-crispy-forms==1.7.2 django-dynamic-formsets==0.0.8 django-polymorphic==2.1.2 django-reversion==3.0.1 djangorestframework==3.7.4 ffs==0.0.8.2 gunicorn==20.0.4 idna==2.7 Jinja2==2.10 kombu==3.0.37 letter==0.5 MarkupSafe==1.1.1 opal==0.14.2 Pillow==8.1.0 psycopg2==2.8.6 python-dateutil==2.7.5 pytz==2019.1 rcssmin==1.0.6 requests==2.20.1 rjsmin==1.0.12 six==1.12.0 urllib3==1.24.3 whitenoise==4.1.4 mysqlclient==2.0.3 cryptography==3.4.1 Already tried removing anyjson from requirements.txt but still gives me error. What Am I missing here? -
Why we must have form with model in django, why model alone can't work?
In django: request.POST--1-->corresponding_SQL--2-->database . And we use form = ModelForm(requst.POST).save() to save a form to database. The form has well designed "consructor", which take value and key inside queryDict(request.POST) and convert them to data inside the instance of form one by one. I guess this 'Form' object is kindof an agent,which can be easily stored to database (like above) and can be rendered out in HTML using form.as_p(). Actually I wonder why we don't put all the functions of a form into the model itself, I think that is more intuitive than create a new class called "form". We could just use model.save() or model.is_valid() or model.as_p(), emmm why bother to design a new class called form? -
LISTAR EL NUMERO DE CATEGORIA CONSULTADAS DENTRO DE UNA ITERACION
Hola, buenas noches ¿Por favor me podrían ayudar con la siguiente duda? En mi vista cree una consulta que me lista todas las categorías exceptuando una, esas categorías las itere en un bucle For en la página html, el modelo Categoría está relacionado con otro que se llama Post, mi intención ahora es que en la parte que dice (N. Post) de mi template, se liste el número de Post que tiene esa categoría. ¿Como podría implementar esa consulta en mi Views? ¿Puedo directamente dentro de ese bucle For contar las categorías y ahí mismo listarlas en la etiqueta ? [1]: https://i.stack.imgur.com/Q4jhU.jpg [2]: https://i.stack.imgur.com/LxxcX.jpg [3]: https://i.stack.imgur.com/kmC6m.jpg [4]: https://i.stack.imgur.com/nz1PV.jpg -
Deploying django app to EC2.. server is running through docker compose, but times out when trying to reach the host?
First time deploying an application, so bear with me... I have my EC2 instance up. I have my code on the server with docker-compose being run (docker-compose -f docker-compose.yml up), and the logs say that it is running with Starting development server at http://0.0.0.0:8000/ I have my allowed_hosts to specify the ec2 instance. When i attempt to hit the server in my browser, im getting nothing. It times out, and no logs in the ec2 instance. Any idea of what im potentially missing? -
Django Channels: WebSocket messages are not sent in production
I have Django server which uses WebSockets to send real time updates to web clients. This is all running perfectly fine locally (with manage.py runserver), but in production I am running into the problem that most messages are simply not sent at all. I test this by opening two browsers, making a change in one, which should then be reflected in the other browser. Like I said, this all works locally, but not in production. In production some WebSocket messages are sent by the server and received by the web client, but maybe 20% or so? The rest is just not sent at all. # /websocket/__init__.py import logging from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from djangorestframework_camel_case.util import camelize logger = logging.getLogger("django.server.ws.critical-notes") def ws_send(model_type, action, model_data, user_ids): logger.info(f"Called ws_send for model {model_type}, action {action}, user_ids: {user_ids}") channel_layer = get_channel_layer() for user_id in user_ids: group_name = f"user-{user_id}" async_to_sync(channel_layer.group_send)( group_name, { "type": "send.data", # this calls Consumer.send_data "data": {"type": model_type, "action": action, "model": camelize(model_data)}, }, ) # /websockets/consumers.py import logging from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.db import database_sync_to_async from django.db import close_old_connections from knox.auth import TokenAuthentication logger = logging.getLogger("django.server.ws.critical-notes") class Consumer(AsyncJsonWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.group_name = None @database_sync_to_async … -
Django Rest Framework Patch Request with Image Upload
I'm trying to make an endpoint for updating the profile image of a user. However, whenever I make the PATCH request, the profile_image field does not change to the uploaded file. I've tested on postman using form-data and I get the response "Updated completed" but the profile_image field remains null. views.py class ProfileImageView(APIView): parser_classes = [MultiPartParser, FormParser] def patch(self, request, user_email, format=None): print(request.data) profile = ProfileImage.objects.get(user_email=user_email) serializer = ProfileImageSerializer(profile, data=request.data, partial=True) data = {} if serializer.is_valid(): serializer.update(profile, request.data) data["response"] = "Update completed." data["user_email"] = user_email data["profile_image"] = ( profile.profile_image.url if profile.profile_image else None ) return Response(serializer.data) data["response"] = "Wrong parameters." return Response(data) models.py class ProfileImage(models.Model): user_email = models.CharField(max_length=255) profile_image = models.ImageField( upload_to="uploads/", height_field=None, width_field=None, null=True, blank=True, ) serializers.py class ProfileImageSerializer(serializers.ModelSerializer): class Meta: model = ProfileImage fields = ["user_email", "profile_image"] urls.py urlpatterns = [ path("api-auth/", include("rest_framework.urls")), path("admin/", admin.site.urls), path("register/", RegisterView.as_view(), name="register"), path("login/", obtain_auth_token, name="login"), path("log/add/", LogView.as_view(), name="log"), path("log/all/", LogView.getAll, name="logall"), path("log/<str:user_email>/", LogView.getByUserEmail, name="logbyuseremail"), path("profile/<str:user_email>/", ProfileView.profile, name="profile"), path("edit-profile/<str:user_email>/", ProfileView.as_view(), name="profile"), path( "profile-image/<str:user_email>/", ProfileImageView.getProfileImage, name="profile-image", ), path( "edit-profile-image/<str:user_email>/", ProfileImageView.as_view(), name="profile-image", ), path("events/", EventView.as_view(), name="events"), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) enter image description here -
How to pass data from one View function to another for a multi-step form?
I'm currently working a developing a Hockey League management website. The feature I am currently working on, is entering a "Game Report". This is where a score keeper enters in all the details for that game once it has been completed. The Game report feature itself requires 3 steps to be completed. Selecting the game for which you want to enter the report for. A form which populates the roster of both teams, with a checkbox for each player to mark off if they played in the game. In addition, there is 2 separate formsets to add players for either team if they aren't already on the roster. The final part of the game report, where you enter in the goals, penalties, and the game results. Where the goals and penalties are formsets, and the game results are a simple model form. The confusion comes from the fact that data from the prior step, is required for the current step. SelectGame View (Step 1) - No issues here @login_required(login_url="/login/") def selectGame(request): games = Game.objects.all().values( 'iceSlot__date', 'homeTeam__name', 'awayTeam__name', 'id' ) context = {'games': games} return render(request, "home/select-game.html", context) Transition From Step 1 to Step 2 occurs in select-game.html (Also No issue) …