You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中检测输入是否已存在?实现重复输入生成二维码时的错误提示

Hey there! Let's fix this step by step. I see a couple of issues in your current code that are preventing the duplicate check from working correctly, plus some missing pieces to make the whole flow work as expected.

1. Fix the Form Validation Logic (forms.py)

Your current clean_input method has the logic reversed—you're throwing an error when the input doesn't exist, which is the opposite of what you want. Also, you're not saving the valid input to your Qr model, so the duplicate check will never find existing entries later. Here's the corrected version:

from django import forms
from generateqr.models import Qr
import qrcode
from uuid import uuid4  # Generate unique filenames to avoid overwriting QR images

class Qrgenerate(forms.Form):
    input = forms.CharField(label="Enter text for QR Code")

    def clean_input(self):
        input_val = self.cleaned_data['input']
        
        # First check if this input already exists in the database
        if Qr.objects.filter(input__iexact=input_val).exists():
            raise forms.ValidationError(f'Input "{input_val}" is already in use.')
        
        # Keep your original minimum length validation
        if len(input_val) < 5:
            raise forms.ValidationError('Enter more than 5 characters.')
        
        # Generate a unique filename so new QR codes don't overwrite old ones
        unique_filename = f"{uuid4().hex}.png"
        img = qrcode.make(input_val)
        img.save(f"path/to/your/qr_images/{unique_filename}")  # Replace with your actual storage path
        
        return input_val

Quick notes:

  • Used filter(...).exists() instead of get() for more efficient existence checks (no need to fetch the full object).
  • Added uuid4 to create unique filenames—your original test.png would get overwritten every time you generate a new QR code.
  • Combined your length validation with the duplicate check for cleaner, more organized code.
2. Complete the View Logic (views.py)

Your views.py was incomplete—you need to handle GET requests properly and save valid inputs to the database so future duplicate checks work. Here's the updated view:

from django.shortcuts import render
from .forms import Qrgenerate
from .models import Qr

def showformdata(request):
    if request.method == 'POST':
        fm = Qrgenerate(request.POST)
        if fm.is_valid():
            # Get the cleaned input from the form
            input_val = fm.cleaned_data['input']
            # Save the input to the Qr model so future checks can detect duplicates
            Qr.objects.create(input=input_val)
            # Optional: Add a success message here if you want to confirm generation
    else:
        # Initialize an empty form for GET requests
        fm = Qrgenerate()
    
    return render(request, "home.html", {'form': fm})
3. Why Your Earlier Attempt Failed

Just to clarify the issues in your test code:

  • You referenced Qrcode.objects but your model is named Qr (simple typo).
  • The query syntax was wrong: input==input should be input=valinput (or input__iexact=valinput for case-insensitive checks).
  • You tried to catch input.DoesNotExist—the exception belongs to the model class, so it should be Qr.DoesNotExist.
  • The variable scoping for input was incorrect, leading to the "Attribute 'object' is not found" error.
4. Update Your Template to Show Errors

Make sure your home.html template displays validation errors correctly. Add this snippet where you want error messages to appear:

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div style="color: red; margin-bottom: 10px;">
                {{ error|escape }}
            </div>
        {% endfor %}
    {% endfor %}
{% endif %}

<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Generate QR Code</button>
</form>

This will show the "already in use" or "too short" error messages right above the form when validation fails.

内容的提问来源于stack exchange,提问作者Pooja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:52:51