Django中拼接字符串与整数生成Shop ID的实现问题
Hey there! Let's get your ShopCreateView's form_valid method sorted out properly to hit all your requirements. I'll walk you through a complete, working implementation that fixes the undefined variable issues and handles every task you listed:
from django.views.generic.edit import CreateView from datetime import datetime from .models import Shop # Make sure to import your Shop model class ShopCreateView(CreateView): model = Shop fields = ['dept_name', ...] # Replace with your actual form fields def form_valid(self, form): # 1. Generate department abbreviation from dept_name dept_name = form.cleaned_data.get('dept_name') if dept_name: # Split into words, skip entries with dots (like "PT."), grab first letter of each remaining word filtered_words = [word for word in dept_name.split() if '.' not in word] dept_abbr = ''.join([word[0].upper() for word in filtered_words]) else: # Fallback if dept_name is empty dept_abbr = 'UNK' # 2. Format counted number to 3-digit string with leading zeros # Adjust this logic to match how you get your "counted" value (this example uses total shops in dept +1) counted = Shop.objects.filter(dept_name=dept_name).count() + 1 formatted_count = f"{counted:03d}" # Turns 1 → "001", 12 → "012", 123 → "123" # 3. Get year and month (customize this if you don't want current date) current_year = datetime.now().strftime('%y') # 2-digit year (e.g., 2024 → "24") current_month = datetime.now().strftime('%m') # 2-digit month (e.g., August → "08") # Build the shop_id string (f-string handles int-to-string conversion automatically) shop_id = f"{dept_abbr}{current_year}{current_month}{formatted_count}" # Example: CAM + 24 + 08 + 001 → "CAM2408001" # Assign the generated shop_id to the new Shop instance form.instance.shop_id = shop_id # Let the parent class handle the rest of the save process return super().form_valid(form)
Key Details & Customization Tips:
- Department Abbreviation: The code skips words with dots (like your example's "PT.") to get "CAM" from "PT. Counter Avenger Manequin". If you don't need this filter, just remove the
if '.' not in wordcheck. - Counted Value: The example uses the total number of shops in the department plus one as the
countedvalue. Adjust this line to pull from your actual source of the count (e.g., a separate counter model or form field). - Year/Month: If you need to use a specific year/month instead of the current date, replace
datetime.now()with your desired date source (e.g.,form.cleaned_data.get('establishment_month')). - Error Handling: Added a fallback for empty
dept_nameto prevent crashes—you can tweak the "UNK" default to whatever makes sense for your app. - String/Int Concatenation: Using f-strings eliminates the need to manually convert integers to strings, which fixes the type mismatch issue you mentioned.
Make sure your Shop model has a shop_id field (we recommend a CharField with a sufficient max_length, like 20) to store this generated value.
内容的提问来源于stack exchange,提问作者Budi Gunawan
相关产品推荐
相关产品推荐

