#django #django-models #django-views #django-forms
Вопрос:
Поэтому я пытаюсь заставить форму модели django принимать только буквенно-цифровой ввод с помощью регулярного выражения, как показано здесь:
class AddDeadCoin(forms.ModelForm):
class Meta:
model = DeadCoin
fields = (
'category',
'is_coin',
'name',
'ticker',
'founder',
'total_coins_or_tokens',
'no_exchanges',
'project_start_date',
'project_end_date',
'social_end_date',
'logo',
'screenshot',
'notes',
'links',
)
def clean_name(self):
name = self.cleaned_data.get('name')
if bool(re.match(r'^[A-Za-z0-9_-]
Однако при попытке отправить любой ввод(как действительный, так и недействительный) я получаю сообщение об ошибке "Это поле обязательно!". Я получаю сообщение дважды, чтобы быть точным. Следует отметить, что поля "имя" и "тикер" обязательны для заполнения.
Вот как выглядят мои модели:
class DeadCoin(models.Model):
name = models.CharField(max_length=70, default=None)
summary = models.TextField(blank=True, null=True, default="Dead Coin Summary")
ticker = models.CharField(max_length=20, default=None)
founder = models.CharField(blank=True, null=True, max_length=50)
is_coin = models.BooleanField(blank=True, null=True, default=True)
notes = models.TextField(blank=True, null=True, default='')
links = models.TextField(blank=True, null=True, default='')
total_coins_or_tokens = models.CharField(blank=True, null=True, max_length=50, default='Unknown')
no_exchanges = models.BooleanField(blank=True, null=True, default=True)
project_start_date = models.CharField(blank=True, null=True, max_length=10, default='2018')
project_end_date = models.CharField(blank=True, null=True, max_length=10, default='2019')
social_end_date = models.CharField(blank=True, null=True, max_length=10, default='2019')
no_website = models.BooleanField(blank=True, null=True, default=True)
logo = models.ImageField(blank=True, null=True, upload_to = 'img/logo/', default = 'img/logo/no-logo.jpg')
screenshot = models.ImageField(blank=True, null=True, upload_to = 'img/', default = 'img/logo/no-logo.jpg')
category = models.CharField(max_length=50, default="Abandoned or No Volume")
slug = models.SlugField(unique=True)
pending = models.BooleanField(default=False)
def save(self, *args, **kwargs):
self.summary=self.summary.strip('<p>').strip('</p>')
if not self.slug:
slug_mix=self.name
self.slug = slugify(slug_mix)
super(DeadCoin, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('deadcoin', args=(self.slug,))
def __str__(self):
return self.name
And this is what my views looks like:
def dead_coins(request):
if request.method == 'POST':
form = AddDeadCoin(data=request.POST or None)
publish=request.POST.get('publish', '')
delete=request.POST.get('delete', '')
category=request.POST.get('category', '')
is_coin=request.POST.get('selector', '')
coinname=request.POST.get('coinname', '')
cointicker=request.POST.get('cointicker', '')
totalcoins=request.POST.get('totalcoins', None)
no_exchange=request.POST.get('ex', '')
project_start_date=request.POST.get('startd', '')
project_end_date=request.POST.get('endd', '')
social_end_date=request.POST.get('sociald', '')
no_website=request.POST.get('web', '')
founder=request.POST.get('founder', '')
screenshot=None
if not founder:
founder="Unknown"
try:
screenshot=request.FILES['screenshots']
except MultiValueDictKeyError:
pass
notes=request.POST.get('notes', '')
links=request.POST.get('links', '')
if form.is_valid():
form.save()
add_dead_coin(category, coinname, cointicker, is_coin, totalcoins, no_exchange,
project_start_date,project_end_date,social_end_date,no_website,founder,screenshot, notes, links, publish, delete, request)
return render(request, 'cryptocracy/dead_coins.html', {
'data': dead_coins_list,
})
else:
return HttpResponse(form.errors.values())
return render(request, 'cryptocracy/dead_coins.html', {
'data': dead_coins_list,
})
What I have tried:
- Explicitly declaring the name and ticker charfields in the form with
required(true)
- using exclude('name', 'ticker') in the form
- adding null=True to the models of ticker and name
- adding an init method to the AddDeadCoin form to make the name and ticker fields required
along with 3-4 other suggestions that I found for similar problems on stackoverflow
My suspicion is that I am not passing information correctly but I am unsure.
Any help would be appreciated.
, str(name))):
return name
else:
raise forms.ValidationError("Sorry , you can only have alphanumeric, _ or - in username")
def save(self):
instance = super(AddDeadCoin, self).save(commit=False)
instance.slug = orig = slugify(instance.name)
for x in itertools.count(1):
if not DeadCoin.objects.filter(slug=instance.slug).exists():
break
instance.slug = '%s-%d' % (orig, x)
instance.save()
return instance
Однако при попытке отправить любой ввод(как действительный, так и недействительный) я получаю сообщение об ошибке «Это поле обязательно!». Я получаю сообщение дважды, чтобы быть точным. Следует отметить, что поля «имя» и «тикер» обязательны для заполнения.
Вот как выглядят мои модели:
And this is what my views looks like:
What I have tried:
- Explicitly declaring the name and ticker charfields in the form with
required(true) - using exclude(‘name’, ‘ticker’) in the form
- adding null=True to the models of ticker and name
- adding an init method to the AddDeadCoin form to make the name and ticker fields required
along with 3-4 other suggestions that I found for similar problems on stackoverflow
My suspicion is that I am not passing information correctly but I am unsure.
Any help would be appreciated.