如何在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.
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 ofget()for more efficient existence checks (no need to fetch the full object). - Added
uuid4to create unique filenames—your originaltest.pngwould get overwritten every time you generate a new QR code. - Combined your length validation with the duplicate check for cleaner, more organized code.
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})
Just to clarify the issues in your test code:
- You referenced
Qrcode.objectsbut your model is namedQr(simple typo). - The query syntax was wrong:
input==inputshould beinput=valinput(orinput__iexact=valinputfor case-insensitive checks). - You tried to catch
input.DoesNotExist—the exception belongs to the model class, so it should beQr.DoesNotExist. - The variable scoping for
inputwas incorrect, leading to the "Attribute 'object' is not found" error.
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

