奖惩表分开

This commit is contained in:
pzc-x99 2025-03-01 23:16:07 +08:00
parent bb3d03b26d
commit ca826214df
10 changed files with 358 additions and 69 deletions

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
/static
/upload_file /upload_file
/generate_paper /generate_paper
*.pyc *.pyc

View File

@ -1,7 +1,7 @@
from django import forms from django import forms
from .models import EcUser, ContactInfo, SchoolInfo, AcademicInfo, HealthInfo, SelfEvaluation from .models import EcUser, ContactInfo, SchoolInfo, AcademicInfo, HealthInfo, SelfEvaluation
from .models import HobbiesInterests, SocialPractice, FamilyInfo, AwardsPunishments from .models import HobbiesInterests, SocialPractice, FamilyInfo, AwardsInfo, PunishmentsInfo
class BaiscInfoForm(forms.ModelForm): class BaiscInfoForm(forms.ModelForm):
class Meta: class Meta:
@ -105,15 +105,21 @@ class FamilyInfoForm(forms.ModelForm):
} }
# AwardsPunishments 表单 # AwardsPunishments 表单
class AwardsPunishmentsForm(forms.ModelForm): class AwardsInfoForm(forms.ModelForm):
class Meta: class Meta:
model = AwardsPunishments model = AwardsInfo
fields = ['award_name', 'award_date', 'award_organization', 'discipline_date', 'discipline_issue', 'discipline_outcome'] fields = ['award_name', 'award_date', 'award_organization']
labels = { labels = {
'award_name': '奖项名称', 'award_name': '奖项名称',
'award_date': '获奖日期', 'award_date': '获奖日期',
'award_organization': '颁奖机构', 'award_organization': '颁奖机构',
}
class PunishmentsInfoForm(forms.ModelForm):
class Meta:
model = PunishmentsInfo
fields = ['discipline_date', 'discipline_issue', 'discipline_outcome']
labels = {
'discipline_date': '处分日期', 'discipline_date': '处分日期',
'discipline_issue': '处分问题', 'discipline_issue': '处分问题',
'discipline_outcome': '处分结果', 'discipline_outcome': '处分结果',
@ -129,7 +135,8 @@ g_models = {
'hobbies_interests': HobbiesInterests, 'hobbies_interests': HobbiesInterests,
'social_practice': SocialPractice, 'social_practice': SocialPractice,
'family_info': FamilyInfo, 'family_info': FamilyInfo,
'awards_punishments': AwardsPunishments 'awards_info': AwardsInfo,
'punishments_info': PunishmentsInfo
} }
g_form_classes = { g_form_classes = {
@ -141,5 +148,6 @@ g_form_classes = {
'hobbies_interests_form': HobbiesInterestsForm, 'hobbies_interests_form': HobbiesInterestsForm,
'social_practice_form': SocialPracticeForm, 'social_practice_form': SocialPracticeForm,
'family_info_form': FamilyInfoForm, 'family_info_form': FamilyInfoForm,
'awards_punishments_form': AwardsPunishmentsForm 'awards_info_form': AwardsInfoForm,
'punishments_info_form': PunishmentsInfoForm,
} }

View File

@ -0,0 +1,91 @@
# Generated by Django 4.2.19 on 2025-03-01 14:45
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ec_user', '0015_alter_hobbiesinterests_extracurricular_activities_and_more'),
]
operations = [
migrations.CreateModel(
name='AwardsInfo',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('award_name', models.CharField(max_length=100)),
('award_date', models.DateField()),
('award_organization', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='PunishmentsInfo',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('discipline_date', models.DateField(blank=True, null=True)),
('discipline_issue', models.CharField(blank=True, max_length=255, null=True)),
('discipline_outcome', models.CharField(blank=True, max_length=255, null=True)),
],
),
migrations.AlterField(
model_name='ecuser',
name='age',
field=models.IntegerField(blank=True, null=True, verbose_name='年龄'),
),
migrations.AlterField(
model_name='ecuser',
name='dob',
field=models.DateField(blank=True, null=True, verbose_name='出生日期'),
),
migrations.AlterField(
model_name='ecuser',
name='ethnicity',
field=models.CharField(default='Unknown', max_length=50, verbose_name='民族'),
),
migrations.AlterField(
model_name='ecuser',
name='gender',
field=models.CharField(choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Other')], default='M', max_length=1, verbose_name='性别'),
),
migrations.AlterField(
model_name='ecuser',
name='id_card_number',
field=models.CharField(max_length=18, unique=True, verbose_name='身份证号'),
),
migrations.AlterField(
model_name='ecuser',
name='name',
field=models.CharField(max_length=100, verbose_name='姓名'),
),
migrations.AlterField(
model_name='ecuser',
name='political_status',
field=models.CharField(blank=True, max_length=50, null=True, verbose_name='政治面貌'),
),
migrations.AlterField(
model_name='ecuser',
name='subject_usage_count',
field=models.IntegerField(default=5, verbose_name='使用次数限制'),
),
migrations.AlterField(
model_name='ecuser',
name='subjects',
field=models.ManyToManyField(blank=True, related_name='users', to='ec_user.subject', verbose_name='开放权限的科目'),
),
migrations.DeleteModel(
name='AwardsPunishments',
),
migrations.AddField(
model_name='punishmentsinfo',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='awardsinfo',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]

View File

@ -0,0 +1,28 @@
# Generated by Django 4.2.19 on 2025-03-01 14:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ec_user', '0016_awardsinfo_punishmentsinfo_alter_ecuser_age_and_more'),
]
operations = [
migrations.AlterField(
model_name='awardsinfo',
name='award_date',
field=models.DateField(blank=True, null=True),
),
migrations.AlterField(
model_name='awardsinfo',
name='award_name',
field=models.CharField(blank=True, max_length=100, null=True),
),
migrations.AlterField(
model_name='awardsinfo',
name='award_organization',
field=models.CharField(blank=True, max_length=100, null=True),
),
]

View File

@ -229,16 +229,24 @@ class FamilyInfo(models.Model):
} }
return f"Family Info of {self.user.name}" return f"Family Info of {self.user.name}"
# AwardsPunishments奖惩情况表 # Awards奖情况表
class AwardsPunishments(models.Model): class AwardsInfo(models.Model):
# 定义一个与EcUser一对多关联的外键
user = models.ForeignKey(EcUser, on_delete=models.CASCADE)
award_name = models.CharField(max_length=100,null=True, blank=True)
award_date = models.DateField(null=True, blank=True)
award_organization = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return f"Awards of {self.user.name}"
# Punishments处分情况表
class PunishmentsInfo(models.Model):
# 定义一个与EcUser一对多关联的外键 # 定义一个与EcUser一对多关联的外键
user = models.ForeignKey(EcUser, on_delete=models.CASCADE) user = models.ForeignKey(EcUser, on_delete=models.CASCADE)
award_name = models.CharField(max_length=100)
award_date = models.DateField()
award_organization = models.CharField(max_length=100)
discipline_date = models.DateField(null=True, blank=True) discipline_date = models.DateField(null=True, blank=True)
discipline_issue = models.CharField(max_length=255, null=True, blank=True) discipline_issue = models.CharField(max_length=255, null=True, blank=True)
discipline_outcome = models.CharField(max_length=255, null=True, blank=True) discipline_outcome = models.CharField(max_length=255, null=True, blank=True)
def __str__(self): def __str__(self):
return f"Awards and Punishments of {self.user.name}" return f"Punishments of {self.user.name}"

View File

@ -269,17 +269,33 @@
</div> </div>
</form> </form>
<form method="POST" action="/ec_user/all_info_edit/{{ user.id }}/awards_punishments/" > <form method="POST" action="/ec_user/all_info_edit/{{ user.id }}/awards_info/" >
<!--情况 --> <!--情况 -->
<div class="form-section"> <div class="form-section">
<h4>情况</h4> <h4>情况</h4>
{{ awards_punishments_form.management_form }} {{ awards_info_form.management_form }}
{% for form in awards_punishments_form %} {% for form in awards_info_form %}
<div class="border p-3 mb-3"> <div class="border p-3 mb-3">
{{ form.as_p }} {{ form.as_p }}
</div> </div>
{% empty %} {% empty %}
<p class="empty-message">没有奖惩情况记录。</p> <p class="empty-message">没有奖励情况记录。</p>
{% endfor %}
<button type="submit" class="btn-submit">提交</button>
</div>
</form>
<form method="POST" action="/ec_user/all_info_edit/{{ user.id }}/punishments_info/" >
<!-- 处罚情况 -->
<div class="form-section">
<h4>处罚情况</h4>
{{ punishments_info_form.management_form }}
{% for form in punishments_info_form %}
<div class="border p-3 mb-3">
{{ form.as_p }}
</div>
{% empty %}
<p class="empty-message">没有处罚情况记录。</p>
{% endfor %} {% endfor %}
<button type="submit" class="btn-submit">提交</button> <button type="submit" class="btn-submit">提交</button>
</div> </div>

View File

@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Awards and Punishments API</title> <title>Test Awards API</title>
<style> <style>
body { body {
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
@ -18,16 +18,16 @@
</style> </style>
</head> </head>
<body> <body>
<h2>Test Awards and Punishments API</h2> <h2>Test Awards API</h2>
<h3>Get Awards and Punishments</h3> <h3>Get Awards</h3>
<label for="user_id_get">User ID:</label> <label for="user_id_get">User ID:</label>
<input type="number" id="user_id_get" min="1" placeholder="Enter user ID"> <input type="number" id="user_id_get" min="1" placeholder="Enter user ID">
<button onclick="getAwardsPunishments()">Get Awards and Punishments</button> <button onclick="getAwards()">Get Awards</button>
<div id="get-result" class="message"></div> <div id="get-result" class="message"></div>
<h3>Update Awards and Punishments</h3> <h3>Update Awards</h3>
<label for="user_id_post">User ID:</label> <label for="user_id_post">User ID:</label>
<input type="number" id="user_id_post" min="1" placeholder="Enter user ID"> <input type="number" id="user_id_post" min="1" placeholder="Enter user ID">
<br><br> <br><br>
@ -39,23 +39,15 @@
<br><br> <br><br>
<label for="award_organization">Award Organization:</label> <label for="award_organization">Award Organization:</label>
<input type="text" id="award_organization" placeholder="Enter award organization"> <input type="text" id="award_organization" placeholder="Enter award organization">
<br><br> <br><br>
<label for="discipline_date">Discipline Date (optional):</label> <button onclick="updateAwards()">Update Awards</button>
<input type="date" id="discipline_date">
<br><br>
<label for="discipline_issue">Discipline Issue (optional):</label>
<input type="text" id="discipline_issue" placeholder="Enter discipline issue">
<br><br>
<label for="discipline_outcome">Discipline Outcome (optional):</label>
<input type="text" id="discipline_outcome" placeholder="Enter discipline outcome">
<br><br>
<button onclick="updateAwardsPunishments()">Update Awards and Punishments</button>
<div id="post-result" class="message"></div> <div id="post-result" class="message"></div>
<script> <script>
// Function to get awards and punishments via GET request // Function to get awards via GET request
function getAwardsPunishments() { function getAwards() {
const userId = document.getElementById('user_id_get').value; const userId = document.getElementById('user_id_get').value;
const resultDiv = document.getElementById('get-result'); const resultDiv = document.getElementById('get-result');
@ -64,7 +56,7 @@
return; return;
} }
fetch(`/ec_user/awards_punishments/api/`, { fetch(`/ec_user/awards_info/api/`, {
method: 'GET', method: 'GET',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -84,15 +76,12 @@
}); });
} }
// Function to update awards and punishments via POST request // Function to update awards via POST request
function updateAwardsPunishments() { function updateAwards() {
const userId = document.getElementById('user_id_post').value; const userId = document.getElementById('user_id_post').value;
const awardName = document.getElementById('award_name').value; const awardName = document.getElementById('award_name').value;
const awardDate = document.getElementById('award_date').value; const awardDate = document.getElementById('award_date').value;
const awardOrganization = document.getElementById('award_organization').value; const awardOrganization = document.getElementById('award_organization').value;
const disciplineDate = document.getElementById('discipline_date').value;
const disciplineIssue = document.getElementById('discipline_issue').value;
const disciplineOutcome = document.getElementById('discipline_outcome').value;
const resultDiv = document.getElementById('post-result'); const resultDiv = document.getElementById('post-result');
if (!userId || !awardName || !awardDate || !awardOrganization) { if (!userId || !awardName || !awardDate || !awardOrganization) {
@ -104,12 +93,9 @@
award_name: awardName, award_name: awardName,
award_date: awardDate, award_date: awardDate,
award_organization: awardOrganization, award_organization: awardOrganization,
discipline_date: disciplineDate || null,
discipline_issue: disciplineIssue || null,
discipline_outcome: disciplineOutcome || null
}; };
fetch(`/ec_user/awards_punishments/api/`, { fetch(`/ec_user/awards_info/api/`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',

View File

@ -0,0 +1,114 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Awards and Punishments API</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.message {
margin-top: 10px;
padding: 10px;
background-color: #f4f4f4;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<h2>Test Punishments API</h2>
<h3>Get Punishments</h3>
<label for="user_id_get">User ID:</label>
<input type="number" id="user_id_get" min="1" placeholder="Enter user ID">
<button onclick="getPunishments()">Get Punishments</button>
<div id="get-result" class="message"></div>
<h3>Update Punishments</h3>
<label for="user_id_post">User ID:</label>
<input type="number" id="user_id_post" min="1" placeholder="Enter user ID">
<br><br>
<label for="discipline_date">Discipline Date (optional):</label>
<input type="date" id="discipline_date">
<br><br>
<label for="discipline_issue">Discipline Issue (optional):</label>
<input type="text" id="discipline_issue" placeholder="Enter discipline issue">
<br><br>
<label for="discipline_outcome">Discipline Outcome (optional):</label>
<input type="text" id="discipline_outcome" placeholder="Enter discipline outcome">
<br><br>
<button onclick="updatePunishments()">Update Punishments</button>
<div id="post-result" class="message"></div>
<script>
// Function to get punishments via GET request
function getPunishments() {
const userId = document.getElementById('user_id_get').value;
const resultDiv = document.getElementById('get-result');
if (!userId) {
resultDiv.textContent = "Please enter a valid user ID.";
return;
}
fetch(`/ec_user/awards_info/api/`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'token': '486ef8198bb10ba6878eba95771c064ff64db81a'
},
})
.then(response => response.json())
.then(data => {
if (data.error) {
resultDiv.textContent = `Error: ${data.error}`;
} else {
resultDiv.textContent = JSON.stringify(data, null, 2);
}
})
.catch(error => {
resultDiv.textContent = `Error: ${error.message}`;
});
}
// Function to update punishments via POST request
function updatePunishments() {
const userId = document.getElementById('user_id_post').value;
const disciplineDate = document.getElementById('discipline_date').value;
const disciplineIssue = document.getElementById('discipline_issue').value;
const disciplineOutcome = document.getElementById('discipline_outcome').value;
const resultDiv = document.getElementById('post-result');
const postData = {
discipline_date: disciplineDate || null,
discipline_issue: disciplineIssue || null,
discipline_outcome: disciplineOutcome || null
};
fetch(`/ec_user/punishments_info/api/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'token': '486ef8198bb10ba6878eba95771c064ff64db81a'
},
body: JSON.stringify(postData)
})
.then(response => response.json())
.then(data => {
if (data.error) {
resultDiv.textContent = `Error: ${data.error}`;
} else {
resultDiv.textContent = data.message;
}
})
.catch(error => {
resultDiv.textContent = `Error: ${error.message}`;
});
}
</script>
</body>
</html>

View File

@ -7,7 +7,7 @@ from . views import MyProtectedApiContactInfo, api_contact_info_test, MyProtecte
from . views import MyProtectedApiAcademicInfo, api_academic_info_test, MyProtectedApiHealthInfo, api_health_info_test from . views import MyProtectedApiAcademicInfo, api_academic_info_test, MyProtectedApiHealthInfo, api_health_info_test
from . views import MyProtectedApiSelfEvaluationInfo, api_self_evaluation_test, MyProtectedFamilyInfo, api_family_info_test from . views import MyProtectedApiSelfEvaluationInfo, api_self_evaluation_test, MyProtectedFamilyInfo, api_family_info_test
from . views import MyProtectedApiHobbiesInterests, api_hobbies_interests_test, MyProtectedSocialPractice, api_social_practice_test from . views import MyProtectedApiHobbiesInterests, api_hobbies_interests_test, MyProtectedSocialPractice, api_social_practice_test
from . views import MyProtectedAwardsPunishments, api_awards_punishments_test , MyProtectedBasicUserInfo from . views import MyProtectedAwardsInfo, MyProtectedPunishmentsInfo, api_awards_info_test, api_punishments_info_test , MyProtectedBasicUserInfo
from . views import all_info_form, all_info_edit from . views import all_info_form, all_info_edit
@ -45,8 +45,11 @@ urlpatterns = [
path('family_info/api/', MyProtectedFamilyInfo.as_view(), name='api_family_info'), path('family_info/api/', MyProtectedFamilyInfo.as_view(), name='api_family_info'),
path('api_family_info_test/', api_family_info_test, name='api_family_info_test'), path('api_family_info_test/', api_family_info_test, name='api_family_info_test'),
path('awards_punishments/api/', MyProtectedAwardsPunishments.as_view(), name='api_awards_punishments'), path('awards_info/api/', MyProtectedAwardsInfo.as_view(), name='api_awards_info'),
path('api_awards_punishments_test/', api_awards_punishments_test, name='api_awards_punishments_test'), path('api_awards_info_test/', api_awards_info_test, name='api_awards_info_test'),
path('punishments_info/api/', MyProtectedPunishmentsInfo.as_view(), name='api_punishments_info'),
path('api_punishments_info_test/', api_punishments_info_test, name='api_punishments_info_test'),
path('all_info_form/<int:user_id>/', all_info_form, name='all_info_form'), path('all_info_form/<int:user_id>/', all_info_form, name='all_info_form'),

View File

@ -11,7 +11,7 @@ from django.contrib.auth.hashers import check_password, make_password # 导入
from .models import EcUser, ContactInfo, SchoolInfo, AcademicInfo, HealthInfo, SelfEvaluation from .models import EcUser, ContactInfo, SchoolInfo, AcademicInfo, HealthInfo, SelfEvaluation
from .models import HobbiesInterests, SocialPractice, FamilyInfo, AwardsPunishments from .models import HobbiesInterests, SocialPractice, FamilyInfo, AwardsInfo, PunishmentsInfo
from .forms import g_models, g_form_classes from .forms import g_models, g_form_classes
@ -83,7 +83,7 @@ def all_info_form(request, user_id):
instances = {} instances = {}
for key, model in g_models.items(): for key, model in g_models.items():
if key in ['hobbies_interests', 'social_practice', 'family_info', 'awards_punishments']: if key in ['hobbies_interests', 'social_practice', 'family_info', 'awards_info', 'punishments_info']:
instances[key] = model.objects.filter(user=user) # 处理一对多关系 instances[key] = model.objects.filter(user=user) # 处理一对多关系
else: else:
instance, _ = model.objects.get_or_create(user=user) instance, _ = model.objects.get_or_create(user=user)
@ -93,7 +93,7 @@ def all_info_form(request, user_id):
# 初始化所有表单 # 初始化所有表单
forms = {} forms = {}
for form_key, form_class in g_form_classes.items(): for form_key, form_class in g_form_classes.items():
if form_key in ['hobbies_interests_form', 'social_practice_form', 'family_info_form', 'awards_punishments_form']: if form_key in ['hobbies_interests_form', 'social_practice_form', 'family_info_form', 'awards_info_form', 'punishments_info_form']:
queryset = instances[form_key[:-5]] # 获取对应模型的查询集 queryset = instances[form_key[:-5]] # 获取对应模型的查询集
# 如果查询集为空,设置 extra=1 来允许添加空表单 # 如果查询集为空,设置 extra=1 来允许添加空表单
@ -160,7 +160,8 @@ class MyProtectedUserInfo(APIView):
"family_info": FamilyInfo.objects.filter(user=request.user).exists(), "family_info": FamilyInfo.objects.filter(user=request.user).exists(),
"hobbies_interests": HobbiesInterests.objects.filter(user=request.user).exists(), "hobbies_interests": HobbiesInterests.objects.filter(user=request.user).exists(),
"social_practice": SocialPractice.objects.filter(user=request.user).exists(), "social_practice": SocialPractice.objects.filter(user=request.user).exists(),
"awards_punishments": AwardsPunishments.objects.filter(user=request.user).exists(), "awards_info": AwardsInfo.objects.filter(user=request.user).exists(),
"punishments_info": PunishmentsInfo.objects.filter(user=request.user).exists(),
} }
}) })
@ -604,10 +605,13 @@ class MyProtectedFamilyInfo(APIView):
return JsonResponse({"message": "Family info updated successfully"}) return JsonResponse({"message": "Family info updated successfully"})
def api_awards_punishments_test(req): def api_awards_info_test(req):
return render(req, 'api_awards_punishments_test.html') return render(req, 'api_awards_info_test.html')
class MyProtectedAwardsPunishments(APIView): def api_punishments_info_test(req):
return render(req, 'api_punishments_info_test.html')
class MyProtectedAwardsInfo(APIView):
authentication_classes = [CustomTokenAuthentication] # 使用自定义的 Token 认证 authentication_classes = [CustomTokenAuthentication] # 使用自定义的 Token 认证
permission_classes = [IsAuthenticated] # 需要用户认证才能访问 permission_classes = [IsAuthenticated] # 需要用户认证才能访问
@ -615,21 +619,18 @@ class MyProtectedAwardsPunishments(APIView):
user = request.user user = request.user
# 获取该用户的奖惩情况记录 # 获取该用户的奖惩情况记录
awards_punishments = AwardsPunishments.objects.filter(user=user) awards_punishments = AwardsInfo.objects.filter(user=user)
if awards_punishments.exists(): if awards_punishments.exists():
response_data = [ response_data = [
{ {
"award_name": ap.award_name, "award_name": ap.award_name,
"award_date": ap.award_date, "award_date": ap.award_date,
"award_organization": ap.award_organization, "award_organization": ap.award_organization
"discipline_date": ap.discipline_date,
"discipline_issue": ap.discipline_issue,
"discipline_outcome": ap.discipline_outcome
} for ap in awards_punishments } for ap in awards_punishments
] ]
return JsonResponse(response_data, safe=False) return JsonResponse(response_data, safe=False)
else: else:
return JsonResponse({"error": "No awards or punishments found"}, status=404) return JsonResponse({"error": "No awards found"}, status=404)
def post(self, request): def post(self, request):
user = request.user user = request.user
@ -639,21 +640,55 @@ class MyProtectedAwardsPunishments(APIView):
award_name = data.get("award_name") award_name = data.get("award_name")
award_date = data.get("award_date") award_date = data.get("award_date")
award_organization = data.get("award_organization") award_organization = data.get("award_organization")
except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON format"}, status=400)
awards_punishment = AwardsInfo.objects.create(
user=user,
award_name=award_name,
award_date=award_date,
award_organization=award_organization,
)
return JsonResponse({"message": "Awards info updated successfully"})
class MyProtectedPunishmentsInfo(APIView):
authentication_classes = [CustomTokenAuthentication] # 使用自定义的 Token 认证
permission_classes = [IsAuthenticated] # 需要用户认证才能访问
def get(self, request):
user = request.user
# 获取该用户的奖惩情况记录
awards_punishments = PunishmentsInfo.objects.filter(user=user)
if awards_punishments.exists():
response_data = [
{
"discipline_date": ap.discipline_date,
"discipline_issue": ap.discipline_issue,
"discipline_outcome": ap.discipline_outcome
} for ap in awards_punishments
]
return JsonResponse(response_data, safe=False)
else:
return JsonResponse({"error": "No punishments found"}, status=404)
def post(self, request):
user = request.user
# 处理 POST 请求,创建或更新奖惩情况记录
try:
data = json.loads(request.body)
discipline_date = data.get("discipline_date") discipline_date = data.get("discipline_date")
discipline_issue = data.get("discipline_issue") discipline_issue = data.get("discipline_issue")
discipline_outcome = data.get("discipline_outcome") discipline_outcome = data.get("discipline_outcome")
except json.JSONDecodeError: except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON format"}, status=400) return JsonResponse({"error": "Invalid JSON format"}, status=400)
# 创建或更新 AwardsPunishments 记录 awards_punishment = PunishmentsInfo.objects.create(
awards_punishment = AwardsPunishments.objects.create(
user=user, user=user,
award_name=award_name,
award_date=award_date,
award_organization=award_organization,
discipline_date=discipline_date, discipline_date=discipline_date,
discipline_issue=discipline_issue, discipline_issue=discipline_issue,
discipline_outcome=discipline_outcome discipline_outcome=discipline_outcome
) )
return JsonResponse({"message": "Awards and punishments info updated successfully"}) return JsonResponse({"message": "punishments info updated successfully"})