updated code so that "now i want to teach class form" don't require email or captcha if the user is logged in#535
Conversation
WalkthroughThe changes update the course creation flow by adapting form behavior based on user authentication. An Changes
Sequence Diagram(s)sequenceDiagram
participant U as User
participant F as TeachForm
participant T as Template
participant V as View
U->>F: Initialize form (pass user)
alt User is authenticated
F-->>F: Remove "email" and "captcha" fields
F->>T: Render form without "email"/"captcha"
else Not authenticated
F->>T: Render complete form
end
U->>V: Submit form data
V->>F: Validate form (without strict email matching)
V->>U: Return confirmation or error response
Tip ⚡💬 Agentic Chat (Pro Plan, General Availability)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
@coderabbitai |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainI'll help you fix the failing tests. First, let's examine what's failing to understand the issue better. 🏁 Script executed: Length of output: 947 Let's examine the relevant test files that might be affected by our changes to the 🏁 Script executed: Length of output: 18665 Let's look at the test_forms.py file as well to see if it has any tests related to the TeachForm class: 🏁 Script executed: Length of output: 31707 Now, let's look at the view code to understand how the TeachForm is being initialized with the user parameter: 🏁 Script executed: Length of output: 1464 Let's check the actual TeachForm implementation in web/forms.py to understand what we need to fix: 🏁 Script executed: Length of output: 65555 Fixing the Failing TestsLooking at the code and tests, I found that the main issue is in the Here's how I'll fix it: flowchart TB
A["Issue: Tests Failing"]
A --o B["Fix `teach` view: pass user to form"]
A --o C["Update tests to match new behavior"]
B --o D["Pass request.user to TeachForm constructor"]
B --o E["Also pass user on GET requests"]
C --o F["Update test_post_authenticated_email_mismatch"]
C --o G["Ensure other tests handle auth users correctly"]
@IITI-tushar I've identified the issue with the tests. The problem is that in the Here's what needs to be fixed:
# For POST requests
form = TeachForm(request.POST, request.FILES, user=request.user)
# For GET requests
form = TeachForm(user=request.user)
I've created a plan to fix these issues - the changes will be implemented by another agent. The fixes ensure that the form works correctly by having the email and captcha fields removed for authenticated users, and updates the tests to match this new behavior. Would you like me to explain any part of the solution in more detail? ⏳ Preparing changes... |
|
@coderabbitai |
|
A summary of the edits CodeRabbit can apply:
A plan of each step that CodeRabbit will take in order to execute the edits for each file (with inline rough draft snippets): ✏️ web/views.pyModify the POST request handling to pass the user parameter to the TeachForm constructor: def teach(request):
"""Handles the course creation process for both authenticated and unauthenticated users."""
if request.method == "POST":
form = TeachForm(request.POST, request.FILES, user=request.user)
if form.is_valid():
# Extract cleaned data
email = form.cleaned_data.get("email", request.user.email if request.user.is_authenticated else None)
course_title = form.cleaned_data["course_title"]
course_description = form.cleaned_data["course_description"]
course_image = form.cleaned_data.get("course_image")
preferred_session_times = form.cleaned_data["preferred_session_times"]This change passes the user parameter to the TeachForm constructor, which will cause the form to remove the email and captcha fields for authenticated users as defined in the TeachForm.init method. Modify the GET request handling to also pass the user parameter to the TeachForm constructor: else:
# GET request
initial_data = {}
if "subject" in request.GET:
initial_data["course_title"] = request.GET.get("subject")
form = TeachForm(user=request.user, initial=initial_data)This ensures that the form is properly initialized with the user parameter for GET requests as well, maintaining consistency between GET and POST handling. Update the email extraction in the form.is_valid() block to handle the case where the email field might not be present for authenticated users: # Extract cleaned data
email = form.cleaned_data.get("email", request.user.email if request.user.is_authenticated else None)This ensures that for authenticated users, where the email field is removed from the form, we still have access to the user's email for further processing. ✏️ web/tests/test_teach.pyRename the test to better reflect its new purpose and update the test logic: @patch("captcha.fields.CaptchaField.clean", return_value="PASSED")
def test_form_prepopulates_authenticated_user_email(self, mock_captcha):
"""Test that for authenticated users, the form uses the user's email and doesn't include email/captcha fields"""
self.client.login(username="testuser", password="testpass123")
form_data = {
"course_title": "Test Course",
"course_description": "This is a test course",
"preferred_session_times": (timezone.now() + timezone.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S"),
"flexible_timing": True,
}
response = self.client.post(self.teach_url, {**form_data, "course_image": self.get_test_image()})
# Should redirect to course detail page since the form should be valid
self.assertEqual(response.status_code, 302)
self.assertTrue(response.url.startswith("/courses/"))
# Verify that a course was created with the authenticated user's email
course = Course.objects.get(title="Test Course")
self.assertEqual(course.teacher, self.user)This updated test verifies that when an authenticated user submits the form without an email field (since it's removed for authenticated users), the form is still valid and creates a course using the user's account email. ✏️ web/views.pyLocate the POST branch inside the teach() function and change the form initialization from
to
. Locate the GET branch inside the same function and change the form initialization from
to
. ✏️ web/tests/test_teach.pyRename the test function from
to
to better reflect its updated purpose. Remove the
and
keys from the
dictionary, as these fields should now be omitted for authenticated users. Update the assertions: Instead of expecting a 200 status code and specific form error messages, assert that the response status code is
(indicating a successful redirect). Then retrieve the created course and verify that
matches
. ✏️ web/views.pyReplace the POST branch where TeachForm is instantiated:
if request.method == "POST":
form = TeachForm(request.POST, request.FILES, user=request.user)
if form.is_valid():
# Extract cleaned data
email = form.cleaned_data["email"]
course_title = form.cleaned_data["course_title"]
course_description = form.cleaned_data["course_description"]
course_image = form.cleaned_data.get("course_image")
preferred_session_times = form.cleaned_data["preferred_session_times"]
…
Replace the GET branch instantiation:
else:
# GET request
initial_data = {}
if "subject" in request.GET:
initial_data["course_title"] = request.GET.get("subject")
form = TeachForm(user=request.user)
✏️ web/tests/test_teach.pyUpdate the test by replacing the previous version with:
@patch("captcha.fields.CaptchaField.clean", return_value="PASSED")
-def test_post_authenticated_email_mismatch(self, mock_captcha):
+def test_form_prepopulates_authenticated_user_email(self, mock_captcha):
"""Test POST for authenticated user with mismatched email"""
- self.client.login(username="testuser", password="testpass123")
-
- form_data = {
- "course_title": "Test Course",
- "course_description": "This is a test course",
- "email": "different@example.com",
- "preferred_session_times": (timezone.now() + timezone.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S"),
- "flexible_timing": True,
- "captcha": "dummy",
- }
-
- response = self.client.post(self.teach_url, {**form_data, "course_image": self.get_test_image()})
-
- self.assertEqual(response.status_code, 200)
- self.assertIn("form", response.context)
- self.assertIn("The provided email does not match your account email", str(response.context["form"].errors))
+ self.client.login(username="testuser", password="testpass123")
+
+ form_data = {
+ "course_title": "Test Course",
+ "course_description": "This is a test course",
+ "preferred_session_times": (timezone.now() + timezone.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S"),
+ "flexible_timing": True,
+ }
+
+ response = self.client.post(self.teach_url, {**form_data, "course_image": self.get_test_image()})
+
+ # For authenticated users, the updated view should produce a redirect (302)
+ self.assertEqual(response.status_code, 302)
+
+ # Verify that the course is created using the authenticated user's email
+ course = Course.objects.get(title="Test Course")
+ self.assertEqual(course.teacher, self.user)
A summary of the context that CodeRabbit is considering across the codebase:
|
|
Tip For best results, initiate chat on the files or code changes. @IITI-tushar Here's the copyable code to fix the failing tests: 1. First, update the
|
|
@coderabbitai |
|
Tip For best results, initiate chat on the files or code changes. @IITI-tushar I see the issue in your tests. The error is happening because we're trying to access Here's the fix for def teach(request):
"""Handles the course creation process for both authenticated and unauthenticated users."""
if request.method == "POST":
form = TeachForm(request.POST, request.FILES, user=request.user)
if form.is_valid():
# Extract cleaned data - safely get email or use user's email if authenticated
email = form.cleaned_data.get("email", None)
if email is None and request.user.is_authenticated:
email = request.user.email
course_title = form.cleaned_data["course_title"]
course_description = form.cleaned_data["course_description"]
course_image = form.cleaned_data.get("course_image")
preferred_session_times = form.cleaned_data["preferred_session_times"]
# Handle duplicate course titles
if Course.objects.filter(title=course_title).exists():
form.add_error("course_title", "A course with this title already exists")
return render(request, "teach.html", {"form": form})
# Create the course
course = Course.objects.create(
title=course_title,
subject=course_title,
description=course_description,
time=preferred_session_times,
teacher=request.user if request.user.is_authenticated else None,
email=email
)
# Process course image if provided
if course_image:
course.image = course_image
course.save()
# Handle redirects based on user authentication status
if request.user.is_authenticated:
return redirect("courses:detail", pk=course.id)
else:
# For unauthenticated users, redirect to email verification
return redirect("account_email_verification_sent")
else:
# GET request
initial_data = {}
if "subject" in request.GET:
initial_data["course_title"] = request.GET.get("subject")
form = TeachForm(user=request.user, initial=initial_data)
return render(request, "teach.html", {"form": form})The key changes:
This change handles the case where the email field is removed for authenticated users while maintaining backward compatibility for unauthenticated users.✏️ Learnings added
|
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (2)
web/tests/test_teach.py(1 hunks)web/views.py(2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
web/tests/test_teach.py (1)
web/models.py (1)
Course(233-327)
web/views.py (1)
web/forms.py (1)
TeachForm(883-980)
🪛 Ruff (0.8.2)
web/tests/test_teach.py
133-133: Missing return type annotation for public function test_form_for_authenticated_user
Add return type annotation: None
(ANN201)
133-133: Missing type annotation for function argument mock_captcha
(ANN001)
133-133: Unused method argument: mock_captcha
(ARG002)
135-135: Possible hardcoded password assigned to argument: "password"
(S106)
147-147: Use a regular assert instead of unittest-style assertEqual
Replace assertEqual(...) with assert ...
(PT009)
151-151: Use a regular assert instead of unittest-style assertEqual
Replace assertEqual(...) with assert ...
(PT009)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Run Tests
- GitHub Check: build-and-test
🔇 Additional comments (6)
web/views.py (3)
1110-1110: Pass user parameter to TeachForm for conditional field removal.This change is essential for the form to know whether the current user is authenticated, allowing it to conditionally remove the email and captcha fields for logged-in users as implemented in the TeachForm's
__init__method.
1113-1115: Handle email retrieval when field may not exist for authenticated users.This correctly implements the form's new behavior by:
- Using
get()with a default value to safely retrieve the email field (which may not exist for authenticated users)- Falling back to the user's email when the field is missing but the user is authenticated
This ensures the email is properly captured regardless of whether the field is present or not.
1252-1252: Pass user to TeachForm in GET requests.This change ensures the TeachForm correctly removes email and captcha fields for authenticated users when the form is initially rendered, not just on form submission. This provides a consistent user experience from the start.
web/tests/test_teach.py (3)
133-135: Good update to align test name with new functionality.The method rename from
test_post_authenticated_email_mismatchtotest_form_for_authenticated_useraccurately reflects the new behavior being tested, and the updated docstring clearly explains the purpose of the test.🧰 Tools
🪛 Ruff (0.8.2)
133-133: Missing return type annotation for public function
test_form_for_authenticated_userAdd return type annotation:
None(ANN201)
133-133: Missing type annotation for function argument
mock_captcha(ANN001)
133-133: Unused method argument:
mock_captcha(ARG002)
135-135: Possible hardcoded password assigned to argument: "password"
(S106)
137-142: Correctly removed email and captcha fields for authenticated user test.This reflects the updated behavior where authenticated users don't need to provide email or captcha fields in the form. The test data properly focuses on only the required fields for an authenticated user submission.
146-152: Appropriate assertion updates for the new behavior.The assertions have been correctly updated to:
- Check for a successful redirect (302 status code) instead of an error case
- Verify that a course is created with the authenticated user as the teacher
This properly tests that the form submission works without email/captcha for authenticated users, aligning with the PR objective.
🧰 Tools
🪛 Ruff (0.8.2)
147-147: Use a regular
assertinstead of unittest-styleassertEqualReplace
assertEqual(...)withassert ...(PT009)
151-151: Use a regular
assertinstead of unittest-styleassertEqualReplace
assertEqual(...)withassert ...(PT009)
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
web/tests/test_teach.py (1)
133-135: 🧹 Nitpick (assertive)Good test case renaming and docstring update.
The test has been appropriately renamed from
test_post_authenticated_email_mismatchtotest_form_for_authenticated_user, and the docstring clearly explains the new test purpose.The
mock_captchaparameter is flagged as unused, but it's still needed because the@patchdecorator injects it. Consider adding a comment to clarify this:@patch("captcha.fields.CaptchaField.clean", return_value="PASSED") -def test_form_for_authenticated_user(self, mock_captcha): +def test_form_for_authenticated_user(self, mock_captcha): # mock_captcha is needed for the patch decorator🧰 Tools
🪛 Ruff (0.8.2)
133-133: Missing return type annotation for public function
test_form_for_authenticated_userAdd return type annotation:
None(ANN201)
133-133: Missing type annotation for function argument
mock_captcha(ANN001)
133-133: Unused method argument:
mock_captcha(ARG002)
135-135: Possible hardcoded password assigned to argument: "password"
(S106)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (4)
web/forms.py(1 hunks)web/templates/teach.html(1 hunks)web/tests/test_teach.py(1 hunks)web/views.py(2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
web/tests/test_teach.py (1)
web/models.py (1)
Course(233-327)
web/views.py (1)
web/forms.py (1)
TeachForm(883-980)
🪛 Ruff (0.8.2)
web/forms.py
949-949: Missing return type annotation for special method __init__
Add return type annotation: None
(ANN204)
949-949: Missing type annotation for *args
(ANN002)
949-949: Missing type annotation for **kwargs
(ANN003)
web/tests/test_teach.py
133-133: Missing return type annotation for public function test_form_for_authenticated_user
Add return type annotation: None
(ANN201)
133-133: Missing type annotation for function argument mock_captcha
(ANN001)
133-133: Unused method argument: mock_captcha
(ARG002)
135-135: Possible hardcoded password assigned to argument: "password"
(S106)
147-147: Use a regular assert instead of unittest-style assertEqual
Replace assertEqual(...) with assert ...
(PT009)
151-151: Use a regular assert instead of unittest-style assertEqual
Replace assertEqual(...) with assert ...
(PT009)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: build-and-test
- GitHub Check: Run Tests
🔇 Additional comments (6)
web/views.py (3)
1110-1110: Necessary change to pass user parameter to TeachForm.The form now correctly receives the current user as a parameter, allowing it to conditionally display fields based on authentication status.
1113-1115: Good defensive programming to handle authenticated users.This change safely handles the case where the email field is removed for authenticated users. Using
get()with a default value avoids KeyError exceptions, and falling back to the user's email ensures the field is always populated.
1252-1252: Consistent initialization of form for both GET and POST requests.The form is now correctly initialized with the user parameter when rendering the form initially, ensuring consistency between form display and submission logic.
web/templates/teach.html (1)
49-52: Good implementation of conditional field rendering.The template now correctly skips rendering the email and captcha fields for authenticated users. This provides a better user experience by hiding fields that aren't needed and aligns perfectly with the changes in the form class.
web/tests/test_teach.py (2)
137-144: Correctly omitted email and captcha from form data.The test data no longer includes the email and captcha fields, which accurately represents the form data that an authenticated user would submit with the updated form.
146-151: Good assertions and verification logic.The test now correctly expects a successful redirect (status code 302) and verifies that a course is created with the authenticated user as the teacher. This validates the key functionality being implemented.
🧰 Tools
🪛 Ruff (0.8.2)
147-147: Use a regular
assertinstead of unittest-styleassertEqualReplace
assertEqual(...)withassert ...(PT009)
151-151: Use a regular
assertinstead of unittest-styleassertEqualReplace
assertEqual(...)withassert ...(PT009)
…mail or captcha if the user is logged in (alphaonelabs#535) * done * fixed
fixes: issue#526
Summary by CodeRabbit