I'm developing a django app to keep track of orders and products in my laboratory. I have an Order model that I create instances from with a form that fills some of its fields (but not all) and creates an object.
I've also created an UpdateForm to update the blank fields once the order arrives to the lab. This update form has just one field (storage location), but I want this form to automatically set the status of the order to "received" and populate the "received_by" field with the logged user and "received_date" with the dateTime when the form is sent..
While writing this I just thought I could create a different model for Receive and relate it to the Order model via OnetoOne, would that be a proper solution?
How my code looks like:
#models.py-------------------------------------------------------------
class Pedido(models.Model):
nombre = models.CharField(max_length=40, help_text=_('Nombre del producto.'))
referencia = models.CharField(max_length=20, help_text=_('Referencia del fabricante.'))
cpm = models.CharField(max_length=20, default ='A la espera.',help_text=_('Código del CPM asignado a este pedido.'), null = True, blank = True, verbose_name = _('CPM'))
fecha = models.DateTimeField(auto_now_add=True)
unidades = models.IntegerField(default = 1)
usuario = models.ForeignKey(User, on_delete=models.CASCADE, blank = True)
autogestion = models.BooleanField(default = False, verbose_name='Autogestión', help_text = _("Marca esta casilla si vas a procesar tu mismo el pedido."))
usuario_recepcion = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='recepcion')
fecha_recepcion = models.DateTimeField(blank=True, null=True)
ESTADO_PEDIDO = (
('n', _('Pendiente')),
('p', _('Proforma solicitada')),
('c', _('CPM solicitado')),
('v', _('Para validar')),
('r', _('Recibido'))
)
estado = models.CharField(
max_length=1,
choices=ESTADO_PEDIDO,
blank=False,
default='n',
help_text=_('Estado del pedido'),
)
fabricante = models.ForeignKey('Fabricante', null = True, on_delete=models.SET_NULL)
centro_gasto = models.ForeignKey('CentroGasto', null = True, on_delete=models.SET_NULL, verbose_name = _('Centro de Gasto'))
almacen = models.ForeignKey('Almacen', null = True, on_delete=models.SET_NULL, blank = True)
direccion = models.ForeignKey('Direccion', default = 'CIBM', null = True, on_delete=models.SET_NULL, verbose_name = _('Dirección de entrega'))
codigo = models.CharField(max_length=20, blank=True, default=keygen())
#views.py----------------------------------------------------------
class PedidoListView(LoginRequiredMixin, generic.ListView):
model = Pedido
ordering = ['-fecha']
class PedidoDetailView(LoginRequiredMixin, generic.DetailView):
model = Pedido
#login_required
def Guia(request):
return render(request, 'guia.html')
#login_required
def add_pedido(request):
if request.method == "POST":
form = PedidoForm(request.POST)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.usuario = request.user
model_instance.save()
return redirect('/')
else:
form = PedidoForm()
return render(request, "nuevo_pedido.html", {'form': form})
class RecepcionUpdate(LoginRequiredMixin, UpdateView):
model = Pedido
fields = ['almacen']
template_name_suffix = '_recepcionar'
#forms.py-----------------------------------------------------------------
class PedidoForm(ModelForm):
def clean_usuario(self):
if not self.cleaned_data['usuario']:
return User()
return self.cleaned_data['user']
class Meta:
model = Pedido
exclude = ['codigo', 'fecha', 'cpm', 'almacen', 'estado', 'usuario']
If you are trying to change predefined class in Django, it's always possible to overwrite it. For example, you could extend the form_valid method:
class RecepcionUpdate(LoginRequiredMixin, generic.UpdateView):
model = Pedido
fields = ['almacen']
template_name_suffix = '_recepcionar'
def form_valid(self, form):
instance = form.save(commit=False)
instance.user = self.request.user
super(RecepcionUpdate, self).save(form)
Note: I have not tested this, it is probable that instead of calling super().save(form) you should return super().form_valid(form). Anyways, I'm sure that with this example you'll be able to find plenty of code snippets matching your Django version.
Related
Model.py
class Branch(models.Model): # Branch Master
status_type = (
("a",'Active'),
("d",'Deactive'),
)
name = models.CharField(max_length=100, unique=True)
suffix = models.CharField(max_length=8, unique=True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.name
class Vendor(models.Model):
status_type = (
("a",'Active'),
("d",'Deactive'),
)
branch = models.ManyToManyField(Branch)
company = models.CharField(max_length=200)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=11, unique = True)
email = models.EmailField(max_length=254, unique = True)
gst = models.CharField(max_length=15, unique = True)
pan_no = models.CharField(max_length=10, unique = True)
add_1 = models.CharField(max_length=50, null=True, blank = True)
add_2 = models.CharField(max_length=50, null=True, blank = True)
add_3 = models.CharField(max_length=50, null=True, blank = True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.company
form.py
i want save like created_by field
class VendorForm(ModelForm):
class Meta:
model = Vendor
fields = 'all'
exclude = ['created_by', 'branch']
widgets = {
'company':forms.TextInput(attrs={'class':'form-control'}),
'name':forms.TextInput(attrs={'class':'form-control'}),
'phone':forms.TextInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
'gst':forms.TextInput(attrs={'class':'form-control'}),
'pan_no':forms.TextInput(attrs={'class':'form-control'}),
'add_1':forms.TextInput(attrs={'class':'form-control'}),
'add_2':forms.TextInput(attrs={'class':'form-control'}),
'add_3':forms.TextInput(attrs={'class':'form-control'}),
'Remark':forms.Textarea(attrs={'class':'form-control','rows':'2'}),
'status':forms.Select(attrs={'class':'form-control'}),
}
Views.py
I have pass branch in session.
I want to save with branch which is many to many field
def Add_Vendor(request): # for vendor add
msg = ""
msg_type = ""
branch_id = request.session['branch_id']
branch_data = Branch.objects.get(id = branch_id)
form = ""
if request.method == "POST":
try:
form = VendorForm(request.POST)
if form.is_valid:
vendor_add = form.save(commit=False)
vendor_add.created_by = request.user
vendor_add.instance.branch = branch_data.id
vendor_add.save()
form.save_m2m() # for m to m field save
msg_type = "success"
msg = "Vendor Added."
form = VendorForm(initial={'branch':branch_id})
except:
msg_type = "error"
msg = str(form.errors)
print(msg)
else:
form = VendorForm(initial={'branch':branch_id})
context = {
'form':form,
'branch_data':branch_data,
'msg_type':msg_type,
'msg':msg,
'btn_type':'fa fa-regular fa-plus',
'form_title':'Vendor Form',
'tree_main_title':'Vendor',
'v_url':'vendor_page',
'tree_title':'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html',context)
I would advise not to work with commit=False in the first place:
def Add_Vendor(request): # for vendor add
branch_id = request.session['branch_id']
branch_data = get_object_or_404(Branch, pk=branch_id)
if request.method == 'POST':
form = VendorForm(request.POST, request.FILES)
if form.is_valid():
form.instance.created_by = request.user
form.instance.branch = branch_data.id
vendor_add = form.save()
vendor_add.branch.add(branch_data)
return redirect('name-of-some-view')
else:
form = VendorForm()
context = {
'form': form,
'branch_data': branch_data,
'btn_type': 'fa fa-regular fa-plus',
'form_title': 'Vendor Form',
'tree_main_title': 'Vendor',
'v_url': 'vendor_page',
'tree_title': 'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html', context)
You can simplify your form by automatically adding form-control to each widget:
class VendorForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
attrs = field.widget.attrs
attrs['class'] = attrs.get('class', '') + ' form-control'
class Meta:
model = Vendor
exclude = ['created_by', 'branch']
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: You can set a field editable=False [Django-doc]. Then the field does not show up in the ModelForms and ModelAdmins by default. In this case for example with created_by.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: Please do not pass messages manually to the template. Django has the messages framework [Django-doc], which allows to add messages to the request, which will then be delivered the next time a template renders these messages. This makes delivering multiple messages convenient, as well as setting different log levels to the messages.
I have already posted (see link below) to 'valid' my ER diagram.
I try to develop a form based on 'trought' model with nested inlineformset.
It works when I define fields in the UtilisateurCreateView class but I want to customize the 'trought' parent's form to be able to:
set initial pro_ide value with value send by GET
hidden this pro_ide field
customize uti_ide field label
So I define a UtilisateurProjetCreateForm based on the 'throught' model like I'm used to do but I got an error:
Cannot assign "'Slater, Kelly (k.slater#surf.com)'": "UtilisateurProjet.uti_ide" must be a "Utilisateur" instance.
moreover, as this form is based on 'throught' model, I am not sure I should define forms.ChoiceField...
models.py
class Projet(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
pro_ide = models.AutoField(primary_key = True)
# utilisateurs = models.ManyToManyField(Utilisateur, through='UtilisateurProjet')
pro_nom = models.IntegerField("Nom du projet")
pro_log = models.CharField("Log utiisateur", max_length=20, null=True, blank=True)
pro_dat = models.DateTimeField("Date log",auto_now_add=True)
pro_act = models.IntegerField("Projet en cours ?", null=True, blank=True)
class Meta:
db_table = 'tbl_pro'
verbose_name_plural = 'Projets'
ordering = ['pro_ide']
permissions = [
('can_add_project','Can add project'),
]
def __str__(self):
return f"{self.pro_nom}"
class Utilisateur(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
uti_ide = models.AutoField(primary_key = True)
# pro_ide = models.ForeignKey(Projet, on_delete = models.CASCADE) # related project
projets = models.ManyToManyField(Projet, through='UtilisateurProjet')
uti_nom = models.CharField("Nom", max_length=20)
uti_pre = models.CharField("Prénom", max_length=20)
uti_mai = models.CharField("Email", max_length=40)
uti_sit = models.CharField("Equipe", max_length=20, null=True, blank=True)
uti_pro = models.CharField("Fonction/profil", max_length=200, null=True, blank=True)
uti_dem_dat = models.DateTimeField("Date demande",auto_now_add=True, null=True, blank=True)
uti_val = models.IntegerField("Demande validée ?", null=True, blank=True)
uti_val_dat = models.DateTimeField("Date validation",null=True, blank=True)
uti_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
uti_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
class Meta:
db_table = 'tbl_uti'
verbose_name_plural = 'Utilisateurs'
ordering = ['uti_ide']
def __str__(self):
return f"{self.uti_nom}, {self.uti_pre} ({self.uti_mai})"
class UtilisateurProjet(models.Model):
_safedelete_policy = SOFT_DELETE_CASCADE
pro_uti_ide = models.AutoField(primary_key = True)
uti_ide = models.ForeignKey(Utilisateur, on_delete=models.CASCADE)
pro_ide = models.ForeignKey(Projet, on_delete=models.CASCADE)
class Meta:
db_table = 'tbl_pro_uti'
class Application(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
app_ide = models.AutoField(primary_key = True)
# uti_ide = models.ForeignKey(Utilisateur, on_delete = models.CASCADE) # related utilisateur
pro_uti_ide = models.ForeignKey(UtilisateurProjet, on_delete = models.CASCADE) # related utilisateur-projet
app_app_nom = models.IntegerField("Nom application", null=True, blank=True)
app_dro = models.IntegerField("Droit sur application", null=True, blank=True)
app_sta = models.IntegerField("Statut (création/Modification/Suppression", null=True, blank=True)
app_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
app_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
class Meta:
db_table = 'tbl_app'
verbose_name_plural = 'Applications'
ordering = ['app_ide']
views.py
# https://stackoverflow.com/questions/29981690/django-form-validation-on-class-based-view
class UtilisateurCreateView(FormView):
template_name = 'project/utilisateurprojet_form.html'
form_class = UtilisateurProjetCreateForm
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data["utilisateur"] = self.request.user.username # nom de l'utilisateur connecté
data["projet"] = get_object_or_404(Projet, pro_ide = self.request.GET['projet'])
data["application"] = ApplicationFormset(self.request.POST)
else:
data["application"] = ApplicationFormset()
return data
def form_valid(self, form):
context = self.get_context_data()
application = context["application"]
self.object = form.save(commit=False)
self.object.uti_log = context["utilisateur"]
self.object.save()
if application.is_valid():
application.instance = self.object
application.save()
return super().form_valid(form)
def get_success_url(self):
return reverse("project:index")
forms.py
ApplicationFormset = inlineformset_factory(
UtilisateurProjet, Application,
fields=('app_app_nom','app_dro'),
widgets={
'app_app_nom': forms.Select(choices=NAME),
'app_dro': forms.Select(choices=ACCESS)
},
extra=3,
can_delete=True,
)
class UtilisateurProjetCreateForm(forms.ModelForm):
PROJETS = [(Projet.objects.get(pro_ide=1),'Coverage Africa'),]
UTILISATEURS = [(Utilisateur.objects.get(uti_ide=1),'Slater'),]
pro_ide = forms.ChoiceField(label = "Nom projet", widget = forms.Select, choices = PROJETS, initial = Projet.objects.get(pro_ide=1), disabled=True)
uti_ide = forms.ChoiceField(label = "Nom, prénom de l'utilisateur", widget = forms.Select, choices = UTILISATEURS)
class Meta:
model = UtilisateurProjet
fields = ('pro_ide','uti_ide')
related post
I had to use ModelChoiceFiled in my ModelForm:
class UtilisateurProjetCreateForm(forms.ModelForm):
PROJETS = Projet.objects.all()
UTILISATEURS = Utilisateur.objects.all()
pro_ide = forms.ModelChoiceField(queryset = PROJETS, label = "Nom projet", widget = forms.Select, initial = Projet.objects.get(pro_ide=1))
uti_ide = forms.ModelChoiceField(queryset = UTILISATEURS, label = "Nom, prénom de l'utilisateur", widget = forms.Select)
class Meta:
model = UtilisateurProjet
fields = ('pro_ide','uti_ide')
I have a model which is filled in different steps by different forms. Fields that are not filled in the first step need to be set Blank = True so you can submit the form. When I try to fill those fields later, the form lets the user leave them blank, which is undesirable. How can I make them mandatory in the subsequent forms?
I've tried implementing a Validation method (clean_almacen) like the one below, but it does nothing.
class RecepcionForm(ModelForm):
def clean_almacen(self):
data = self.cleaned_data['almacen']
# Check if the field is empty.
if data == '':
raise ValidationError(_('¡Seleccione un almacén!'))
return data
def clean_usuario(self):
if not self.cleaned_data['usuario_recepcion']:
return User()
return self.cleaned_data['usuario_recepcion']
class Meta:
model = Pedido
fields = ['almacen']
Also, setting the field Blank = False and null = True will make this work, but it will make mandatory to assign a value to the field when you edit the object in the admin page (which is undesirable too).
This is my code:
models.py
class Pedido(models.Model):
nombre = models.CharField(max_length=40, help_text=_('Nombre del producto.'))
referencia = models.CharField(max_length=20, help_text=_('Referencia del fabricante.'))
cpm = models.CharField(max_length=20, default ='A la espera.',help_text=_('Código del CPM asignado a este pedido.'), null = True, blank = True, verbose_name = _('CPM'))
fecha = models.DateTimeField(auto_now_add=True)
fecha_cpm = models.DateTimeField(blank=True, null=True, verbose_name=_('Fecha asignación CPM'))
unidades = models.IntegerField(default = 1)
usuario = models.ForeignKey(User, on_delete=models.CASCADE, blank = True)
autogestion = models.BooleanField(default = False, verbose_name='Autogestión', help_text = _("Marca esta casilla si vas a procesar tú mismo el pedido."))
usuario_recepcion = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='recepcion', verbose_name=_('Recepcionado por'))
fecha_recepcion = models.DateTimeField(blank=True, null=True)
ESTADO_PEDIDO = (
('n', _('Pendiente')),
('p', _('Proforma solicitada')),
('c', _('CPM solicitado')),
('v', _('Para validar')),
('r', _('Recibido')),
('b', _('Bloqueado')),
)
estado = models.CharField(
max_length=1,
choices=ESTADO_PEDIDO,
blank=False,
default='n',
help_text=_('Estado del pedido'),
)
fabricante = models.ForeignKey('Fabricante', null = True, on_delete=models.SET_NULL)
centro_gasto = models.ForeignKey('CentroGasto', null = True, on_delete=models.SET_NULL, verbose_name = _('Centro de Gasto'))
almacen = models.ForeignKey('Almacen', null = True, on_delete=models.SET_NULL, blank = True)
direccion = models.ForeignKey('Direccion', default = 'CIBM', null = True, on_delete=models.SET_NULL, verbose_name = _('Dirección de entrega'))
codigo = models.CharField(max_length=20, blank=True, default=keygen())
bloqueo = models.TextField(blank=True, verbose_name=_('Incidencias'), help_text = _('Anote las incidencias relacionadas con el pedido para que puedan ser solucionadas'))
views.py
#permission_required('gestion.puede_editar_cpm')
def añadir_cpm(request, pk):
instance = get_object_or_404(Pedido, id=pk)
if request.method == "POST":
form = CPMForm(request.POST, instance=instance)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.estado = 'v'
model_instance.fecha_cpm = datetime.now()
model_instance.save(update_fields=['estado', 'fecha_cpm', 'cpm'])
return redirect('/')
else:
form = CPMForm()
return render(request, "gestion/cpm_edit.html", {'form': form})
#permission_required('gestion.puede_editar_cpm')
def cpm_block(request, pk):
instance = get_object_or_404(Pedido, id=pk)
if request.method == "POST":
form = CPMBlockForm(request.POST, instance=instance)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.estado = 'b'
model_instance.save(update_fields=['estado', 'bloqueo'])
return redirect('/')
else:
form = CPMBlockForm()
return render(request, "gestion/cpm_block.html", {'form': form})
#login_required
def recepcion(request, pk):
instance = get_object_or_404(Pedido, id=pk)
if request.method == "POST":
form = RecepcionForm(request.POST, instance=instance)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.usuario_recepcion = request.user
model_instance.estado = 'r'
model_instance.fecha_recepcion = datetime.now()
model_instance.save(update_fields=['usuario_recepcion', 'almacen', 'fecha_recepcion', 'estado'])
return redirect('/')
else:
form = RecepcionForm()
return render(request, "gestion/pedido_recepcionar.html", {'form': form})
forms.py
class PedidoForm(ModelForm):
def clean_usuario(self):
if not self.cleaned_data['usuario']:
return User()
return self.cleaned_data['usuario']
class Meta:
model = Pedido
exclude = ['codigo', 'fecha', 'cpm', 'almacen', 'estado', 'usuario']
class RecepcionForm(ModelForm):
def clean_almacen(self):
data = self.cleaned_data['almacen']
# Check if a date is not in the past.
if data == '':
raise ValidationError(_('¡Seleccione un almacén!'))
return data
def clean_usuario(self):
if not self.cleaned_data['usuario_recepcion']:
return User()
return self.cleaned_data['usuario_recepcion']
class Meta:
model = Pedido
fields = ['almacen']
class CPMForm(ModelForm):
class Meta:
model = Pedido
fields = ['cpm']
class CPMBlockForm(ModelForm):
class Meta:
model = Pedido
fields = ['bloqueo']
I'm sorry for the long code, I don't know what could be useful or not. I hope you guys can help me.
Thanks in advance.
You would override the field definitions in the subsequent forms. You can do this declaratively:
class CPMForm(ModelForm):
cpm = forms.CharField(required=True, max_length=20, initial='A la espera.', help_text=_('Código del CPM asignado a este pedido.'), label=_('CPM'))
class Meta:
model = Pedido
fields = ['cpm']
or programmatically:
class CPMBlockForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['bloqueo'].required = True
class Meta:
model = Pedido
fields = ['bloqueo']
I need to populate two combos in a ModelForm, and I would like to initialize them with the current value of each foreign key.
My models are:
class Alumno(models.Model):
idalumno = models.AutoField(primary_key=True)
padre_idpadre = models.ForeignKey('Padre', models.DO_NOTHING, db_column='padre_idpadre', blank=True, null=True)
curso_idcurso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='curso_idcurso')
nombre = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'alumno'
class Curso(models.Model):
idcurso = models.IntegerField(primary_key=True)
nombrecurso = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'curso'
class Padre(models.Model):
idpadre = models.AutoField(primary_key=True)
socio = models.NullBooleanField(blank=True, null=True)
nombre = models.CharField(max_length=45, blank=True, null=True)
primerapellido = models.CharField(max_length=45, blank=True, null=True)
segundoapellido = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'padre'
This is my Form in forms.py:
class AlumnoForm(forms.ModelForm):
padre = PadreModelChoiceField(queryset=Padre.objects.all(), initial=**XXXXXXXXX**) #I would like to init here with the value of the FK
curso = CursoModelChoiceField(queryset=Curso.objects.all(), initial=**XXXXXXXXXX**) #And here too
class Meta:
model = Alumno
fields = ('nombre','padre','curso',)
labels = {
'nombre': 'Nombre',
'padre': 'Padre',
'curso': 'Curso',
}
In views.py
def alumno_editar(request, pk):
alumno = get_object_or_404(Alumno, pk=pk)
if request.method == "POST":
form = AlumnoForm(request.POST, instance=alumno)
if form.is_valid():
alumno = form.save(commit=False)
alumno.save()
return redirect('alumno_listar')
else:
form = AlumnoForm(instance=alumno)
return render(request, 'administration/alumno_editar.html', {'form': form})
What should I write in the part XXXXXXXXXX of the code.
It could be misconception but I'm think is a common operation, althought I don't find it.
In models.py:
class Client(AbstractBaseUser):
username = models.CharField(max_length=32, unique=True)
email = models.EmailField('email address', unique=True, db_index=True)
avatar = models.ImageField('avatar', upload_to='avatars')
id = id(object)
class Order(models.Model):
class Meta():
db_table = 'order'
short_desc = models.CharField(max_length=30)
subject = models.ForeignKey(Subject, blank=True)
user_id = models.ForeignKey('Client', to_field='id', related_name='client_id', default='0', blank=True)
performer_id = models.ForeignKey('Client', to_field='id', related_name='performer_id', default='0', blank=True)
worktype = models.ForeignKey(Type, blank=True)
level = models.IntegerField(default=0, blank=True)
readiness = models.BooleanField(default=False, blank=True)
description = models.TextField(max_length=2000, blank=True)
file = models.FileField(upload_to='orderfiles', blank=True)
#maxdate = models.DateField(blank=True)
addate = models.DateField(auto_now=True, blank=True)
price = models.IntegerField(max_length=10, blank=True)
responses = models.IntegerField(blank=True)
In forms.py:
class AddOrderForm(forms.ModelForm):
short_desc = forms.CharField(widget=forms.TextInput,label="Краткое описание(послужит именем)")
subject = forms.ModelChoiceField(queryset=Subject.objects.all(), label="Предмет")
worktype = forms.ModelChoiceField(queryset=Type.objects.all(), label="Тип")
level = forms.IntegerField(widget=forms.TextInput,label="Уровень сложности (от 1 до 5)")
description = forms.CharField(widget=forms.TextInput,label="Полное описание")
#maxdate = forms.DateField(widget=forms.TextInput,label="maxdate")
price = forms.IntegerField(widget=forms.TextInput,label="Ваша цена")
responses = forms.IntegerField(widget=forms.TextInput,label="Кол-во ответов на заказ")
class Meta:
model = Order
fields = ['short_desc', 'level', 'description', 'price', 'responses', 'subject', 'worktype']
In views.py:
def addorder(request, user_id):
"""
Adding Order view
"""
if request.POST:
form = AddOrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
return redirect('/')
auth1 = auth.get_user(request).username
return render_to_response('customer.html', { 'form': form,'username' : auth1}, context_instance=RequestContext(request))
I need the field user_id in class Order to be initialized immediately after adding order(). Where should I do it and in which way? I need something like this logic: Client adds an Order through AddOrderForm and then user_id field of just added object of class Order has to be initialized with an object of class Client, whose id equals user_id in parameters of addorder() function.
You can do that using commit=False while saving the form. This is typical way of saving the object using model form which has fewer fields.
def addorder(request, user_id):
"""
Adding Order view
"""
if request.POST:
form = AddOrderForm(request.POST)
if form.is_valid():
order = form.save(commit=false)
order.client_id = Client.objects.get(id=user_id)
order.save()
return redirect('/')
else:
return redirect('/')
auth1 = auth.get_user(request).username
return render_to_response('customer.html',
{ 'form': form,'username' : auth1},
context_instance=RequestContext(request))
Disclaimer: Handle errors e.g. Client.objects.get() may fail. Use appropriate fields to search.