与django用户

时间:2017-03-29 08:16:37

标签: django django-forms django-admin

我对Django用户有一些问题

第一个:我创建了一个新用户,我喜欢这个:

user = User.objects.create_user(username='douglas2', password='password')
user.save()
users = User.objects.all()
users

输出:

  

< QuerySet [<用户:douglas>,<用户:douglas2>]>

但是当我尝试登录Django时,它指责无效的用户或密码......我做错了什么?

第二个问题是:当我在评估页面上时,评估者的选项允许我选择任何评估者,什么不是......如何,纠正这个我必须从管理页面(http://127.0.0.1:8000/admind/evaluation)开始这个页面吗?

第三个问题:我使用模型的属性(评估师)"评估"是独一无二的,因为评估师只能评估候选人一次。但是当我选择第二个评估师时(在我上面引用的错误字段中),Django说这个评估师已经评估了这个候选人,甚至没有......

我对同一个问题提出了不止一个疑问,因为我认为在这种情况下,这些问题都是相关的

我的代码:

**views.py**
from django.shortcuts import render, get_object_or_404
from .models import Candidate, Criterion, Evaluation
from django import forms
from .forms import CandForm
from .forms import EvalForm
from django.shortcuts import redirect
from django.db import IntegrityError


def canditate_list(request):
    candidates = Candidate.objects.all()

    eva = Evaluation.objects.all()
    eval_cand_list = []                                     #aqui guarda uma lista com os FK candidates convertidos p/ str

    context = {
        'candidates': candidates,
        'eva': eva
    }
    return render(request, 'app/candidate_list.html',context)

def candidate_detail(request, pk):
    candidate = get_object_or_404(Candidate, pk=pk)
    c_name = candidate.name                                 #pega o nome (string) do candidato
    c1 = Evaluation.objects.all()                           #guarda tds Evaluation na variavel  
    scores = []                                             #declara a array que vai receber as notas
    for c in c1:                                            
        cand = str(c.candidate)                             #guarda o nome do candidato do Evaluation atual
        if cand == c_name:                                  #confere se o Evaluation atual corresponde ao candidate atual(pk)
            scores += [c.score]

    _sum = 0                                                #variavel que guardara a soma declarada
    for s in scores:
        _sum += s                                           #faz a soma dos scores

    average = 0 
    if len(scores) > 0:
        average = _sum/len(scores)                              #tira a média

    context = {
        'candidate': candidate,
        'average': average
    }

    return render(request, 'app/candidate_detail.html', context)


def evaluation(request):
    # form2 initialization
    form2 = EvalForm()

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid():    
            post = form2.save(commit=False)
            try:
                post.save()
                return redirect('canditate_list')
            except IntegrityError:
                return HttpResponse("Você já avaliou este candidato!")
    return render(request, 'app/evaluation.html', {'criterions': form2,})


def register(request):
    if request.method == "POST":
        form = CandForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('candidate_detail', pk=post.pk)
    else:
        form = CandForm()
    return render(request, 'app/register.html', {'form': form})

models.py

    from django.db import models
    from jsonfield import JSONField
    from site_.settings import MEDIA_ROOT
    from django.core.validators import MaxValueValidator

    class Criterion(models.Model):
        label = models.CharField(max_length=100)

        def  __str__(self):
            return self.label

    class Candidate(models.Model):
        name = models.CharField(max_length=100)
        e_mail = models.EmailField(max_length=100, default = '')
        github = models.URLField(default = '')
        linkedin = models.URLField(max_length=100, default = '')
        cover_letter = models.TextField(default = '')
        higher_education = models.BooleanField(default = False)
        average = models.IntegerField(default = 0)
        docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True)

        def  __str__(self):
            return self.name


    class Evaluation(models.Model):
        candidate = models.ForeignKey(Candidate, unique=True)
        criterion = models.ForeignKey(Criterion, default='')
        score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)])
        appraiser = models.ForeignKey('auth.User')

        def  __str__(self):
            return str(self.candidate)

**forms.py**

from .models import Candidate, Evaluation
from django import forms

class CandForm(forms.ModelForm):
    class Meta:
        model = Candidate
        fields = ('name', 'e_mail', 'github', 'linkedin', 'higher_education','cover_letter')

class EvalForm(forms.ModelForm):
    class Meta:
        model = Evaluation
        fields = ('candidate','criterion','score','appraiser')
        #fields = ('v1','v2')

0 个答案:

没有答案