django form not saving to database(no error message) - python

First of all, I apologize for using a translator because I am not familiar with English.
My Views.py
def my_create_view(request):
if "reg" in request.method == 'POST':
first_form = FirstRegForm(request.POST, prefix='firstform')
second_form = SecondRegForm(request.POST, prefix='secondform')
if all([first_form.is_valid(), second_form.is_valid()]):
form = first_form.save(commit=False)
form.created_name = request.user.user_name
form.save()
formm = second_form.save(commit=False)
formm.shop_seq = form
formm.save()
return redirect('someview')
else:
first_form = FirstRegForm(prefix='store')
second_form = SecondRegForm(prefix='input')
return render(request, 'app/template.html', {'first_form': first_form, 'second_form': second_form})
My Models.py
from django.db.models import Max
class My_user(AbstractBaseUser):
shop_seq = models.ForeignKey('My_shop', null=True, blank=True, on_delete=models.SET_NULL, db_column="shop_seq")
user_name = models.CharField(max_length=50)
class My_shop(models.Model):
shop_seq = models.CharField(primary_key=True, editable=False, max_length=5)
shop_name = models.CharField(max_length=20, null=True)
shop_code = models.CharField(max_length=15, null=True, unique=True)
shop_address = models.CharField(max_length=40, null=True)
shop_tel = models.CharField(max_length=20, null=True)
created_name = models.CharField(max_length=100, null=True)
def save(self, **kwargs):
if not self.shop_seq:
max = Rate.objects.aggregate(shop_seq_max=Max('shop_seq'))['shop_seq_max'] + 1
self.shop_seq = "{:05d}".format(max if max is not None else 1)
super().save(*kwargs)
class My_model(models.Model):
model_id = models.BigAutoField(primary_key=True)
my_field = models.CharField(max_length=20, null=True)
some_field = models.CharField(max_length=20, null=True)
shop_seq = models.ForeignKey('My_shop', on_delete=models.SET_NULL, null=True, db_column="shop_seq", related_name="shop_model")
My Forms.py
class FirstRegForm(forms.ModelForm):
class Meta:
model = My_shop
fields = ('shop_name', 'shop_code', 'shop_address', 'shop_tel',)
class SecondRegForm(forms.ModelForm):
class Meta:
model = My_model
fields = ('my_field', 'some_field',)
My Template.py
<form method="post">{% csrf_token %}
{{ first_form.shop_name }}
{{ first_form.shop_code }}
{{ first_form.shop_address }}
{{ first_form.shop_tel }}
{{ second_form.my_field }}
{{ second_form.some_field }}
<input class="btn btn-dark" name="reg" type="submit" value="reg">
</form>
If you submit it in this state, it will not be saved in the db.(no error message)
What's wrong with my code?

This line will always be evaluated to false:
if "reg" in request.method == 'POST'
You should change it to:
if request.method == 'POST':

Related

How can I show a many-to-many field values in a form?

i wrote a code about music and used Many-To-Many-Field() as genre but when i try to show genres it just shows : Genre['a number']
template:
{% extends 'pages/base.html' %}
{% block content %}
<form>
{% if mdata.image %}
<img src="mdata.image.url" height="500" width="500">
{% endif %}
{% for field in form %}
<p>{{ field.label }} : {{ field.value}}</p>
}
{% endfor %}
</form>
edit
{% endblock %}
models is here:(i didnt know which one u need so pasted both of them)
from django.db import models
from django.contrib.auth.models import User
class Genre(models.Model):
name = models.CharField(unique=True,max_length=20)
def __str__(self):
return self.name.title()
class Mdata(models.Model):
name = models.CharField(max_length=100)
artist = models.CharField(max_length=150)
album = models.CharField(max_length=100)
nation = models.CharField(max_length=100)
duration = models.DecimalField(max_digits=4,decimal_places=2)
released_in = models.DecimalField(max_digits=4,decimal_places=0)
uploaded_at = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='images/',blank=True,null=True)
audio = models.FileField(upload_to='audios/',null=True,blank=True)
genre = models.ManyToManyField(Genre)
uploader = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.name.title()+" by "+self.artist.title()
forms.py:(its just a simple form im using)
[![class MdataForm(ModelForm):
class Meta:
model = Mdata
fields =\[
'name',
'artist',
'album',
'genre',
'nation',
'duration',
'released_in',
'image',
'audio',
]
and here the render :dunno if this is enough
[1]: https://i.stack.imgur.com/T5eK2.png
This could be that you don't have a __str__ method on your Genre model. Add a __str__ method and return the genre name. That would be something like:
def __str__(self):
return self.name
self.name here being the field on your genre model used to specify the name. In the sample image below, I set the custom user to return the username by default, that way anywhere I call a user it will automatically show the name of the genre.
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
email = models.EmailField(_("email address"), unique=True, null=True)
phone_number = PhoneNumberField(unique=True, null=True)
username = models.CharField(max_length=100, unique=True, null=True)
password = models.CharField(_("password"), max_length=128, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "User"
verbose_name_plural = "Users"
def __str__(self):
return self.username

How to categorize content in Django ? Where is the problem with my work?

I wanted to categorize my site content. Show the category titles in the menu and the contents of each category in the body. I have used these codes.
#urls
path('category/<slug:slug>', views.category, name="category")
#views
def category(request, slug):
context = {
"categorys": get_object_or_404(Category, slug=slug, status=True)
}
return render(request, "blog/category.html", context)
#models
class PostManager(models.Manager):
def published(self):
return self.filter(status='p')
class Category(models.Model):
title = models.CharField(max_length=100, verbose_name="عنوان دسته بندی")
slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس")
status = models.BooleanField(
default=True, verbose_name="آیا نمایش داده شود؟")
position = models.IntegerField(verbose_name="پوزیشن")
class Meta:
verbose_name = "دسته بندی"
verbose_name_plural = "دسته بندی ها"
ordering = ['position']
def __str__(self):
return self.title
class Post(models.Model):
STATUS_CHOICES = [
('d', 'پیش نویس'),
('p', 'منتشر شده'),
]
title = models.CharField(max_length=100, verbose_name="عنوان")
slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس")
category = models.ManyToManyField(
Category, verbose_name="دسته بندی", related_name="postcat")
description = models.TextField(verbose_name="توضیحات")
thumbnail = models.ImageField(
upload_to="imgpost", height_field=None, width_field=None, max_length=None, verbose_name="تصویر")
publish = models.DateTimeField(
default=timezone.now, verbose_name="زمان انتشار")
created = models.DateTimeField(
auto_now_add=True, verbose_name="زمان ایجاد")
updated = models.DateTimeField(
auto_now=True, verbose_name="زمان بروزرسانی")
status = models.CharField(
max_length=1, choices=STATUS_CHOICES, verbose_name="وضعیت")
def __str__(self):
return self.title
class Meta:
verbose_name = "پست"
verbose_name_plural = "پست ها"
objects = PostManager()
#template
{% for posts in categorys.postcat.published %}
<p>
posts.title
</p>
<p>
posts.description
</p>
{%endfor%}
The problem is that despite the filter I have set for not displaying draft posts, that post is not displayed in the category section. If you can help. my project in my github
{% for posts in categorys.postcat.published %}
<p>
{{ posts.title }}
</p>
<p>
{{ posts.description }}
</p>
{%endfor%}
try this!
We have to put this line of code in the model, the post class. It was a back fever.
objects = PostManager()

django ListView query_set code abbreviation

The codes are as
models.py
class Firm(models.Model):
name = models.CharField(unique=True, max_length=50, verbose_name="Firma Adı")
slug = models.SlugField(unique=True, editable=False, max_length=50)
class Worksite(models.Model):
firm = models.ForeignKey('Firm', verbose_name='Firma', related_name="worksites", on_delete=models.CASCADE)
name = models.CharField(unique=True, max_length=50, verbose_name="Şantiye Adı")
slug = models.SlugField(unique=True, editable=False, max_length=50)
class Subcontractor(models.Model):
worksite = models.ForeignKey('Worksite', on_delete=models.CASCADE)
firm = models.ForeignKey('Firm', related_name="subcontractors", on_delete=models.CASCADE)
Can the queryset code be written shorter?
views.py
class SubcontractorListView(ListView):
template_name = 'firm/subcontractor_list.html'
context_object_name = "firms"
def get_queryset(self):
ws = self.request.user.firm.worksites.values_list('id', flat=True)
ss = Subcontractor.objects.values_list('firm_id', flat=True).filter(worksite_id__in=ws)
return Firm.objects.filter(id__in=ss)
Do you have different and short solutions?
template
{% for firm in firms %}
<div class="btn btn-outline-secondary text-left button">{{ firm }} </div>
{% endfor %}

How can I check which subcclass the object is in a template?

Obligatory, I'm a django beginner and I don't understand why my code isn't working.
I'm trying to sort through a parent class in a view to get an object, then pass that object to a template. In the template, I have certain fields showing for each subclass and some which are inherited from the parent class.
I have tried using isinstance() in my template but it raised errors. After that I tried to add a static attribute to each subclass to check via an if statement in my template. When doing this, none of the subclass specific fields show. So I tried to set the attribute in the view and still had none of the subclass specific fields display.
Here are the parent object class and one of the subclasses (models):
class Chunk(models.Model):
name = models.CharField(max_length=250)
text = models.CharField(max_length=500)
images = models.FileField()
question = models.CharField(max_length=250)
expected_completion_time = models.IntegerField(default=1)
keywords = models.CharField(max_length=250, blank=True, null=True)
topic = models.CharField(max_length=250, blank=True, null=True)
course = models.CharField(max_length=250, blank=True, null=True)
def get_absolute_url(self):
return reverse('detail', kwargs={'pk':self.pk})
def __str__(self):
return self.name
class Concept(Chunk):
application = models.CharField(max_length=500)
subconcept1 = models.CharField(max_length=500, blank=True, null=True)
subconcept2 = models.CharField(max_length=500, blank=True, null=True)
subconcept3 = models.CharField(max_length=500, blank=True, null=True)
subconcept4 = models.CharField(max_length=500, blank=True, null=True)
subconcept5 = models.CharField(max_length=500, blank=True, null=True)
subconcept6 = models.CharField(max_length=500, blank=True, null=True)
subconcept7 = models.CharField(max_length=500, blank=True, null=True)
subconcept8 = models.CharField(max_length=500, blank=True, null=True)
subconcept9 = models.CharField(max_length=500, blank=True, null=True)
subconcept10 = models.CharField(max_length=500, blank=True, null=True)
conceptimage = models.FileField(blank=True, null=True)
#property
def mode(self):
return "concept"
Here is the view:
def startpomodoro(request):
key = getpriority(Chunk.objects.all())
object = Chunk.objects.get(id=key)
a = random() > 0.5
mode = str()
if isinstance(object, Problem):
if a:
mode = "problemoutline"
else:
mode = "problemfull"
elif isinstance(object, Concept):
mode = "concept"
elif isinstance(object, Formula):
mode = "formula"
elif isinstance(object, Code):
mode = "code"
context = dict(object=object, mode=mode)
return render(request, 'pomodoro/pomodorogo.html', context)
Here is the relevant part of the template:
<center>
<p>{{ object.text }}</p>
{% if mode == concept %}
<p>{{ object.application }}</p>
<p>{{ object.subconcept1 }}</p>
{% if object.subconcept2 %}
<p>{{ object.subconcept2 }}</p>
{% elif mode == formula %}
I don't understand why I haven't got any of these methods to work. I'm sure it's an issue in implementation on my part but I don't know what I'm doing incorrectly.
I think you have some unnecessary complications in your models, try a simplified model:
class SubConcept(models.Model):
name = models.CharField(max_length=200)
class Chunk(models.Model):
CHUNK_TYPES = [('P', 'Problem'),
('C', 'Concept'),
('I', 'Idea'),
('K', 'Code'),
('F', 'Formula')]
name = models.CharField(max_length=250)
text = models.CharField(max_length=500)
image = models.FileField()
question = models.CharField(max_length=250)
expected_completion_time = models.IntegerField(default=1)
keywords = models.CharField(max_length=250, blank=True, null=True)
topic = models.CharField(max_length=250, blank=True, null=True)
course = models.CharField(max_length=250, blank=True, null=True)
chunk_type = models.CharField(max_length=1, choices=CHUNK_TYPES)
application = models.CharField(max_length=200)
subs = models.ManyToManyField(SubConcept, blank=True, null=True)
def get_absolute_url(self):
return reverse('detail', kwargs={'pk':self.pk})
def __str__(self):
return '{}'.format(self.name or '')
#property
def mode(self):
return dict(CHUNK_TYPES)[self.chunk_type]
Now, your view is quite simple (I'm ignoring the getpriority method because I have no idea what it does):
def pomodoro(request):
obj = get_object_or_404(Chunk, pk=1)
return render(request, 'foo.html', {'obj': obj})
Here is your template:
<center>
<p>{{ obj.text }}</p>
{% if obj.mode == 'Concept' %}
<p>{{ object.application }}</p>
{% for sub in obj.subs.all %}
<p>{{ sub.name }}</p>
{% endfor %}
{% elif obj.mode == 'Formula' %}
...
</center>
On one Django project I was working on we had a similar issue to this with inherited model classes. The solution we used was to add a type to the parent class.
class Chunk(models.Model):
CONCEPT_TYPES = (
('Problem', 'Problem'),
('Concept', 'Concept'),
('Formula', 'Formula'),
('Code', 'Code'),
)
concept_type = models.CharField(max_length=7, choices=CONCEPT_TYPES)
...
Then in our templates we would do something like:
{% if object.concept_type == 'Concept' %}
<p>{{ object.concept.application }}</p>
<p>{{ object.concept.subconcept1 }}</p>
{% elif object.type == 'Problem' %}
...
{% endif %}
Things to note are that in the future I wouldn't structure my database like this again unless there was a very compelling reason and there are almost certainly better solutions.
You should also try changing your if statement in views.py to something like:
if object.problem:
...
elif object.concept:
....
This might mean that you don't need to put a type row in your models.

Trying to search for record in Django

Trying to build a simple search page in django.
I have a model:
class Person(models.Model):
ROLE_CHOICES = (
('Eng', 'Engineering'),
('Product', 'Product'),
('QA', 'QA'),
('Mrkt', 'Marketing'),
('Fin/Off', 'Finance / Office'), \
('Care', 'Care'),
('Sales', 'Sales'),
)
ROLE_TYPE = (
('Full', 'Full Time'),
('CooP', 'Co-Op'),
('Part', 'Part Time'),
('Intern', 'Intern'),
)
first_name = models.CharField(blank=True, max_length=100)
last_name = models.CharField(blank=True, max_length=100)
date_added = models.DateField(auto_now_add=True)
date_start = models.DateField(auto_now=False)
date_leaving = models.DateField(auto_now=False)
role = models.CharField(max_length=100, default = "", choices = ROLE_CHOICES)
manager = models.ForeignKey('self', limit_choices_to = {'is_manager': True}, null=True, blank=True)
title = models.CharField(blank=True, max_length=100)
role_type = models.CharField(max_length=100, default = "", choices = ROLE_TYPE)
laptop_needed = models.BooleanField(default=True)
phone_needed = models.BooleanField(default=True)
desk_loco = models.CharField(blank=True, max_length=100)
mail_lists = models.ManyToManyField(Mailists, blank=True, null=True)
notes = models.CharField(blank=True, max_length=500)
is_manager = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_leaving = models.BooleanField(default=False)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
I have this view:
def search_people(request):
if request.method == 'POST':
search_text = request.POST['search']
else:
search_text = ''
persons=Person.objects.filter(last_name__contains=search_text)
return render(request, 'hireterm/search.html', {'persons': persons})
Which grabs from this form:
<form class="searchfield" method="get" action="/search/" autocomplete="off">
Search: <input type="text" name="search">
<input id="searchbuttonmain" type="submit" class="subbtn" value="Search">
</form>
And renders this page:
{% if persons.count %}
{% for p in persons %}
<p>{{ p.last_name }}<p>
{% endfor %}
{% else %}
<p> OH NOES <p>
{% endif %}
It always return all of the Perosns records, not the ones filtered by last name and I am not sure why. I am sure I have missed something trivial, but I can't see it. Thanks for your input.
your form method is GET, but it should be POST. This causes it to hit the else-part of the if-statement. Thus Person objects containing the empty string in their last_name field are selected, but this matches all of the objects.

Categories

Resources