#python #html #django
#python #HTML #django
Вопрос:
когда я регистрирую пациента или врача на платформе регистрации (регистрируюсь), я не знаю, почему данные врача и пациента не регистрируются в базе данных (MySQL)?, Мне нужна ваша помощь, пожалуйста.
У меня есть следующий код в bas_appviews.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.contrib.auth import login, authenticate
from .forms import MedForm, PatForm, ContactForm
from .models import Patient, Médecin, User
def accueil(request):
return render(request, 'base_app/accueil.html')
def inscription(request):
if request.method == 'GET':
dict_inscription_form = {'form': UserCreationForm()}
return render(request, 'base_app/inscription.html', dict_inscription_form)
else:
# Creer un nouveau compte
if request.POST['password1'] == request.POST['password2']:
try:
# Enregistrer ses données
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
# Se Connecter directement
login(request, user)
return render(request, 'base_app/apres-inscription.html')
except IntegrityError:
dict_form_error = {'form': UserCreationForm(), 'error': "Ce nom d'utilisateur existe déjà"}
return render(request, 'base_app/inscription.html', dict_form_error)
else:
# Probléme dans le mot de passe
dict_form_error = {'form': UserCreationForm(), 'error': 'Le mot de passe ne correspond pas'}
return render(request, 'base_app/inscription.html', dict_form_error)
# apres Connection page
def apres_inscription(request):
return render(request, 'base_app/apres-inscription.html')
def apres_connection_medecin(request):
return render(request, 'base_app/apres_connection_medecin')
# se connecter
def se_connecter(request):
if request.method == 'GET':
return render(request, 'base_app/connection.html', {'form': AuthenticationForm()})
else:
user = authenticate(request, username=request.POST['username'],first_name=request.POST['nom'],last_name=request.POST['prénom'],password=request.POST['password'])
if user is None:
return render(request, 'base_app/inscription.html', {'form': UserCreationForm(),
'error': "Le nom d'utilisateur ou le mot de passe ne correspond pas"})
else:
login(request, user)
return render(request, 'base_app/accueil.html')
def Medformpage(request):
if request.method == 'GET' :
return render(request,'base_app/inscription-finale-medecin.html', {'form' : MedForm() } )
else :
try:
form = MedForm(request.POST)
newform = form.save(commit=False)
newform.user = request.user
newform.save()
return redirect('accueil')
except ValueError:
return render(request,'base_app/inscription-finale-medecin.html', {'form' : MedForm(), 'error' : "Il y a une erreur sur votre soumission"} )
def Patformpage(request):
if request.method == 'GET' :
return render(request,'base_app/inscription-finale-patient.html', {'form' : PatForm() } )
else :
try:
form = PatForm(request.POST)
newform = form.save(commit=False)
newform.user = request.user
newform.save()
return redirect('accueil')
except ValueError:
return render(request,'base_app/inscription-finale-patient.html', {'form' : PatForm(), 'error' : "Il y a une erreur sur votre soumission"} )
У меня есть следующий код в bas_appmodels.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
spécialité_types = [
('', 'Choose....'),
('Aucune','Aucune'),
('chirurgien','chirurgien'),
('Gynécologue','Gynécologue')
]
sex_types = [
('1','Homme'),
('2','Femme'),
]
quartier_types = [
('0', ' '),
('1', 'Hay Riad'),
('2', 'Hassan 2'),
('3', 'Agdal')
]
class Médecin(models.Model):
username_id = models.OneToOneField(User,on_delete=models.CASCADE)
nom = models.CharField("Nom ",max_length=30)
prénom = models.CharField("Prénom ", max_length=30)
cin = models.CharField("C.I.N ", max_length=10)
date_de_naissance = models.DateField(null=True, blank=True)
spécialité = models.CharField(max_length=20, choices=spécialité_types, default='spa')
sexe = models.CharField(max_length=10, choices=sex_types, default='1')
quartier = models.CharField(max_length=20, choices=quartier_types, default='0')
active = models.BooleanField(default=True)
class Patient(models.Model):
username_id = models.OneToOneField(User,on_delete=models.CASCADE)
nom = models.CharField("Nom ",max_length=30)
prénom = models.CharField("Prénom ", max_length=30)
cin = models.CharField("C.I.N ", max_length=10)
date_de_naissance = models.DateField(null=True, blank=True)
sexe = models.CharField(max_length=10, choices=sex_types, default='1')
quartier = models.CharField(max_length=20, choices=quartier_types, default='0')
У меня есть следующий код в bas_appforms.py
from django.forms import ModelForm
from django import forms
from django.forms.widgets import NumberInput
from .models import Médecin, Patient
YEARS=[x for x in range(1950,2010)]
sex =[
('', 'Choose....'),
('Femme', 'Femme'),
('Homme', 'Homme'),
]
quartiers=[
('', 'Choose....'),
('Riad_agdal', 'Riad_agdal'),
('Hassan', 'Hassan'),
('Alfath', 'Alfath'),
]
spécialité_types = [
('', 'Choose....'),
('Aucune','Aucune'),
('chirurgien','chirurgien'),
('Gynécologue','Gynécologue')
]
class MedForm(forms.ModelForm):
class Meta:
model = Médecin
fields = [ 'nom', 'prénom', 'cin', 'sexe', 'date_de_naissance', 'quartier', 'spécialité']
widget={'nom': forms.TextInput(attrs={'class':'form-control','placeholder':'First_name'}),
'prénom' :forms.TextInput(attrs={'class':'form-control','placeholder':'Last_name'}),
'cin' : forms.TextInput(attrs={'class':'form-control','placeholder':'CIN'}),
'sexe':forms.Select(choices= sex),
'date_de_naissance' : NumberInput(attrs={'type': 'date'}),
'quartier':forms.Select(choices= quartiers),
'spécialité' :forms.Select(choices= spécialité_types)
}
class PatForm(forms.ModelForm):
class Meta:
model = Patient
fields = ['nom', 'prénom', 'cin', 'sexe', 'date_de_naissance', 'quartier']
widget = {'nom': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First_name'}),
'prénom': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last_name'}),
'cin': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'CIN'}),
'date_de_naissance': NumberInput(attrs={'type': 'date'}),
'sexe': forms.Select(choices=sex),
'quartier': forms.Select(choices=quartiers)
}
Заранее благодарю
Комментарии:
1. Я думаю, что вы
def inscription
просто не правы, погуглите несколько примеров регистрации и увидите разницу
Ответ №1:
Измените домашний редирект на ту страницу, на которую вы хотите перенаправить.
Название страницы происходит из urls.py
. Пример: path("", Home, name="home")
Попробуйте это :
def inscription(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=form,password=password)
login(request,user)
return redirect('home')
else:
form = UserRegisterForm()
return render(request, 'base_app/inscription.html', {'form': form})